@embedpdf-editor/react-chapter-viewer 0.2.1 → 0.2.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.
- package/README.md +159 -146
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +64 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +636 -503
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),a=require("@embedpdf/core/react"),s=require("@embedpdf/plugin-interaction-manager/react"),i=require("@embedpdf/plugin-rotate/react"),r=require("@embedpdf/plugin-selection/react"),o=require("@embedpdf/plugin-selection"),n=require("@embedpdf/plugin-annotation/react"),h=require("@embedpdf/plugin-redaction/react"),l=require("@embedpdf/core"),d=require("@embedpdf/models"),c=require("@embedpdf/plugin-document-manager"),u=require("@embedpdf/plugin-render/react");require("@embedpdf/plugin-tiling/react");const p=require("@embedpdf/plugin-annotation"),g=require("@embedpdf/plugin-interaction-manager"),f=require("@embedpdf/plugin-render"),m=require("@embedpdf/plugin-rotate"),v=require("@embedpdf/plugin-history"),b=require("@embedpdf/plugin-redaction"),P=require("@embedpdf/plugin-form"),w=require("@embedpdf/plugin-stamp"),I=require("@embedpdf/plugin-signature"),y=require("@embedpdf/plugin-commands"),C=require("@embedpdf/plugin-i18n"),M=require("@embedpdf/plugin-ui"),S=require("@embedpdf/engines/react"),x={kind:"first-wins"};function L(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const k=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=x,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??x,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=x){const a=function(t,e=x){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,L(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};k.id="chapter-manager";let D=k;const T=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(D.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};T.id="chapter-scroll";let z=T;function O({item:s,renderPage:i,renderPlaceholder:r}){const o=function(t,s){const i=a.useDocumentState(t),r=e.useMemo(()=>!(!i||"loaded"!==i.status||!i.document)&&Boolean(i.document.pages[s]),[i,s]),[o,n]=e.useState(r);return e.useEffect(()=>{n(r)},[r]),e.useEffect(()=>{if(r)return;if(!i||"loaded"!==i.status||!i.document)return;let t=!1,e=0;const a=()=>{var r;t||((null==(r=i.document)?void 0:r.pages[s])?n(!0):++e<120&&requestAnimationFrame(a))};return requestAnimationFrame(a),()=>{t=!0}},[i,s,r]),o}(s.chapterId,s.localPageIndex);return t.jsx("div",{"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:{position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:o?"#fff":"#f3f4f6",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"},children:o?i(s):(null==r?void 0:r(s))??t.jsx("div",{style:{display:"flex",width:"100%",height:"100%",alignItems:"center",justifyContent:"center",color:"#9ca3af",fontSize:"12px"},children:"Loading chapter…"})})}function G({renderPage:s,renderPlaceholder:i,className:r,style:o,...n}){const{provides:h}=a.useCapability(z.id),{provides:l}=a.useCapability(c.DocumentManagerPlugin.id),d=e.useRef(null),[u,p]=e.useState(null);e.useEffect(()=>{if(!h)return;const t=d.current;h.registerViewport(t);const e=t=>p(t),a=h.onLayoutChange(e),s=null==l?void 0:l.onDocumentOpened(()=>e(h.getLayout())),i=null==l?void 0:l.onDocumentClosed(()=>e(h.getLayout()));return()=>{a(),null==s||s(),null==i||i(),h.registerViewport(null)}},[h,l]);const g=(null==u?void 0:u.totalHeight)??0,f=(null==u?void 0:u.totalWidth)??0;return t.jsx("div",{...n,ref:d,"data-chapter-scroll-viewport":"",className:r,style:{overflow:"auto",position:"relative",width:"100%",height:"100%",...o},children:t.jsx("div",{style:{position:"relative",width:`${f}px`,height:`${g}px`,margin:"0 auto"},children:null==u?void 0:u.items.map(e=>t.jsx(O,{item:e,renderPage:s,renderPlaceholder:i},e.globalPageIndex))})})}function A({chapterId:e,localPageIndex:a,scale:s,dpr:i,className:r}){return t.jsx(u.RenderLayer,{documentId:e,pageIndex:a,scale:s,dpr:i,className:r,style:{pointerEvents:"none"}})}const N={kind:"first-wins"};function E(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let R=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const V=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=N,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??N,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=N){const a=function(t,e=N){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,E(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new R(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};V.id="chapter-manager";let _=V;const U={kind:"first-wins"};function F(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let q=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const B=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=U,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??U,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=U){const a=function(t,e=U){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,F(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new q(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};B.id="chapter-manager";let j=B;const W=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(j.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};W.id="chapter-scroll";let H=W;const Y=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(H.id),this.chapterManager=this.registry.getPlugin(_.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:X(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Y.id="note";let K=Y;function X(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Z({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,color:l="#f59e0b",ui:d,className:c,style:u}){const{plugin:p}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(K.id);return{plugin:e,isLoading:!1,ready:(null==e?void 0:e.ready())??Promise.resolve()}})(),{provides:g}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{provides:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(K.id);return(null==e?void 0:e.provides)?{provides:e.provides(),isLoading:!1,ready:e.ready()}:{provides:null,isLoading:!1,ready:Promise.resolve()}})(),[f,m]=e.useState([]),[v,b]=e.useState(null),[P,w]=e.useState(null);if(e.useEffect(()=>{if(g)return g.onNotesChange(t=>{m(t.filter(t=>t.chapterId===s&&t.localPageIndex===i))})},[g,s,i]),e.useEffect(()=>{if(!P)return;const t=t=>{var e;const a=t.target;(null==(e=a.closest)?void 0:e.call(a,`[data-note-marker-zone="${P}"]`))||(w(null),b(null))};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[P]),!g||0===f.length||!r||!o)return null;const I=n/r,y=h/o,C=(null==d?void 0:d.iconSize)??16,M=(null==d?void 0:d.highlightColor)??"rgba(245, 158, 11, 0.08)";return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:25,...u},children:f.map(e=>{const a=v===e.noteId,s=P===e.noteId,i=a||s,{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:I,sy:y,cssPageWidth:n,iconSize:C}),h=function(t,e,a){let s=1/0,i=1/0,r=-1/0,o=-1/0;for(const n of t)s=Math.min(s,n.origin.x*e),i=Math.min(i,n.origin.y*a),r=Math.max(r,(n.origin.x+n.size.width)*e),o=Math.max(o,(n.origin.y+n.size.height)*a);return{left:s,top:i,width:r-s,height:o-i}}(e.rectsPdfCoord,I,y),c=s?72:0,u=Math.max(0,Math.min(h.left,r)-8),f=Math.max(0,Math.min(h.top,o)-8),m=Math.min(n,Math.max(h.left+h.width,r+C)+8)-u,S=Math.max(h.top+h.height,o+C+6+c)+8-f;return t.jsxs("div",{children:[e.rectsPdfCoord.map((a,s)=>t.jsx("div",{style:{position:"absolute",left:a.origin.x*I+"px",top:a.origin.y*y+"px",width:a.size.width*I+"px",height:a.size.height*y+"px",background:M,borderRadius:"2px",pointerEvents:"auto",cursor:"default"},onMouseEnter:()=>b(e.noteId)},`${e.noteId}-bg-${s}`)),i&&t.jsxs("div",{"data-note-marker-zone":e.noteId,style:{position:"absolute",left:`${u}px`,top:`${f}px`,width:`${m}px`,height:`${S}px`,pointerEvents:"auto",zIndex:26},onMouseEnter:()=>b(e.noteId),onMouseLeave:()=>{P!==e.noteId&&b(null)},children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"笔记","aria-label":"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:d.renderIcon({note:e})}):t.jsx("button",{type:"button",title:"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,border:"none",borderRadius:"50%",background:l,color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":"笔记",children:"💬"}),s&&((null==d?void 0:d.renderMenuActions)?t.jsx("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto"},onMouseDown:t=>t.stopPropagation(),children:d.renderMenuActions({note:e,onEdit:()=>{w(null),b(null),null==p||p.requestEdit(e.noteId)},onDelete:()=>{w(null),b(null),g.deleteNote(e.noteId)}})}):t.jsxs("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto",minWidth:"80px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onMouseDown:t=>t.stopPropagation(),children:[t.jsx("button",{type:"button",style:Q,onClick:t=>{t.stopPropagation(),w(null),b(null),null==p||p.requestEdit(e.noteId)},children:"编辑"}),t.jsx("button",{type:"button",style:{...Q,color:"#dc2626"},onClick:t=>{t.stopPropagation(),w(null),b(null),g.deleteNote(e.noteId)},children:"删除"})]}))]})]},e.noteId)})})}const Q={display:"block",width:"100%",padding:"6px 10px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#334155",cursor:"pointer",textAlign:"left"},J={kind:"first-wins"};function tt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let et=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const at=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=J,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??J,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=J){const a=function(t,e=J){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,tt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new et(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};at.id="chapter-manager";let st=at;const it={kind:"first-wins"};function rt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ot=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const nt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=it,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??it,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=it){const a=function(t,e=it){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,rt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ot(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};nt.id="chapter-manager";let ht=nt;const lt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ht.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};lt.id="chapter-scroll";let dt=lt;function ct(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function ut(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function pt(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??ct(i),n=e.markerAnchor??ct(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(ut(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const gt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(dt.id),this.chapterManager=this.registry.getPlugin(st.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(pt(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};gt.id="paragraph-bookmark";let ft=gt;function mt({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,onBookmarkClick:l,ui:d,className:c,style:u}){const{provides:p}=a.useCapability(ft.id),[g,f]=e.useState([]),[m,v]=e.useState(null),b=e.useRef(null);if(e.useEffect(()=>{if(!p)return;const t=()=>{f(p.listBookmarks().filter(t=>t.anchor.chapterId===s&&t.anchor.localPageIndex===i))};return t(),p.onBookmarksChange(t)},[p,s,i]),e.useEffect(()=>{if(!m)return;const t=t=>{var e;(null==(e=b.current)?void 0:e.contains(t.target))||v(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[m]),!p||0===g.length||!r||!o)return null;const P=n/r,w=h/o,I=(null==d?void 0:d.iconSize)??16;return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",...u},children:g.map(e=>{var a;const s=(null==(a=e.anchor.rectsPdfCoord)?void 0:a.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord],i=e.anchor.markerAnchor??{x:e.anchor.rectPdfCoord.origin.x+e.anchor.rectPdfCoord.size.width,y:e.anchor.rectPdfCoord.origin.y+e.anchor.rectPdfCoord.size.height},{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:i,lineRects:s,sx:P,sy:w,cssPageWidth:n,iconSize:I}),h=Math.max(0,r-6),c=Math.max(0,o-6);return t.jsxs("div",{style:{position:"absolute",left:`${h}px`,top:`${c}px`,width:`${I+12}px`,height:`${I+12}px`,pointerEvents:"auto",zIndex:20},onMouseDown:t=>t.stopPropagation(),children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:e.label,"aria-label":`bookmark ${e.label}`,style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},children:d.renderIcon({bookmark:e})}):t.jsx("button",{type:"button",title:e.label,onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":`bookmark ${e.label}`,children:"🔖"}),m===e.id&&t.jsx("div",{ref:b,style:{position:"absolute",left:"6px",top:"-36px",zIndex:30,pointerEvents:"auto",minWidth:"88px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onClick:t=>t.stopPropagation(),children:t.jsx("button",{type:"button",style:{width:"100%",padding:"6px 8px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#dc2626",cursor:"pointer",textAlign:"left"},onClick:()=>{p.requestRemoveBookmark(e.id).then(t=>{t&&v(null)})},children:"删除书签"})})]},e.id)})})}function vt(t){return t.chapterId}function bt(t,e){t.wait(e,()=>{})}const Pt="note",wt={id:Pt,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},It={kind:"first-wins"};function yt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ct=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Mt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=It,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??It,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=It){const a=function(t,e=It){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,yt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ct(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Mt.id="chapter-manager";let St=Mt;const xt={kind:"first-wins"};function Lt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $t=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const kt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=xt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??xt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=xt){const a=function(t,e=xt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Lt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $t(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};kt.id="chapter-manager";let Dt=kt;const Tt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Dt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Tt.id="chapter-scroll";let zt=Tt;const Ot=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(zt.id),this.chapterManager=this.registry.getPlugin(St.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:At(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Ot.id="note";let Gt=Ot;function At(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const Nt={manifest:wt,create:t=>new Gt(Pt,t),reducer:t=>t,initialState:{}},Et="paragraph-bookmark",Rt={id:Et,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Vt={kind:"first-wins"};function _t(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ut=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ft=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Vt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Vt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Vt){const a=function(t,e=Vt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,_t(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ut(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ft.id="chapter-manager";let qt=Ft;const Bt={kind:"first-wins"};function jt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Wt{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Ht=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Bt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Bt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Bt){const a=function(t,e=Bt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,jt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Wt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ht.id="chapter-manager";let Yt=Ht;const Kt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Yt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Kt.id="chapter-scroll";let Xt=Kt;function Zt(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function Qt(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Jt(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function te(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Qt(i),n=e.markerAnchor??Qt(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Jt(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const ee=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Xt.id),this.chapterManager=this.registry.getPlugin(qt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(te(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};ee.id="paragraph-bookmark";let ae=ee;const se={manifest:Rt,create:t=>new ae(Et,t),reducer:t=>t,initialState:{}};function ie({item:s,pdfPageWidth:i,pdfPageHeight:r,cssPageWidth:n,cssPageHeight:h,hoverUi:l}){const d=vt(s),{provides:c}=a.useCapability(o.SelectionPlugin.id),{provides:u}=a.useCapability(ae.id),p=e.useRef(null),[g,f]=e.useState(null),[m,v]=e.useState(null),[b,P]=e.useState(null),w=(null==l?void 0:l.iconSize)??16;e.useEffect(()=>{if(!c)return;const t=c.forDocument(d),e=()=>{const e=t.getState().geometry[s.localPageIndex];e&&f(e)},a=t.onSelectionChange(e);let i=!1;const r=()=>{if(!i){try{if(e(),t.getState().geometry[s.localPageIndex])return}catch{}requestAnimationFrame(r)}};return r(),()=>{i=!0,a()}},[c,d,s.localPageIndex]);const I=b??m;e.useEffect(()=>{if(!g||!i)return;const t=t=>{if(b)return;if(c)try{if(c.forDocument(d).getState().selecting)return void v(null)}catch{}const e=p.current;if(!e)return;const a=e.getBoundingClientRect();if(t.clientX<a.left||t.clientX>a.right||t.clientY<a.top||t.clientY>a.bottom)return void v(null);const s=function(t,e){const a=o.glyphAt(t,e);if(a<0)return null;const s=o.expandToLineBoundary(t,a);if(!s)return null;const i=o.rectsWithinSlice(t,s.from,s.to);return 0===i.length?null:{lineRects:i,charFrom:s.from,charTo:s.to}}(g,{x:(t.clientX-a.left)/(n/i),y:(t.clientY-a.top)/(h/r)});v((null==s?void 0:s.lineRects)??null)};return document.addEventListener("mousemove",t),()=>document.removeEventListener("mousemove",t)},[g,i,r,n,h,c,d,b]);const y=(null==I?void 0:I.length)?function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Zt(i),rectsPdfCoord:i,markerAnchor:Qt(i)}}(s.chapterId,s.localPageIndex,I,{globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber}):null,C=y&&(null==u?void 0:u.listBookmarks().some(t=>te(t.anchor,y))),M=e.useCallback(()=>{u&&y&&!C&&(u.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:y}),v(null),P(null))},[u,y,C]);if(!u||!i||!r)return null;const S=n/i,x=h/r,L=null==I?void 0:I[I.length-1],$=L?Math.min((L.origin.x+L.size.width)*S+6,Math.max(0,n-w-2)):0,k=L?L.origin.y*x+(L.size.height*x-w)/2:0,D=L?Math.max(0,(L.origin.x+L.size.width)*S-4):0,T=L?Math.max(0,L.origin.y*x-4):0;return t.jsx("div",{ref:p,style:{position:"absolute",inset:0,zIndex:14,pointerEvents:"none"},children:I&&L&&!C&&t.jsx("div",{style:{position:"absolute",left:`${D}px`,top:`${T}px`,width:`${w+20}px`,height:`${L.size.height*x+w+12}px`,pointerEvents:"auto"},onMouseEnter:()=>P(I),onMouseLeave:()=>P(null),children:(null==l?void 0:l.renderAddIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-D+"px",top:k-T+"px",width:w,height:w,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:l.renderAddIcon()}):t.jsx("button",{type:"button",title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-D+"px",top:k-T+"px",width:`${w}px`,height:`${w}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",lineHeight:1,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:"🔖"})})})}const re={position:"relative",height:"100%",width:"100%"},oe={height:"100%",width:"100%"},ne={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},he={highlight:d.PdfAnnotationSubtype.HIGHLIGHT,underline:d.PdfAnnotationSubtype.UNDERLINE,squiggly:d.PdfAnnotationSubtype.SQUIGGLY,strikeout:d.PdfAnnotationSubtype.STRIKEOUT};function le(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function de(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}const ce=[{id:"highlight",label:"高亮背景",icon:t.jsx(fe,{})},{id:"underline",label:"下划线",icon:t.jsx(me,{})},{id:"squiggly",label:"波浪线",icon:t.jsx(ve,{})},{id:"strikeout",label:"删除线",icon:t.jsx(be,{})},{id:"note",label:"添加笔记",icon:t.jsx(Pe,{})}];function ue({placementAbove:e,anchorHeight:a,onAction:s,hiddenBuiltinActions:i=[],extraActions:r=[]}){const o=new Set(i),n=ce.filter(t=>"note"!==t.id&&!o.has(t.id)),h=ce.find(t=>"note"===t.id),l=h&&!o.has("note"),d=[...r].sort((t,e)=>(t.order??0)-(e.order??0));return t.jsxs("div",{style:{position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:e?void 0:a+10,bottom:e?a+10:void 0,display:"flex",alignItems:"center",gap:2,padding:"6px 8px",borderRadius:10,background:"#ffffff",border:"1px solid rgba(15, 23, 42, 0.08)",boxShadow:"0 4px 6px -1px rgba(15, 23, 42, 0.08), 0 10px 24px -4px rgba(15, 23, 42, 0.12)"},role:"toolbar","aria-label":"选区工具",children:[n.map(e=>t.jsx(pe,{label:e.label,onClick:()=>s(e.id),children:e.icon},e.id)),d.map(e=>t.jsx(pe,{label:e.label,onClick:()=>s(e.id),children:t.jsx("span",{style:{fontSize:11,fontWeight:600},children:e.label.slice(0,2)})},e.id)),l&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{width:1,height:28,margin:"0 4px",background:"#e2e8f0",flexShrink:0},"aria-hidden":!0}),t.jsx(pe,{label:h.label,onClick:()=>s("note"),accent:!0,children:h.icon})]})]})}function pe({label:e,onClick:a,accent:s,children:i}){return t.jsx("button",{type:"button",title:e,"aria-label":e,onClick:a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,border:"none",borderRadius:8,background:"transparent",color:s?"#b45309":"#334155",cursor:"pointer"},onMouseEnter:t=>{t.currentTarget.style.background=s?"#fffbeb":"#f1f5f9"},onMouseLeave:t=>{t.currentTarget.style.background="transparent"},children:i})}function ge({behind:e,mark:a}){return t.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 28 28",fill:"none","aria-hidden":!0,children:[e,t.jsx("text",{x:"14",y:"19",textAnchor:"middle",fontSize:"15",fontWeight:"700",fontFamily:"system-ui, sans-serif",fill:"#0f172a",children:"A"}),a]})}function fe(){return t.jsx(ge,{behind:t.jsx("rect",{x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#facc15"})})}function me(){return t.jsx(ge,{mark:t.jsx("path",{d:"M6 22h16",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function ve(){return t.jsx(ge,{mark:t.jsx("path",{d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626",strokeWidth:"2",strokeLinecap:"round",fill:"none"})})}function be(){return t.jsx(ge,{mark:t.jsx("path",{d:"M5 14h18",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function Pe(){return t.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[t.jsx("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706",strokeWidth:"1.2",strokeLinejoin:"round"}),t.jsx("path",{d:"M16 3v4h4",stroke:"#d97706",strokeWidth:"1.2"}),t.jsx("path",{d:"M10 12h6M10 16h4",stroke:"#92400e",strokeWidth:"1.2",strokeLinecap:"round"})]})}const we={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"};function Ie(s,i){var r,n,h,l;const c=null==s?void 0:s.selectionToolbar,u=!1!==(null==(r=null==s?void 0:s.markup)?void 0:r.enabled),g=!1!==(null==(n=null==s?void 0:s.notes)?void 0:n.enabled);if(!1===(null==c?void 0:c.enabled))return;if(!u&&!g&&!(null==(h=null==c?void 0:c.extraActions)?void 0:h.length))return;const{provides:f}=a.useCapability(o.SelectionPlugin.id),{provides:m}=a.useCapability(p.AnnotationPlugin.id),{provides:v}=a.useCapability(Gt.id);return e.useMemo(()=>e=>{const a=vt(e.item);return r=>{var o;return t.jsx("div",{...r.menuWrapperProps,children:t.jsx(ue,{placementAbove:!!(null==(o=r.placement)?void 0:o.suggestTop),anchorHeight:r.rect.size.height,onAction:t=>{var r,o;if("highlight"!==t&&"underline"!==t&&"squiggly"!==t&&"strikeout"!==t){if("note"===t){if(!f||!v||!g)return;const t=f.getHighlightRectsForPage(e.item.localPageIndex,a);return void bt(f.getSelectedText(a),a=>{v.requestCreateFromSelection({chapterId:e.item.chapterId,localPageIndex:e.item.localPageIndex,globalPageIndex:e.item.globalPageIndex,globalPageNumber:e.item.globalPageNumber,rectsPdfCoord:t,selectedText:a.join("\n")})})}null==(r=null==i?void 0:i.onExtraAction)||r.call(i,t,e)}else{if(!f||!m||!u)return;!function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,c={...ne[g=e],...null==(f=i)?void 0:f[g]},u=o.getFormattedSelection();var g,f;if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=d.uuidV4(),a=c.color??l.color??l.strokeColor,s=c.opacity??l.opacity,i=c.thickness??l.strokeWidth,o=c.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?le(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?de(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:he[e],..."highlight"===e?{blendMode:d.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}o.clear()}(a,we[t],m,f,null==(o=null==s?void 0:s.markup)?void 0:o.styles)}},hiddenBuiltinActions:null==c?void 0:c.hiddenBuiltinActions,extraActions:null==c?void 0:c.extraActions})})}},[m,null==(l=null==s?void 0:s.markup)?void 0:l.styles,null==i?void 0:i.onExtraAction,u,v,g,f,null==c?void 0:c.extraActions,null==c?void 0:c.hiddenBuiltinActions])}function ye({className:s,buildSelectionMenu:i,annotationSelectionMenu:r,redactionSelectionMenu:o,showNoteMarkers:n=!0,showBookmarkMarkers:h=!0,showRedactionLayer:l=!1,renderPageOverlay:d,features:c,onExtraSelectionAction:u,children:p}){var g,f,m,v;const b=function(){const{registry:t}=a.useRegistry();return e.useMemo(()=>{var e,a;const s=null==(a=null==(e=null==t?void 0:t.getPlugin(Gt.id))?void 0:e.provides)?void 0:a.call(e);return s?t=>s.createNoteFromSelection(t):null},[t])}(),P=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(Gt.id))}(),w=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(ae.id))}(),I=n&&P&&!1!==(null==(g=null==c?void 0:c.notes)?void 0:g.enabled),y=h&&w&&!1!==(null==(f=null==c?void 0:c.bookmarks)?void 0:f.enabled),C=w&&!1!==(null==(m=null==c?void 0:c.bookmarks)?void 0:m.enabled),M=Ie(c,{onExtraAction:u}),S=e.useMemo(()=>{if(i||M)return t=>{const e=M?M(t):t.defaultMenu;return i?i({...t,defaultMenu:e}):e}},[i,M]),x=e.useMemo(()=>d||C?e=>{var a;return t.jsxs(t.Fragment,{children:[C&&t.jsx(Ce,{item:e,hoverUi:null==(a=null==c?void 0:c.bookmarks)?void 0:a.hover}),null==d?void 0:d(e)]})}:d,[null==(v=null==c?void 0:c.bookmarks)?void 0:v.hover,C,d]);return t.jsxs("div",{className:s,style:s?void 0:re,children:[t.jsx(G,{renderPage:e=>{var a,s;return t.jsx(Me,{item:e,showNoteMarkers:I,showBookmarkMarkers:y,noteMarkerUi:null==(a=null==c?void 0:c.notes)?void 0:a.marker,bookmarkMarkerUi:null==(s=null==c?void 0:c.bookmarks)?void 0:s.marker,renderPageOverlay:x,buildSelectionMenu:S,createNote:b,annotationSelectionMenu:r,redactionSelectionMenu:o,showRedactionLayer:l})}}),p]})}function Ce({item:e,hoverUi:s}){var i;const r=vt(e),o=a.useDocumentState(r),n=(null==(i=null==o?void 0:o.document)?void 0:i.pages[e.localPageIndex])??null;return n?t.jsx(ie,{item:e,pdfPageWidth:n.size.width,pdfPageHeight:n.size.height,cssPageWidth:e.width,cssPageHeight:e.height,hoverUi:s}):null}function Me({item:l,showNoteMarkers:d,showBookmarkMarkers:u,noteMarkerUi:p,bookmarkMarkerUi:g,renderPageOverlay:f,createNote:m,buildSelectionMenu:v,annotationSelectionMenu:b,redactionSelectionMenu:P,showRedactionLayer:w=!1}){var I;const y=vt(l);!function(t){const{provides:s}=a.useCapability(c.DocumentManagerPlugin.id);e.useEffect(()=>{s&&t&&s.isDocumentOpen(t)&&s.setActiveDocument(t)},[s,t])}(y);const C=a.useDocumentState(y),M=(null==(I=null==C?void 0:C.document)?void 0:I.pages[l.localPageIndex])??null,S=function(s,i){const{provides:r}=a.useCapability(o.SelectionPlugin.id),n=vt(s);return e.useMemo(()=>{if(i)return e=>{var a;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(a=e.placement)?void 0:a.suggestTop)?-40:e.rect.size.height+8};return t.jsx("div",{...e.menuWrapperProps,children:t.jsx("div",{style:o,children:t.jsx("button",{type:"button",onClick:()=>{if(!r)return;const t=r.getHighlightRectsForPage(s.localPageIndex,n);bt(r.getSelectedText(n),e=>{const a=e.join("\n"),r=function(t,e,a){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageIndex:t.globalPageIndex,globalPageNumber:t.globalPageNumber,rectsPdfCoord:e,selectedText:a}}(s,t,a);i(r)})},style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e5e7eb",borderRadius:"6px",background:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},children:"添加附注"})})})}},[i,n,s,r])}(l,m),x=void 0!==v?v({item:l,defaultMenu:S,createNote:m}):S;return M?t.jsx(s.GlobalPointerProvider,{documentId:y,children:t.jsx(i.Rotate,{documentId:y,pageIndex:l.localPageIndex,style:{backgroundColor:"#fff"},children:t.jsxs(s.PagePointerProvider,{documentId:y,pageIndex:l.localPageIndex,children:[t.jsx(A,{chapterId:y,localPageIndex:l.localPageIndex}),t.jsx(r.SelectionLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:x}),w&&t.jsx(h.RedactionLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:P}),t.jsx(n.AnnotationLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:b}),u&&M&&t.jsx(mt,{chapterId:y,localPageIndex:l.localPageIndex,pdfPageWidth:M.size.width,pdfPageHeight:M.size.height,cssPageWidth:l.width,cssPageHeight:l.height,ui:g}),null==f?void 0:f(l),d&&M&&t.jsx(Z,{chapterId:y,localPageIndex:l.localPageIndex,pdfPageWidth:M.size.width,pdfPageHeight:M.size.height,cssPageWidth:l.width,cssPageHeight:l.height,ui:p})]})})}):null}const Se="chapter-manager",xe={id:Se,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Le={kind:"first-wins"};function $e(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ke=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const De=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Le,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Le,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Le){const a=function(t,e=Le){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,$e(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ke(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};De.id="chapter-manager";let Te=De;const ze={manifest:xe,create:t=>new Te(Se,t),reducer:t=>t,initialState:{}},Oe="chapter-scroll",Ge={id:Oe,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},Ae={kind:"first-wins"};function Ne(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Ee{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Re=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ae,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ae,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Ae){const a=function(t,e=Ae){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ne(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ee(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Re.id="chapter-manager";let Ve=Re;const _e=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ve.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};_e.id="chapter-scroll";let Ue=_e;const Fe={manifest:Ge,create:t=>new Ue(Oe,t),reducer:t=>t,initialState:{}},qe={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class Be{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(qe);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=je(a.items,s,e.position)}return t}}function je(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const We={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function He(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}const Ye={markup:{enabled:!0},bookmarks:{enabled:!0},notes:{enabled:!0},selectionToolbar:{enabled:!0},zoom:{enabled:!0,min:.5,max:3,initial:1}};function Ke(t){var e,a,s,i,r;return function(t){var e,a,s,i,r,n;const h=t.toolbar??{},d=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=d.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new Be;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=We[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:d}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?He(x.list()):{},...t.commands??{}},$=[l.createPluginRegistration(c.DocumentManagerPluginPackage,{initialDocuments:[]}),l.createPluginRegistration(ze,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),l.createPluginRegistration(Fe,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),l.createPluginRegistration(g.InteractionManagerPluginPackage),l.createPluginRegistration(f.RenderPluginPackage),l.createPluginRegistration(m.RotatePluginPackage),l.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),l.createPluginRegistration(v.HistoryPluginPackage),l.createPluginRegistration(p.AnnotationPluginPackage),l.createPluginRegistration(b.RedactionPluginPackage),l.createPluginRegistration(P.FormPluginPackage),l.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),l.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[l.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[l.createPluginRegistration(C.I18nPluginPackage),l.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(l.createPluginRegistration(Nt,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(l.createPluginRegistration(se,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}({...t,toolbar:t.toolbar??{enabledModes:[]},features:{...Ye,...t.features,markup:{...Ye.markup,...null==(e=t.features)?void 0:e.markup},bookmarks:{...Ye.bookmarks,...null==(a=t.features)?void 0:a.bookmarks},notes:{...Ye.notes,...null==(s=t.features)?void 0:s.notes},selectionToolbar:{...Ye.selectionToolbar,...null==(i=t.features)?void 0:i.selectionToolbar},zoom:{...Ye.zoom,...null==(r=t.features)?void 0:r.zoom}}})}function Xe(t,e,a){return Math.min(a,Math.max(e,t))}const Ze="chapter-manager",Qe={id:Ze,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Je={kind:"first-wins"};function ta(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ea=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const aa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Je,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Je,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Je){const a=function(t,e=Je){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ta(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ea(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};aa.id="chapter-manager";let sa=aa;const ia={manifest:Qe,create:t=>new sa(Ze,t),reducer:t=>t,initialState:{}},ra="chapter-scroll",oa={id:ra,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},na={kind:"first-wins"};function ha(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class la{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const da=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=na,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??na,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=na){const a=function(t,e=na){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ha(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new la(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};da.id="chapter-manager";let ca=da;const ua=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ca.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ua.id="chapter-scroll";let pa=ua;const ga={manifest:oa,create:t=>new pa(ra,t),reducer:t=>t,initialState:{}},fa="note",ma={id:fa,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},va={kind:"first-wins"};function ba(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Pa=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const wa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=va,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??va,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=va){const a=function(t,e=va){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ba(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Pa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};wa.id="chapter-manager";let Ia=wa;const ya={kind:"first-wins"};function Ca(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ma=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Sa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=ya,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??ya,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=ya){const a=function(t,e=ya){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ca(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ma(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Sa.id="chapter-manager";let xa=Sa;const La=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(xa.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};La.id="chapter-scroll";let $a=La;const ka=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin($a.id),this.chapterManager=this.registry.getPlugin(Ia.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:Ta(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};ka.id="note";let Da=ka;function Ta(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const za={manifest:ma,create:t=>new Da(fa,t),reducer:t=>t,initialState:{}},Oa="paragraph-bookmark",Ga={id:Oa,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Aa={kind:"first-wins"};function Na(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ea=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ra=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Aa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Aa,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Aa){const a=function(t,e=Aa){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Na(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ea(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ra.id="chapter-manager";let Va=Ra;const _a={kind:"first-wins"};function Ua(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Fa{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const qa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=_a,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??_a,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=_a){const a=function(t,e=_a){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ua(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Fa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};qa.id="chapter-manager";let Ba=qa;const ja=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ba.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ja.id="chapter-scroll";let Wa=ja;function Ha(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Ya(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Ka(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Ha(i),n=e.markerAnchor??Ha(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Ya(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const Xa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Wa.id),this.chapterManager=this.registry.getPlugin(Va.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Ka(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};Xa.id="paragraph-bookmark";let Za=Xa;const Qa={manifest:Ga,create:t=>new Za(Oa,t),reducer:t=>t,initialState:{}},Ja={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class ts{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(Ja);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=es(a.items,s,e.position)}return t}}function es(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const as={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function ss(t){var e,a,s,i,r,n;const h=t.toolbar??{},d=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=d.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new ts;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=as[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:d}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?is(x.list()):{},...t.commands??{}},$=[l.createPluginRegistration(c.DocumentManagerPluginPackage,{initialDocuments:[]}),l.createPluginRegistration(ia,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),l.createPluginRegistration(ga,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),l.createPluginRegistration(g.InteractionManagerPluginPackage),l.createPluginRegistration(f.RenderPluginPackage),l.createPluginRegistration(m.RotatePluginPackage),l.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),l.createPluginRegistration(v.HistoryPluginPackage),l.createPluginRegistration(p.AnnotationPluginPackage),l.createPluginRegistration(b.RedactionPluginPackage),l.createPluginRegistration(P.FormPluginPackage),l.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),l.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[l.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[l.createPluginRegistration(C.I18nPluginPackage),l.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(l.createPluginRegistration(za,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(l.createPluginRegistration(Qa,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}function is(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}const rs={markup:{enabled:!0},bookmarks:{enabled:!0},notes:{enabled:!0},selectionToolbar:{enabled:!0},zoom:{enabled:!0,min:.5,max:3,initial:1}};class os{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}}const ns={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},hs={highlight:d.PdfAnnotationSubtype.HIGHLIGHT,underline:d.PdfAnnotationSubtype.UNDERLINE,squiggly:d.PdfAnnotationSubtype.SQUIGGLY,strikeout:d.PdfAnnotationSubtype.STRIKEOUT};function ls(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function ds(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}const cs={kind:"first-wins"};function us(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ps=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function gs(t,e=cs){const a=function(t,e=cs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,us(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ps(r)}const fs=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=cs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??cs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=gs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};fs.id="chapter-manager";let ms=fs;const vs={kind:"first-wins"};function bs(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Ps{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function ws(t,e=vs){const a=function(t,e=vs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,bs(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ps(r)}const Is=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=vs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??vs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=ws(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Is.id="chapter-manager";let ys=Is;const Cs=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ys.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Cs.id="chapter-scroll";let Ms=Cs;function Ss(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function xs(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Ls(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);if(o<=0)return 0;return Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function $s(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??xs(i),n=e.markerAnchor??xs(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Ls(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}async function ks(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Ms.id),this.chapterManager=this.registry.getPlugin(ms.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if($s(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await ks(a,s,i)}}).id="paragraph-bookmark";const Ds={kind:"first-wins"};function Ts(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let zs=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function Os(t,e=Ds){const a=function(t,e=Ds){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ts(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new zs(r)}const Gs=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ds,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ds,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Os(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Gs.id="chapter-manager";let As=Gs;const Ns={kind:"first-wins"};function Es(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Rs{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function Vs(t,e=Ns){const a=function(t,e=Ns){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Es(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Rs(r)}const _s=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ns,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ns,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Vs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};_s.id="chapter-manager";let Us=_s;const Fs=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Us.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Fs.id="chapter-scroll";let qs=Fs;const Bs={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"};function js({nodes:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r}){return t.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",marginLeft:a>0?12:0},children:e.map(e=>t.jsx(Ws,{node:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r},e.id))})}function Ws({node:a,depth:s,activeChapterId:i,chapterStatus:r,onSelect:o}){const n=a.children??[],h=n.length>0,[l,d]=e.useState(s<1),c=i===a.id,u=r[a.id]??"idle",p=!h;return t.jsxs("li",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"stretch",gap:2},children:[h?t.jsx("button",{type:"button","aria-expanded":l,style:Xs,onClick:()=>d(t=>!t),children:l?"▼":"▶"}):t.jsx("span",{style:{width:16,flexShrink:0},"aria-hidden":!0}),t.jsxs("button",{type:"button",style:{...Zs,background:c?"#1e293b":"transparent",color:c?"#fff":"#334155"},onClick:()=>o(a.id),children:[t.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:a.title}),t.jsxs("div",{style:{marginTop:2,fontSize:10,color:c?"#cbd5e1":"#94a3b8",display:"flex",flexWrap:"wrap",gap:"4px 8px"},children:[t.jsxs("span",{children:["第 ",a.startPage,a.endPage!==a.startPage?`–${a.endPage}`:""," 页"]}),p?t.jsx("span",{children:Bs[u]}):null]})]})]}),h&&l?t.jsx(js,{nodes:n,depth:s+1,activeChapterId:i,chapterStatus:r,onSelect:o}):null]})}const Hs={display:"flex",flexDirection:"column",width:224,flexShrink:0,borderRadius:8,border:"1px solid #e2e8f0",background:"#fff",overflow:"hidden"},Ys={margin:0,padding:"8px 12px",fontSize:12,fontWeight:600,color:"#334155",borderBottom:"1px solid #f1f5f9"},Ks={flex:1,overflowY:"auto",padding:4},Xs={flexShrink:0,padding:"0 4px",border:"none",background:"transparent",fontSize:10,color:"#94a3b8",cursor:"pointer"},Zs={minWidth:0,flex:1,border:"none",borderRadius:6,padding:"8px",textAlign:"left",fontSize:13,cursor:"pointer"};Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>a.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>a.useCapability}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>S.usePdfiumEngine}),exports.CallbackPasswordProvider=class{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}},exports.ChapterManagerPlugin=As,exports.ChapterPdfViewer=function({engine:s,editorOptions:i,features:r,className:o,viewportClassName:n,buildSelectionMenu:h,onExtraSelectionAction:l,renderPageOverlay:d,children:c}){var u,p,g,f;const m=e.useMemo(()=>({...Ye,...r}),[r]),v=e.useMemo(()=>Ke({...i,features:m}),[i,m]),b=!1!==(null==(u=m.zoom)?void 0:u.enabled),[P,w]=e.useState((null==(p=m.zoom)?void 0:p.initial)??1),I=e.useRef(null);return e.useEffect(()=>{var t,e;if(!b)return;const a=I.current;if(!a)return;const s=a.querySelector("[data-chapter-scroll-viewport]");return s?function({container:t,getScale:e,setScale:a,minZoom:s=.5,maxZoom:i=3}){let r=0,o=1,n=null,h=1,l=1;const d=t=>{(t.ctrlKey||t.metaKey)&&(t.preventDefault(),null===n?(l=e(),h=1):clearTimeout(n),h*=1-.01*t.deltaY,h=Xe(h,.1,10),a(Xe(l*h,s,i)),n=setTimeout(()=>{n=null},120))},c=new Map,u=t=>{if(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size){const[t,a]=[...c.values()];r=Math.hypot(a.x-t.x,a.y-t.y),o=e()}},p=t=>{if(c.has(t.pointerId)&&(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size&&r>0)){t.preventDefault();const[e,n]=[...c.values()],h=Math.hypot(n.x-e.x,n.y-e.y);a(Xe(o*(h/r),s,i))}},g=t=>{c.delete(t.pointerId),c.size<2&&(r=0)};return t.addEventListener("wheel",d,{passive:!1}),t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p,{passive:!1}),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("wheel",d),t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g),n&&clearTimeout(n)}}({container:s,getScale:()=>P,setScale:w,minZoom:(null==(t=m.zoom)?void 0:t.min)??.5,maxZoom:(null==(e=m.zoom)?void 0:e.max)??3}):void 0},[null==(g=m.zoom)?void 0:g.max,null==(f=m.zoom)?void 0:f.min,P,b]),t.jsx("div",{ref:I,className:o,style:o?void 0:re,children:t.jsx(a.EmbedPDF,{engine:s,plugins:v.plugins,children:({pluginsReady:e})=>e?t.jsxs("div",{style:b?{...oe,transform:`scale(${P})`,transformOrigin:"top center"}:oe,children:[t.jsx(ye,{className:n,features:m,buildSelectionMenu:h,onExtraSelectionAction:l,renderPageOverlay:d}),c]}):null})})},exports.ChapterScrollPlugin=qs,exports.ChapterTreePanel=function({tree:s,activeChapterId:i,onActiveChapterChange:r}){const{provides:o}=a.useCapability(qs.id),{provides:n}=a.useCapability(As.id),[h,l]=e.useState({}),d=e.useCallback(()=>{if(!n)return;const t={},e=a=>{var s;for(const i of a)t[i.id]=n.getChapterStatus(i.id),(null==(s=i.children)?void 0:s.length)&&e(i.children)};e(s),l(t)},[n,s]);return e.useEffect(()=>{d()},[d]),e.useEffect(()=>{if(n)return n.onChapterStatusChange(d)},[n,d]),t.jsxs("aside",{style:Hs,children:[t.jsx("h2",{style:Ys,children:"章节目录"}),t.jsx("nav",{style:Ks,"aria-label":"章节目录",children:t.jsx(js,{nodes:s,depth:0,activeChapterId:i,chapterStatus:h,onSelect:t=>{null==r||r(t),null==o||o.scrollToChapter(t)}})})]})},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=rs,exports.PdfChapterViewport=ye,exports.applySelectionMarkup=function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,c=function(t,e){return{...ns[t],...null==e?void 0:e[t]}}(e,i),u=o.getFormattedSelection();if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=d.uuidV4(),a=c.color??l.color??l.strokeColor,s=c.opacity??l.opacity,i=c.thickness??l.strokeWidth,o=c.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?ls(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?ds(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:hs[e],..."highlight"===e?{blendMode:d.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}return o.clear(),!0},exports.buildParagraphBookmarkAnchor=function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Ss(i),rectsPdfCoord:i,markerAnchor:xs(i)}},exports.createChapterViewerEditor=function(t){var e,a,s,i,r;return ss({...t,toolbar:t.toolbar??{enabledModes:[]},features:{...rs,...t.features,markup:{...rs.markup,...null==(e=t.features)?void 0:e.markup},bookmarks:{...rs.bookmarks,...null==(a=t.features)?void 0:a.bookmarks},notes:{...rs.notes,...null==(s=t.features)?void 0:s.notes},selectionToolbar:{...rs.selectionToolbar,...null==(i=t.features)?void 0:i.selectionToolbar},zoom:{...rs.zoom,...null==(r=t.features)?void 0:r.zoom}}})},exports.createChapterViewerEditorOptions=function(t){return{manifest:t.manifest,chapterPdfLoader:t.chapterPdfLoader,overlapStrategy:{kind:"first-wins"},passwordProvider:new os(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]},bookmarks:t.bookmarks,notes:t.notes}},exports.createPdfChapterEditor=ss;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),a=require("@embedpdf/core/react"),s=require("@embedpdf/plugin-interaction-manager/react"),i=require("@embedpdf/plugin-rotate/react"),r=require("@embedpdf/plugin-selection/react"),o=require("@embedpdf/plugin-selection"),n=require("@embedpdf/plugin-annotation/react"),h=require("@embedpdf/plugin-redaction/react"),l=require("@embedpdf/core"),d=require("@embedpdf/models"),c=require("@embedpdf/plugin-document-manager"),u=require("@embedpdf/plugin-render/react");require("@embedpdf/plugin-tiling/react");const p=require("@embedpdf/plugin-annotation"),g=require("@embedpdf/plugin-interaction-manager"),f=require("@embedpdf/plugin-render"),m=require("@embedpdf/plugin-rotate"),v=require("@embedpdf/plugin-history"),b=require("@embedpdf/plugin-redaction"),P=require("@embedpdf/plugin-form"),w=require("@embedpdf/plugin-stamp"),I=require("@embedpdf/plugin-signature"),y=require("@embedpdf/plugin-commands"),C=require("@embedpdf/plugin-i18n"),M=require("@embedpdf/plugin-ui"),S=require("@embedpdf/engines/react"),x={kind:"first-wins"};function L(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const k=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=x,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??x,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=x){const a=function(t,e=x){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,L(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};k.id="chapter-manager";let D=k;const T=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(D.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};T.id="chapter-scroll";let z=T;function O({item:s,renderPage:i,renderPlaceholder:r}){const o=function(t,s){const i=a.useDocumentState(t),r=e.useMemo(()=>!(!i||"loaded"!==i.status||!i.document)&&Boolean(i.document.pages[s]),[i,s]),[o,n]=e.useState(r);return e.useEffect(()=>{n(r)},[r]),e.useEffect(()=>{if(r)return;if(!i||"loaded"!==i.status||!i.document)return;let t=!1,e=0;const a=()=>{var r;t||((null==(r=i.document)?void 0:r.pages[s])?n(!0):++e<120&&requestAnimationFrame(a))};return requestAnimationFrame(a),()=>{t=!0}},[i,s,r]),o}(s.chapterId,s.localPageIndex);return t.jsx("div",{"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:{position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:o?"#fff":"#f3f4f6",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"},children:o?i(s):(null==r?void 0:r(s))??t.jsx("div",{style:{display:"flex",width:"100%",height:"100%",alignItems:"center",justifyContent:"center",color:"#9ca3af",fontSize:"12px"},children:"Loading chapter…"})})}function G({renderPage:s,renderPlaceholder:i,className:r,style:o,...n}){const{provides:h}=a.useCapability(z.id),{provides:l}=a.useCapability(c.DocumentManagerPlugin.id),d=e.useRef(null),[u,p]=e.useState(null);e.useEffect(()=>{if(!h)return;const t=d.current;h.registerViewport(t);const e=t=>p(t),a=h.onLayoutChange(e),s=null==l?void 0:l.onDocumentOpened(()=>e(h.getLayout())),i=null==l?void 0:l.onDocumentClosed(()=>e(h.getLayout()));return()=>{a(),null==s||s(),null==i||i(),h.registerViewport(null)}},[h,l]);const g=(null==u?void 0:u.totalHeight)??0,f=(null==u?void 0:u.totalWidth)??0;return t.jsx("div",{...n,ref:d,"data-chapter-scroll-viewport":"",className:r,style:{overflow:"auto",position:"relative",width:"100%",height:"100%",...o},children:t.jsx("div",{style:{position:"relative",width:`${f}px`,height:`${g}px`,margin:"0 auto"},children:null==u?void 0:u.items.map(e=>t.jsx(O,{item:e,renderPage:s,renderPlaceholder:i},e.globalPageIndex))})})}function A({chapterId:e,localPageIndex:a,scale:s,dpr:i,className:r}){return t.jsx(u.RenderLayer,{documentId:e,pageIndex:a,scale:s,dpr:i,className:r,style:{pointerEvents:"none"}})}const E={kind:"first-wins"};function N(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let R=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const V=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=E,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??E,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=E){const a=function(t,e=E){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,N(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new R(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};V.id="chapter-manager";let _=V;const U={kind:"first-wins"};function F(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let q=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const B=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=U,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??U,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=U){const a=function(t,e=U){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,F(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new q(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};B.id="chapter-manager";let j=B;const W=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(j.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};W.id="chapter-scroll";let H=W;const Y=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(H.id),this.chapterManager=this.registry.getPlugin(_.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:K(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Y.id="note";let Z=Y;function K(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function X({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,color:l="#f59e0b",ui:d,className:c,style:u}){const{plugin:p}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(Z.id);return{plugin:e,isLoading:!1,ready:(null==e?void 0:e.ready())??Promise.resolve()}})(),{provides:g}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{provides:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(Z.id);return(null==e?void 0:e.provides)?{provides:e.provides(),isLoading:!1,ready:e.ready()}:{provides:null,isLoading:!1,ready:Promise.resolve()}})(),[f,m]=e.useState([]),[v,b]=e.useState(null),[P,w]=e.useState(null);if(e.useEffect(()=>{if(g)return g.onNotesChange(t=>{m(t.filter(t=>t.chapterId===s&&t.localPageIndex===i))})},[g,s,i]),e.useEffect(()=>{if(!P)return;const t=t=>{var e;const a=t.target;(null==(e=a.closest)?void 0:e.call(a,`[data-note-marker-zone="${P}"]`))||(w(null),b(null))};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[P]),!g||0===f.length||!r||!o)return null;const I=n/r,y=h/o,C=(null==d?void 0:d.iconSize)??16,M=(null==d?void 0:d.highlightColor)??"rgba(245, 158, 11, 0.08)";return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:25,...u},children:f.map(e=>{const a=v===e.noteId,s=P===e.noteId,i=a||s,{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:I,sy:y,cssPageWidth:n,iconSize:C}),h=function(t,e,a){let s=1/0,i=1/0,r=-1/0,o=-1/0;for(const n of t)s=Math.min(s,n.origin.x*e),i=Math.min(i,n.origin.y*a),r=Math.max(r,(n.origin.x+n.size.width)*e),o=Math.max(o,(n.origin.y+n.size.height)*a);return{left:s,top:i,width:r-s,height:o-i}}(e.rectsPdfCoord,I,y),c=s?72:0,u=Math.max(0,Math.min(h.left,r)-8),f=Math.max(0,Math.min(h.top,o)-8),m=Math.min(n,Math.max(h.left+h.width,r+C)+8)-u,S=Math.max(h.top+h.height,o+C+6+c)+8-f;return t.jsxs("div",{children:[e.rectsPdfCoord.map((a,s)=>t.jsx("div",{style:{position:"absolute",left:a.origin.x*I+"px",top:a.origin.y*y+"px",width:a.size.width*I+"px",height:a.size.height*y+"px",background:M,borderRadius:"2px",pointerEvents:"auto",cursor:"default"},onMouseEnter:()=>b(e.noteId)},`${e.noteId}-bg-${s}`)),i&&t.jsxs("div",{"data-note-marker-zone":e.noteId,style:{position:"absolute",left:`${u}px`,top:`${f}px`,width:`${m}px`,height:`${S}px`,pointerEvents:"auto",zIndex:26},onMouseEnter:()=>b(e.noteId),onMouseLeave:()=>{P!==e.noteId&&b(null)},children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"笔记","aria-label":"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:d.renderIcon({note:e})}):t.jsx("button",{type:"button",title:"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,border:"none",borderRadius:"50%",background:l,color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":"笔记",children:"💬"}),s&&((null==d?void 0:d.renderMenuActions)?t.jsx("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto"},onMouseDown:t=>t.stopPropagation(),children:d.renderMenuActions({note:e,onEdit:()=>{w(null),b(null),null==p||p.requestEdit(e.noteId)},onDelete:()=>{w(null),b(null),g.deleteNote(e.noteId)}})}):t.jsxs("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto",minWidth:"80px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onMouseDown:t=>t.stopPropagation(),children:[t.jsx("button",{type:"button",style:Q,onClick:t=>{t.stopPropagation(),w(null),b(null),null==p||p.requestEdit(e.noteId)},children:"编辑"}),t.jsx("button",{type:"button",style:{...Q,color:"#dc2626"},onClick:t=>{t.stopPropagation(),w(null),b(null),g.deleteNote(e.noteId)},children:"删除"})]}))]})]},e.noteId)})})}const Q={display:"block",width:"100%",padding:"6px 10px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#334155",cursor:"pointer",textAlign:"left"},J={kind:"first-wins"};function tt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let et=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const at=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=J,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??J,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=J){const a=function(t,e=J){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,tt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new et(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};at.id="chapter-manager";let st=at;const it={kind:"first-wins"};function rt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ot=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const nt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=it,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??it,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=it){const a=function(t,e=it){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,rt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ot(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};nt.id="chapter-manager";let ht=nt;const lt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ht.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};lt.id="chapter-scroll";let dt=lt;function ct(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function ut(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function pt(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??ct(i),n=e.markerAnchor??ct(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(ut(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const gt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(dt.id),this.chapterManager=this.registry.getPlugin(st.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(pt(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};gt.id="paragraph-bookmark";let ft=gt;function mt({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,onBookmarkClick:l,ui:d,className:c,style:u}){const{provides:p}=a.useCapability(ft.id),[g,f]=e.useState([]),[m,v]=e.useState(null),b=e.useRef(null);if(e.useEffect(()=>{if(!p)return;const t=()=>{f(p.listBookmarks().filter(t=>t.anchor.chapterId===s&&t.anchor.localPageIndex===i))};return t(),p.onBookmarksChange(t)},[p,s,i]),e.useEffect(()=>{if(!m)return;const t=t=>{var e;(null==(e=b.current)?void 0:e.contains(t.target))||v(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[m]),!p||0===g.length||!r||!o)return null;const P=n/r,w=h/o,I=(null==d?void 0:d.iconSize)??16;return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",...u},children:g.map(e=>{var a;const s=(null==(a=e.anchor.rectsPdfCoord)?void 0:a.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord],i=e.anchor.markerAnchor??{x:e.anchor.rectPdfCoord.origin.x+e.anchor.rectPdfCoord.size.width,y:e.anchor.rectPdfCoord.origin.y+e.anchor.rectPdfCoord.size.height},{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:i,lineRects:s,sx:P,sy:w,cssPageWidth:n,iconSize:I}),h=Math.max(0,r-6),c=Math.max(0,o-6);return t.jsxs("div",{style:{position:"absolute",left:`${h}px`,top:`${c}px`,width:`${I+12}px`,height:`${I+12}px`,pointerEvents:"auto",zIndex:20},onMouseDown:t=>t.stopPropagation(),children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:e.label,"aria-label":`bookmark ${e.label}`,style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},children:d.renderIcon({bookmark:e})}):t.jsx("button",{type:"button",title:e.label,onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":`bookmark ${e.label}`,children:"🔖"}),m===e.id&&t.jsx("div",{ref:b,style:{position:"absolute",left:"6px",top:"-36px",zIndex:30,pointerEvents:"auto",minWidth:"88px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onClick:t=>t.stopPropagation(),children:t.jsx("button",{type:"button",style:{width:"100%",padding:"6px 8px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#dc2626",cursor:"pointer",textAlign:"left"},onClick:()=>{p.requestRemoveBookmark(e.id).then(t=>{t&&v(null)})},children:"删除书签"})})]},e.id)})})}function vt(t){return t.chapterId}function bt(t,e){t.wait(e,()=>{})}const Pt="note",wt={id:Pt,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},It={kind:"first-wins"};function yt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ct=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Mt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=It,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??It,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=It){const a=function(t,e=It){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,yt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ct(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Mt.id="chapter-manager";let St=Mt;const xt={kind:"first-wins"};function Lt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $t=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const kt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=xt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??xt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=xt){const a=function(t,e=xt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Lt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $t(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};kt.id="chapter-manager";let Dt=kt;const Tt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Dt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Tt.id="chapter-scroll";let zt=Tt;const Ot=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(zt.id),this.chapterManager=this.registry.getPlugin(St.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:At(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Ot.id="note";let Gt=Ot;function At(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const Et={manifest:wt,create:t=>new Gt(Pt,t),reducer:t=>t,initialState:{}},Nt="paragraph-bookmark",Rt={id:Nt,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Vt={kind:"first-wins"};function _t(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ut=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ft=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Vt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Vt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Vt){const a=function(t,e=Vt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,_t(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ut(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ft.id="chapter-manager";let qt=Ft;const Bt={kind:"first-wins"};function jt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Wt{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Ht=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Bt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Bt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Bt){const a=function(t,e=Bt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,jt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Wt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ht.id="chapter-manager";let Yt=Ht;const Zt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Yt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Zt.id="chapter-scroll";let Kt=Zt;function Xt(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function Qt(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Jt(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function te(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Qt(i),n=e.markerAnchor??Qt(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Jt(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const ee=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Kt.id),this.chapterManager=this.registry.getPlugin(qt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(te(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};ee.id="paragraph-bookmark";let ae=ee;const se={manifest:Rt,create:t=>new ae(Nt,t),reducer:t=>t,initialState:{}};function ie({item:s,pdfPageWidth:i,pdfPageHeight:r,cssPageWidth:n,cssPageHeight:h,hoverUi:l}){const d=vt(s),{provides:c}=a.useCapability(o.SelectionPlugin.id),{provides:u}=a.useCapability(ae.id),p=e.useRef(null),[g,f]=e.useState(null),[m,v]=e.useState(null),[b,P]=e.useState(null),w=(null==l?void 0:l.iconSize)??16;e.useEffect(()=>{if(!c)return;const t=c.forDocument(d),e=()=>{const e=t.getState().geometry[s.localPageIndex];e&&f(e)},a=t.onSelectionChange(e);let i=!1;const r=()=>{if(!i){try{if(e(),t.getState().geometry[s.localPageIndex])return}catch{}requestAnimationFrame(r)}};return r(),()=>{i=!0,a()}},[c,d,s.localPageIndex]);const I=b??m;e.useEffect(()=>{if(!g||!i)return;const t=t=>{if(b)return;if(c)try{if(c.forDocument(d).getState().selecting)return void v(null)}catch{}const e=p.current;if(!e)return;const a=e.getBoundingClientRect();if(t.clientX<a.left||t.clientX>a.right||t.clientY<a.top||t.clientY>a.bottom)return void v(null);const s=function(t,e){const a=o.glyphAt(t,e);if(a<0)return null;const s=o.expandToLineBoundary(t,a);if(!s)return null;const i=o.rectsWithinSlice(t,s.from,s.to);return 0===i.length?null:{lineRects:i,charFrom:s.from,charTo:s.to}}(g,{x:(t.clientX-a.left)/(n/i),y:(t.clientY-a.top)/(h/r)});v((null==s?void 0:s.lineRects)??null)};return document.addEventListener("mousemove",t),()=>document.removeEventListener("mousemove",t)},[g,i,r,n,h,c,d,b]);const y=(null==I?void 0:I.length)?function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Xt(i),rectsPdfCoord:i,markerAnchor:Qt(i)}}(s.chapterId,s.localPageIndex,I,{globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber}):null,C=y&&(null==u?void 0:u.listBookmarks().some(t=>te(t.anchor,y))),M=e.useCallback(()=>{u&&y&&!C&&(u.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:y}),v(null),P(null))},[u,y,C]);if(!u||!i||!r)return null;const S=n/i,x=h/r,L=null==I?void 0:I[I.length-1],$=L?Math.min((L.origin.x+L.size.width)*S+6,Math.max(0,n-w-2)):0,k=L?L.origin.y*x+(L.size.height*x-w)/2:0,D=L?Math.max(0,(L.origin.x+L.size.width)*S-4):0,T=L?Math.max(0,L.origin.y*x-4):0;return t.jsx("div",{ref:p,style:{position:"absolute",inset:0,zIndex:14,pointerEvents:"none"},children:I&&L&&!C&&t.jsx("div",{style:{position:"absolute",left:`${D}px`,top:`${T}px`,width:`${w+20}px`,height:`${L.size.height*x+w+12}px`,pointerEvents:"auto"},onMouseEnter:()=>P(I),onMouseLeave:()=>P(null),children:(null==l?void 0:l.renderAddIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-D+"px",top:k-T+"px",width:w,height:w,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:l.renderAddIcon()}):t.jsx("button",{type:"button",title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-D+"px",top:k-T+"px",width:`${w}px`,height:`${w}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",lineHeight:1,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:"🔖"})})})}const re={position:"relative",height:"100%",width:"100%"},oe={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},ne={highlight:d.PdfAnnotationSubtype.HIGHLIGHT,underline:d.PdfAnnotationSubtype.UNDERLINE,squiggly:d.PdfAnnotationSubtype.SQUIGGLY,strikeout:d.PdfAnnotationSubtype.STRIKEOUT};function he(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function le(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function de(t,e){const a=t;return!1===t?{...e,enabled:!1}:!0===t||void 0===t?{...e,enabled:e.enabled??!0}:{...e,...a,enabled:!1!==(null==a?void 0:a.enabled)}}function ce(t){const e=de(null==t?void 0:t.markup,{enabled:!0}),a=de(null==t?void 0:t.bookmarks,{enabled:!0}),s=de(null==t?void 0:t.notes,{enabled:!0});return{markup:e,bookmarks:a,notes:s,zoom:de(null==t?void 0:t.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:de(void 0===(null==t?void 0:t.selectionToolbar)?!1!==e.enabled||!1!==s.enabled:t.selectionToolbar,{enabled:!0})}}const ue=[{id:"highlight",label:"高亮背景",icon:t.jsx(me,{})},{id:"underline",label:"下划线",icon:t.jsx(ve,{})},{id:"squiggly",label:"波浪线",icon:t.jsx(be,{})},{id:"strikeout",label:"删除线",icon:t.jsx(Pe,{})},{id:"note",label:"添加笔记",icon:t.jsx(we,{})}];function pe({placementAbove:e,anchorHeight:a,onAction:s,hiddenBuiltinActions:i=[],extraActions:r=[]}){const o=new Set(i),n=ue.filter(t=>"note"!==t.id&&!o.has(t.id)),h=ue.find(t=>"note"===t.id),l=h&&!o.has("note"),d=[...r].sort((t,e)=>(t.order??0)-(e.order??0));return t.jsxs("div",{style:{position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:e?void 0:a+10,bottom:e?a+10:void 0,display:"flex",alignItems:"center",gap:2,padding:"6px 8px",borderRadius:10,background:"#ffffff",border:"1px solid rgba(15, 23, 42, 0.08)",boxShadow:"0 4px 6px -1px rgba(15, 23, 42, 0.08), 0 10px 24px -4px rgba(15, 23, 42, 0.12)"},role:"toolbar","aria-label":"选区工具",children:[n.map(e=>t.jsx(ge,{label:e.label,onClick:()=>s(e.id),children:e.icon},e.id)),d.map(e=>t.jsx(ge,{label:e.label,onClick:()=>s(e.id),children:t.jsx("span",{style:{fontSize:11,fontWeight:600},children:e.label.slice(0,2)})},e.id)),l&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{width:1,height:28,margin:"0 4px",background:"#e2e8f0",flexShrink:0},"aria-hidden":!0}),t.jsx(ge,{label:h.label,onClick:()=>s("note"),accent:!0,children:h.icon})]})]})}function ge({label:e,onClick:a,accent:s,children:i}){return t.jsx("button",{type:"button",title:e,"aria-label":e,onClick:a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,border:"none",borderRadius:8,background:"transparent",color:s?"#b45309":"#334155",cursor:"pointer"},onMouseEnter:t=>{t.currentTarget.style.background=s?"#fffbeb":"#f1f5f9"},onMouseLeave:t=>{t.currentTarget.style.background="transparent"},children:i})}function fe({behind:e,mark:a}){return t.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 28 28",fill:"none","aria-hidden":!0,children:[e,t.jsx("text",{x:"14",y:"19",textAnchor:"middle",fontSize:"15",fontWeight:"700",fontFamily:"system-ui, sans-serif",fill:"#0f172a",children:"A"}),a]})}function me(){return t.jsx(fe,{behind:t.jsx("rect",{x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#facc15"})})}function ve(){return t.jsx(fe,{mark:t.jsx("path",{d:"M6 22h16",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function be(){return t.jsx(fe,{mark:t.jsx("path",{d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626",strokeWidth:"2",strokeLinecap:"round",fill:"none"})})}function Pe(){return t.jsx(fe,{mark:t.jsx("path",{d:"M5 14h18",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function we(){return t.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[t.jsx("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706",strokeWidth:"1.2",strokeLinejoin:"round"}),t.jsx("path",{d:"M16 3v4h4",stroke:"#d97706",strokeWidth:"1.2"}),t.jsx("path",{d:"M10 12h6M10 16h4",stroke:"#92400e",strokeWidth:"1.2",strokeLinecap:"round"})]})}const Ie={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"};function ye(s,i){var r,n,h,l;const c=null==s?void 0:s.selectionToolbar,u=!1!==(null==(r=null==s?void 0:s.markup)?void 0:r.enabled),g=!1!==(null==(n=null==s?void 0:s.notes)?void 0:n.enabled);if(!1===(null==c?void 0:c.enabled))return;if(!u&&!g&&!(null==(h=null==c?void 0:c.extraActions)?void 0:h.length))return;const{provides:f}=a.useCapability(o.SelectionPlugin.id),{provides:m}=a.useCapability(p.AnnotationPlugin.id),{provides:v}=a.useCapability(Gt.id);return e.useMemo(()=>e=>{const a=vt(e.item);return r=>{var o;return t.jsx("div",{...r.menuWrapperProps,children:t.jsx(pe,{placementAbove:!!(null==(o=r.placement)?void 0:o.suggestTop),anchorHeight:r.rect.size.height,onAction:t=>{var r,o;if("highlight"!==t&&"underline"!==t&&"squiggly"!==t&&"strikeout"!==t){if("note"===t){if(!f||!v||!g)return;const t=f.getHighlightRectsForPage(e.item.localPageIndex,a);return void bt(f.getSelectedText(a),a=>{v.requestCreateFromSelection({chapterId:e.item.chapterId,localPageIndex:e.item.localPageIndex,globalPageIndex:e.item.globalPageIndex,globalPageNumber:e.item.globalPageNumber,rectsPdfCoord:t,selectedText:a.join("\n")})})}null==(r=null==i?void 0:i.onExtraAction)||r.call(i,t,e)}else{if(!f||!m||!u)return;!function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,c={...oe[g=e],...null==(f=i)?void 0:f[g]},u=o.getFormattedSelection();var g,f;if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=d.uuidV4(),a=c.color??l.color??l.strokeColor,s=c.opacity??l.opacity,i=c.thickness??l.strokeWidth,o=c.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?he(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?le(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:ne[e],..."highlight"===e?{blendMode:d.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}o.clear()}(a,Ie[t],m,f,null==(o=null==s?void 0:s.markup)?void 0:o.styles)}},hiddenBuiltinActions:null==c?void 0:c.hiddenBuiltinActions,extraActions:null==c?void 0:c.extraActions})})}},[m,null==(l=null==s?void 0:s.markup)?void 0:l.styles,null==i?void 0:i.onExtraAction,u,v,g,f,null==c?void 0:c.extraActions,null==c?void 0:c.hiddenBuiltinActions])}const Ce="chapter-manager",Me={id:Ce,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Se={kind:"first-wins"};function xe(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Le=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const $e=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Se,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Se,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Se){const a=function(t,e=Se){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,xe(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Le(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};$e.id="chapter-manager";let ke=$e;const De={manifest:Me,create:t=>new ke(Ce,t),reducer:t=>t,initialState:{}};function Te(t,e=.5,a=3){return Math.min(a,Math.max(e,t))}function ze(t,e,a){return Math.min(a,Math.max(e,t))}const Oe={chapters:[]};function Ge(t){const s=e.useRef(null),{provides:i}=a.useCapability(ke.id),r=e.useMemo(()=>(null==i?void 0:i.getManifest())??Oe,[i]),{scale:o,setScale:n,zoomEnabled:h,minZoom:d,maxZoom:u}=function(t,s){const{registry:i}=a.useRegistry(),{provides:r}=a.useCapability(c.DocumentManagerPlugin.id),{provides:o}=a.useCapability(ke.id),n=!1!==(null==s?void 0:s.enabled),h=(null==s?void 0:s.min)??.5,d=(null==s?void 0:s.max)??3,u=null==s?void 0:s.pageWidth,[p,g]=e.useState(()=>(null==s?void 0:s.initial)??1),f=e.useRef(p),m=e.useCallback(e=>{const a=Te(e,h,d);f.current=a,g(a),function(t,e,a,s=.5,i=3){const r=null==t?void 0:t.getStore();if(!r)return;const o=Te(a,s,i);r.dispatchToCore(l.setDefaultScale(o));for(const n of e.chapters)r.getState().core.documents[n.chapterId]&&r.dispatchToCore(l.setScale(o,n.chapterId))}(i,t,a,h,d)},[i,t,h,d]),v=e.useCallback(t=>{if(!u||!r)return;const e=r.getDocument(t);e&&m(function(t,e,a=0){var s;const i=t.pages[a];return(null==(s=null==i?void 0:i.size)?void 0:s.width)?e/i.size.width:1}(e,u))},[m,r,u]);return e.useEffect(()=>{n&&i&&(u||m((null==s?void 0:s.initial)??1))},[m,n,u,i,null==s?void 0:s.initial]),e.useEffect(()=>{if(!n||!o)return;const e=t=>{u?v(t):m(f.current)},a=o.onChapterStatusChange(t=>{"loaded"===t.status&&e(t.chapterId)});for(const s of t.chapters)"loaded"===o.getChapterStatus(s.chapterId)&&e(s.chapterId);return a},[v,m,o,n,t.chapters,u]),{scale:p,setScale:m,zoomEnabled:n,minZoom:h,maxZoom:d}}(r,null==t?void 0:t.zoom);return function(t,a){const{enabled:s,getScale:i,setScale:r,minZoom:o,maxZoom:n}=a;e.useEffect(()=>{if(s)return function(t,e){if(!t||!1===e.enabled)return()=>{};let a=null,s=null,i=0;const r=()=>{const s=t.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==a||a(),a=function({container:t,getScale:e,setScale:a,minZoom:s=.5,maxZoom:i=3}){let r=0,o=1,n=null,h=1,l=1;const d=t=>{(t.ctrlKey||t.metaKey)&&(t.preventDefault(),null===n?(l=e(),h=1):clearTimeout(n),h*=1-.01*t.deltaY,h=ze(h,.1,10),a(ze(l*h,s,i)),n=setTimeout(()=>{n=null},120))},c=new Map,u=t=>{if(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size){const[t,a]=[...c.values()];r=Math.hypot(a.x-t.x,a.y-t.y),o=e()}},p=t=>{if(c.has(t.pointerId)&&(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size&&r>0)){t.preventDefault();const[e,n]=[...c.values()],h=Math.hypot(n.x-e.x,n.y-e.y);a(ze(o*(h/r),s,i))}},g=t=>{c.delete(t.pointerId),c.size<2&&(r=0)};return t.addEventListener("wheel",d,{passive:!1}),t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p,{passive:!1}),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("wheel",d),t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g),n&&clearTimeout(n)}}({container:s,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom}),!0)};return r()||(s=new MutationObserver(()=>{r()&&(null==s||s.disconnect(),s=null)}),s.observe(t,{childList:!0,subtree:!0}),i=requestAnimationFrame(()=>r())),()=>{i&&cancelAnimationFrame(i),null==s||s.disconnect(),null==a||a()}}(t.current,{enabled:!0,getScale:i,setScale:r,minZoom:o,maxZoom:n})},[s,i,t,n,o,r])}(s,{enabled:h,getScale:()=>o,setScale:n,minZoom:d,maxZoom:u}),{hostRef:s,scale:o,setScale:n,zoomEnabled:h}}function Ae({className:s,buildSelectionMenu:i,annotationSelectionMenu:r,redactionSelectionMenu:o,showNoteMarkers:n=!0,showBookmarkMarkers:h=!0,showRedactionLayer:l=!1,renderPageOverlay:d,features:c,onExtraSelectionAction:u,children:p}){var g,f,m,v;const{hostRef:b}=Ge(c),P=function(){const{registry:t}=a.useRegistry();return e.useMemo(()=>{var e,a;const s=null==(a=null==(e=null==t?void 0:t.getPlugin(Gt.id))?void 0:e.provides)?void 0:a.call(e);return s?t=>s.createNoteFromSelection(t):null},[t])}(),w=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(Gt.id))}(),I=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(ae.id))}(),y=n&&w&&!1!==(null==(g=null==c?void 0:c.notes)?void 0:g.enabled),C=h&&I&&!1!==(null==(f=null==c?void 0:c.bookmarks)?void 0:f.enabled),M=I&&!1!==(null==(m=null==c?void 0:c.bookmarks)?void 0:m.enabled),S=ye(c,{onExtraAction:u}),x=e.useMemo(()=>{if(i||S)return t=>{const e=S?S(t):t.defaultMenu;return i?i({...t,defaultMenu:e}):e}},[i,S]),L=e.useMemo(()=>d||M?e=>{var a;return t.jsxs(t.Fragment,{children:[M&&t.jsx(Ee,{item:e,hoverUi:null==(a=null==c?void 0:c.bookmarks)?void 0:a.hover}),null==d?void 0:d(e)]})}:d,[null==(v=null==c?void 0:c.bookmarks)?void 0:v.hover,M,d]);return t.jsxs("div",{ref:b,className:s,style:s?void 0:re,children:[t.jsx(G,{renderPage:e=>{var a,s;return t.jsx(Ne,{item:e,showNoteMarkers:y,showBookmarkMarkers:C,noteMarkerUi:null==(a=null==c?void 0:c.notes)?void 0:a.marker,bookmarkMarkerUi:null==(s=null==c?void 0:c.bookmarks)?void 0:s.marker,renderPageOverlay:L,buildSelectionMenu:x,createNote:P,annotationSelectionMenu:r,redactionSelectionMenu:o,showRedactionLayer:l})}}),p]})}function Ee({item:e,hoverUi:s}){var i;const r=vt(e),o=a.useDocumentState(r),n=(null==(i=null==o?void 0:o.document)?void 0:i.pages[e.localPageIndex])??null;return n?t.jsx(ie,{item:e,pdfPageWidth:n.size.width,pdfPageHeight:n.size.height,cssPageWidth:e.width,cssPageHeight:e.height,hoverUi:s}):null}function Ne({item:l,showNoteMarkers:d,showBookmarkMarkers:u,noteMarkerUi:p,bookmarkMarkerUi:g,renderPageOverlay:f,createNote:m,buildSelectionMenu:v,annotationSelectionMenu:b,redactionSelectionMenu:P,showRedactionLayer:w=!1}){var I;const y=vt(l);!function(t){const{provides:s}=a.useCapability(c.DocumentManagerPlugin.id);e.useEffect(()=>{s&&t&&s.isDocumentOpen(t)&&s.setActiveDocument(t)},[s,t])}(y);const C=a.useDocumentState(y),M=(null==(I=null==C?void 0:C.document)?void 0:I.pages[l.localPageIndex])??null,S=function(s,i){const{provides:r}=a.useCapability(o.SelectionPlugin.id),n=vt(s);return e.useMemo(()=>{if(i)return e=>{var a;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(a=e.placement)?void 0:a.suggestTop)?-40:e.rect.size.height+8};return t.jsx("div",{...e.menuWrapperProps,children:t.jsx("div",{style:o,children:t.jsx("button",{type:"button",onClick:()=>{if(!r)return;const t=r.getHighlightRectsForPage(s.localPageIndex,n);bt(r.getSelectedText(n),e=>{const a=e.join("\n"),r=function(t,e,a){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageIndex:t.globalPageIndex,globalPageNumber:t.globalPageNumber,rectsPdfCoord:e,selectedText:a}}(s,t,a);i(r)})},style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e5e7eb",borderRadius:"6px",background:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},children:"添加附注"})})})}},[i,n,s,r])}(l,m),x=void 0!==v?v({item:l,defaultMenu:S,createNote:m}):S;return M?t.jsx(s.GlobalPointerProvider,{documentId:y,children:t.jsx(i.Rotate,{documentId:y,pageIndex:l.localPageIndex,style:{backgroundColor:"#fff"},children:t.jsxs(s.PagePointerProvider,{documentId:y,pageIndex:l.localPageIndex,children:[t.jsx(A,{chapterId:y,localPageIndex:l.localPageIndex}),t.jsx(r.SelectionLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:x}),w&&t.jsx(h.RedactionLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:P}),t.jsx(n.AnnotationLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:b}),u&&M&&t.jsx(mt,{chapterId:y,localPageIndex:l.localPageIndex,pdfPageWidth:M.size.width,pdfPageHeight:M.size.height,cssPageWidth:l.width,cssPageHeight:l.height,ui:g}),null==f?void 0:f(l),d&&M&&t.jsx(X,{chapterId:y,localPageIndex:l.localPageIndex,pdfPageWidth:M.size.width,pdfPageHeight:M.size.height,cssPageWidth:l.width,cssPageHeight:l.height,ui:p})]})})}):null}const Re="chapter-scroll",Ve={id:Re,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},_e={kind:"first-wins"};function Ue(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Fe{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const qe=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=_e,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??_e,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=_e){const a=function(t,e=_e){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ue(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Fe(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};qe.id="chapter-manager";let Be=qe;const je=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Be.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};je.id="chapter-scroll";let We=je;const He={manifest:Ve,create:t=>new We(Re,t),reducer:t=>t,initialState:{}},Ye={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class Ze{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(Ye);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=Ke(a.items,s,e.position)}return t}}function Ke(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const Xe={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Qe(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}function Je(t){return function(t){var e,a,s,i,r,n;const h=t.toolbar??{},d=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=d.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new Ze;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=Xe[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:d}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?Qe(x.list()):{},...t.commands??{}},$=[l.createPluginRegistration(c.DocumentManagerPluginPackage,{initialDocuments:[]}),l.createPluginRegistration(De,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),l.createPluginRegistration(He,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),l.createPluginRegistration(g.InteractionManagerPluginPackage),l.createPluginRegistration(f.RenderPluginPackage),l.createPluginRegistration(m.RotatePluginPackage),l.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),l.createPluginRegistration(v.HistoryPluginPackage),l.createPluginRegistration(p.AnnotationPluginPackage),l.createPluginRegistration(b.RedactionPluginPackage),l.createPluginRegistration(P.FormPluginPackage),l.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),l.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[l.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[l.createPluginRegistration(C.I18nPluginPackage),l.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(l.createPluginRegistration(Et,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(l.createPluginRegistration(se,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}({...t,toolbar:t.toolbar??{enabledModes:[]},features:ce(t.features)})}ce();const ta={overlapStrategy:{kind:"first-wins"},passwordProvider:new class{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}}(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};const ea="chapter-manager",aa={id:ea,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},sa={kind:"first-wins"};function ia(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ra=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const oa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=sa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??sa,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=sa){const a=function(t,e=sa){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ia(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ra(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};oa.id="chapter-manager";let na=oa;const ha={manifest:aa,create:t=>new na(ea,t),reducer:t=>t,initialState:{}},la="chapter-scroll",da={id:la,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},ca={kind:"first-wins"};function ua(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class pa{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const ga=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=ca,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??ca,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=ca){const a=function(t,e=ca){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ua(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new pa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};ga.id="chapter-manager";let fa=ga;const ma=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(fa.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ma.id="chapter-scroll";let va=ma;const ba={manifest:da,create:t=>new va(la,t),reducer:t=>t,initialState:{}},Pa="note",wa={id:Pa,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},Ia={kind:"first-wins"};function ya(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ca=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ma=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ia,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ia,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Ia){const a=function(t,e=Ia){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ya(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ca(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ma.id="chapter-manager";let Sa=Ma;const xa={kind:"first-wins"};function La(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $a=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const ka=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=xa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??xa,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=xa){const a=function(t,e=xa){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,La(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $a(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};ka.id="chapter-manager";let Da=ka;const Ta=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Da.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Ta.id="chapter-scroll";let za=Ta;const Oa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(za.id),this.chapterManager=this.registry.getPlugin(Sa.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:Aa(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Oa.id="note";let Ga=Oa;function Aa(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const Ea={manifest:wa,create:t=>new Ga(Pa,t),reducer:t=>t,initialState:{}},Na="paragraph-bookmark",Ra={id:Na,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Va={kind:"first-wins"};function _a(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ua=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Fa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Va,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Va,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Va){const a=function(t,e=Va){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,_a(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ua(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Fa.id="chapter-manager";let qa=Fa;const Ba={kind:"first-wins"};function ja(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Wa{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Ha=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ba,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ba,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Ba){const a=function(t,e=Ba){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ja(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Wa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ha.id="chapter-manager";let Ya=Ha;const Za=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ya.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Za.id="chapter-scroll";let Ka=Za;function Xa(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Qa(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Ja(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Xa(i),n=e.markerAnchor??Xa(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Qa(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const ts=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Ka.id),this.chapterManager=this.registry.getPlugin(qa.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Ja(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};ts.id="paragraph-bookmark";let es=ts;const as={manifest:Ra,create:t=>new es(Na,t),reducer:t=>t,initialState:{}},ss={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class is{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(ss);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=rs(a.items,s,e.position)}return t}}function rs(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const os={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function ns(t){var e,a,s,i,r,n;const h=t.toolbar??{},d=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=d.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new is;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=os[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:d}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?hs(x.list()):{},...t.commands??{}},$=[l.createPluginRegistration(c.DocumentManagerPluginPackage,{initialDocuments:[]}),l.createPluginRegistration(ha,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),l.createPluginRegistration(ba,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),l.createPluginRegistration(g.InteractionManagerPluginPackage),l.createPluginRegistration(f.RenderPluginPackage),l.createPluginRegistration(m.RotatePluginPackage),l.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),l.createPluginRegistration(v.HistoryPluginPackage),l.createPluginRegistration(p.AnnotationPluginPackage),l.createPluginRegistration(b.RedactionPluginPackage),l.createPluginRegistration(P.FormPluginPackage),l.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),l.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[l.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[l.createPluginRegistration(C.I18nPluginPackage),l.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(l.createPluginRegistration(Ea,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(l.createPluginRegistration(as,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}function hs(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}function ls(t,e){const a=t;return!1===t?{...e,enabled:!1}:!0===t||void 0===t?{...e,enabled:e.enabled??!0}:{...e,...a,enabled:!1!==(null==a?void 0:a.enabled)}}function ds(t){const e=ls(null==t?void 0:t.markup,{enabled:!0}),a=ls(null==t?void 0:t.bookmarks,{enabled:!0}),s=ls(null==t?void 0:t.notes,{enabled:!0});return{markup:e,bookmarks:a,notes:s,zoom:ls(null==t?void 0:t.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:ls(void 0===(null==t?void 0:t.selectionToolbar)?!1!==e.enabled||!1!==s.enabled:t.selectionToolbar,{enabled:!0})}}d.PdfAnnotationSubtype.HIGHLIGHT,d.PdfAnnotationSubtype.UNDERLINE,d.PdfAnnotationSubtype.SQUIGGLY,d.PdfAnnotationSubtype.STRIKEOUT;const cs=ds();function us(t){return ns({...t,toolbar:t.toolbar??{enabledModes:[]},features:ds(t.features)})}const ps={overlapStrategy:{kind:"first-wins"},passwordProvider:new class{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}}(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function gs(t){return"callbacks"in t.notes?{manifest:t.manifest,chapterPdfLoader:t.chapterPdfLoader,notes:t.notes.callbacks,bookmarks:t.bookmarks.callbacks}:t}function fs(t){return{manifest:t.manifest,chapterPdfLoader:t.chapterPdfLoader,...ps,notes:{callbacks:t.notes},bookmarks:{callbacks:t.bookmarks},features:ds(t.features)}}const ms={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},vs={highlight:d.PdfAnnotationSubtype.HIGHLIGHT,underline:d.PdfAnnotationSubtype.UNDERLINE,squiggly:d.PdfAnnotationSubtype.SQUIGGLY,strikeout:d.PdfAnnotationSubtype.STRIKEOUT};function bs(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function Ps(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function ws(t,e){const a=t;return!1===t?{...e,enabled:!1}:!0===t||void 0===t?{...e,enabled:e.enabled??!0}:{...e,...a,enabled:!1!==(null==a?void 0:a.enabled)}}const Is={kind:"first-wins"};function ys(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Cs=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function Ms(t,e=Is){const a=function(t,e=Is){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ys(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Cs(r)}const Ss=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Is,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Is,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Ms(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ss.id="chapter-manager";let xs=Ss;const Ls={kind:"first-wins"};function $s(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class ks{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function Ds(t,e=Ls){const a=function(t,e=Ls){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,$s(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ks(r)}const Ts=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ls,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ls,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Ds(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ts.id="chapter-manager";let zs=Ts;const Os=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(zs.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Os.id="chapter-scroll";let Gs=Os;function As(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function Es(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Ns(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);if(o<=0)return 0;return Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Rs(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Es(i),n=e.markerAnchor??Es(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Ns(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}async function Vs(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Gs.id),this.chapterManager=this.registry.getPlugin(xs.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Rs(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await Vs(a,s,i)}}).id="paragraph-bookmark";const _s={kind:"first-wins"};function Us(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Fs=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function qs(t,e=_s){const a=function(t,e=_s){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Us(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Fs(r)}const Bs=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=_s,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??_s,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=qs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Bs.id="chapter-manager";let js=Bs;const Ws={kind:"first-wins"};function Hs(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Ys{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function Zs(t,e=Ws){const a=function(t,e=Ws){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Hs(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ys(r)}const Ks=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ws,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ws,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Zs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ks.id="chapter-manager";let Xs=Ks;const Qs=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Xs.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Qs.id="chapter-scroll";let Js=Qs;const ti={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"};function ei({nodes:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r}){return t.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",marginLeft:a>0?12:0},children:e.map(e=>t.jsx(ai,{node:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r},e.id))})}function ai({node:a,depth:s,activeChapterId:i,chapterStatus:r,onSelect:o}){const n=a.children??[],h=n.length>0,[l,d]=e.useState(s<1),c=i===a.id,u=r[a.id]??"idle",p=!h;return t.jsxs("li",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"stretch",gap:2},children:[h?t.jsx("button",{type:"button","aria-expanded":l,style:oi,onClick:()=>d(t=>!t),children:l?"▼":"▶"}):t.jsx("span",{style:{width:16,flexShrink:0},"aria-hidden":!0}),t.jsxs("button",{type:"button",style:{...ni,background:c?"#1e293b":"transparent",color:c?"#fff":"#334155"},onClick:()=>o(a.id),children:[t.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:a.title}),t.jsxs("div",{style:{marginTop:2,fontSize:10,color:c?"#cbd5e1":"#94a3b8",display:"flex",flexWrap:"wrap",gap:"4px 8px"},children:[t.jsxs("span",{children:["第 ",a.startPage,a.endPage!==a.startPage?`–${a.endPage}`:""," 页"]}),p?t.jsx("span",{children:ti[u]}):null]})]})]}),h&&l?t.jsx(ei,{nodes:n,depth:s+1,activeChapterId:i,chapterStatus:r,onSelect:o}):null]})}const si={display:"flex",flexDirection:"column",width:224,flexShrink:0,borderRadius:8,border:"1px solid #e2e8f0",background:"#fff",overflow:"hidden"},ii={margin:0,padding:"8px 12px",fontSize:12,fontWeight:600,color:"#334155",borderBottom:"1px solid #f1f5f9"},ri={flex:1,overflowY:"auto",padding:4},oi={flexShrink:0,padding:"0 4px",border:"none",background:"transparent",fontSize:10,color:"#94a3b8",cursor:"pointer"},ni={minWidth:0,flex:1,border:"none",borderRadius:6,padding:"8px",textAlign:"left",fontSize:13,cursor:"pointer"};Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>a.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>a.useCapability}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>S.usePdfiumEngine}),exports.CallbackPasswordProvider=class{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}},exports.ChapterManagerPlugin=js,exports.ChapterPdfViewer=function({engine:s,options:i,editorOptions:r,features:o,className:n,viewportClassName:h,buildSelectionMenu:l,onExtraSelectionAction:d,renderPageOverlay:c,children:u}){const{plugins:p,features:g}=e.useMemo(()=>function(t){if(t.options)return function(t){const e=function(t){return{manifest:t.manifest,chapterPdfLoader:t.chapterPdfLoader,...ta,notes:{callbacks:t.notes},bookmarks:{callbacks:t.bookmarks},features:ce(t.features)}}("callbacks"in(s=t).notes?{manifest:s.manifest,chapterPdfLoader:s.chapterPdfLoader,notes:s.notes.callbacks,bookmarks:s.bookmarks.callbacks}:s),{plugins:a}=Je(e);var s;return{plugins:a,features:e.features,editorOptions:e}}(t.options);if(!t.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const e=ce(t.features),{plugins:a}=Je({...t.editorOptions,features:e});return{plugins:a,features:e,editorOptions:{...t.editorOptions,features:e}}}({options:i,editorOptions:r,features:o}),[r,o,i]);return t.jsx("div",{className:n,style:n?void 0:re,children:t.jsx(a.EmbedPDF,{engine:s,plugins:p,children:({pluginsReady:e})=>e?t.jsx(Ae,{className:h,features:g,buildSelectionMenu:l,onExtraSelectionAction:d,renderPageOverlay:c,children:u}):null})})},exports.ChapterScrollPlugin=Js,exports.ChapterTreePanel=function({tree:s,activeChapterId:i,onActiveChapterChange:r}){const{provides:o}=a.useCapability(Js.id),{provides:n}=a.useCapability(js.id),[h,l]=e.useState({}),d=e.useCallback(()=>{if(!n)return;const t={},e=a=>{var s;for(const i of a)t[i.id]=n.getChapterStatus(i.id),(null==(s=i.children)?void 0:s.length)&&e(i.children)};e(s),l(t)},[n,s]);return e.useEffect(()=>{d()},[d]),e.useEffect(()=>{if(n)return n.onChapterStatusChange(d)},[n,d]),t.jsxs("aside",{style:si,children:[t.jsx("h2",{style:ii,children:"章节目录"}),t.jsx("nav",{style:ri,"aria-label":"章节目录",children:t.jsx(ei,{nodes:s,depth:0,activeChapterId:i,chapterStatus:h,onSelect:t=>{null==r||r(t),null==o||o.scrollToChapter(t)}})})]})},exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=cs,exports.PdfChapterViewport=Ae,exports.applySelectionMarkup=function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,c=function(t,e){return{...ms[t],...null==e?void 0:e[t]}}(e,i),u=o.getFormattedSelection();if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=d.uuidV4(),a=c.color??l.color??l.strokeColor,s=c.opacity??l.opacity,i=c.thickness??l.strokeWidth,o=c.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?bs(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?Ps(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:vs[e],..."highlight"===e?{blendMode:d.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}return o.clear(),!0},exports.buildParagraphBookmarkAnchor=function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:As(i),rectsPdfCoord:i,markerAnchor:Es(i)}},exports.createChapterViewerBundle=function(t){const e=fs(gs(t)),{plugins:a}=us(e);return{plugins:a,features:e.features,editorOptions:e}},exports.createChapterViewerEditor=us,exports.createChapterViewerEditorOptions=function(t){const{features:e,...a}=fs(gs(t));return a},exports.createPdfChapterEditor=ns,exports.normalizeChapterViewerConfig=function(t){const e=ws(null==t?void 0:t.markup,{enabled:!0}),a=ws(null==t?void 0:t.bookmarks,{enabled:!0}),s=ws(null==t?void 0:t.notes,{enabled:!0});return{markup:e,bookmarks:a,notes:s,zoom:ws(null==t?void 0:t.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:ws(void 0===(null==t?void 0:t.selectionToolbar)?!1!==e.enabled||!1!==s.enabled:t.selectionToolbar,{enabled:!0})}};
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|