@embedpdf-editor/vue3-chapter-viewer 1.1.3 → 1.1.4

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/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),s=require("@embedpdf/plugin-annotation"),r=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),i=require("@embedpdf/plugin-interaction-manager"),o=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),c=require("@embedpdf/plugin-history"),d=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),m=require("@embedpdf/plugin-commands"),f=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),P=require("@embedpdf/plugin-interaction-manager/vue"),I=require("@embedpdf/plugin-rotate/vue"),S=require("@embedpdf/plugin-selection/vue"),b=require("@embedpdf/plugin-annotation/vue"),C=require("@embedpdf/plugin-redaction/vue"),y=require("@embedpdf/plugin-render/vue"),w=require("@embedpdf/engines/vue"),M={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function L(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const $="#f1f5f9",k={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},D={highlight:r.PdfAnnotationSubtype.HIGHLIGHT,underline:r.PdfAnnotationSubtype.UNDERLINE,squiggly:r.PdfAnnotationSubtype.SQUIGGLY,strikeout:r.PdfAnnotationSubtype.STRIKEOUT};function U(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function E(e){let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function V(e,t,n,a,i){const o=n.forDocument(e),l=a.forDocument(e);if(!o||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",c=n.getTool(h);if(!c)return!1;const d=c.defaults,u={...k[g=t],...null==(m=i)?void 0:m[g]},p=l.getFormattedSelection();var g,m;if(0===p.length)return!1;o.setLocked({type:s.LockModeType.Exclude,categories:["markup","shape"]});for(const s of p){const e=r.uuidV4(),n=u.color??d.color??d.strokeColor,a=u.opacity??d.opacity,i=u.thickness??d.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(s.segmentRects,l):s.segmentRects,c="underline"===t||"squiggly"===t||"strikeout"===t?E(h):s.rect;o.createAnnotation(s.pageIndex,{id:e,created:new Date,flags:["print"],type:D[t],..."highlight"===t?{blendMode:r.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=i?{strokeWidth:i}:{},pageIndex:s.pageIndex,rect:c,segmentRects:h})}return l.clear(),!0}const A=new Set([r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT]);function T(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}function N(e){var t;const s=T(null==e?void 0:e.markup,{enabled:!0}),r=T(null==e?void 0:e.bookmarks,{enabled:!0}),n=T(null==e?void 0:e.notes,{enabled:!0}),a=T(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),i=T(void 0===(null==e?void 0:e.selectionToolbar)?!1!==s.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:s,bookmarks:r,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??$},selectionToolbar:i}}function F(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function O(e,t){return`${e}#s${t}`}function R(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return F(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=F(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:O(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}let z=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const B="chapter-manager",G={id:B,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,maxConcurrentSegmentLoads:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function _(e){const[t,s]=e.localPageRange;return s-t+1}function W(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function q(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return W(t)?t.segmentPageThreshold:null}function H(e,t){return`${e}#s${t}`}function K(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function j(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function X(e){const t=q(e);if(!t)return null;const s=_(e),r=j(s,t),n=W(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:H(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Y(e,t){const s=X(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Z(e,t){const s=X(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function J(e){var t;const s=q(e);if(!s)return[];const r=[],{chapterId:n}=e,a=_(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!W(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=j(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Q={kind:"first-wins"};function ee(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let te=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const se=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Q,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Q,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=K(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=K(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=K(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Y(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?X(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...J(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Q){const s=function(e,t=Q){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ee(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new te(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?X(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Z(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(W(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=X(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=X(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Z(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Z(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Y(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=X(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(W(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=q(t);if(a){const r=j(_(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(W(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=K(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?X(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};se.id="chapter-manager";let re=se;const ne={manifest:G,create:e=>new re(B,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",ie={id:ae,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:0,placeholderPageWidth:0,bufferSize:2,pageGap:20}};function oe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function le(e,t){return`${e}#s${t}`}function he(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ce(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return oe(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=oe(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function de(e){const[t,s]=e.localPageRange;return s-t+1}function ue(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function pe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ue(t)?t.segmentPageThreshold:null}function ge(e,t){return`${e}#s${t}`}function me(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function fe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ve(e){const t=pe(e);if(!t)return null;const s=de(e),r=fe(s,t),n=ue(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:ge(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Pe(e,t){const s=ve(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ie(e,t){const s=ve(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Se(e){var t;const s=pe(e);if(!s)return[];const r=[],{chapterId:n}=e,a=de(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ue(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=fe(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const be={kind:"first-wins"};function Ce(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ye=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const we=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=be,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??be,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=me(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=me(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=me(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Pe(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ve(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Se(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=be){const s=function(e,t=be){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ce(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ye(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ve(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ie(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ue(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ve(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ve(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ie(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Ie(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Pe(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ve(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ue(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=pe(t);if(a){const r=fe(de(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ue(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=me(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ve(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};we.id="chapter-manager";let Me=we;function xe(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const Le=792/612;function $e(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function ke(e){return 0===e.length?null:{width:$e(e.map(e=>e.width)),height:$e(e.map(e=>e.height))}}function De(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*Le)}}const Ue=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,xe),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Me.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=ce(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=ke(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=ke(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=ke(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=De(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?De(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=ce(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=he(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Ue.id="chapter-scroll";let Ee=Ue;const Ve={manifest:ie,create:e=>new Ee(ae,e),reducer:e=>e,initialState:{}},Ae="note",Te={id:Ae,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}};function Ne(e){const[t,s]=e.localPageRange;return s-t+1}function Fe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Oe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fe(t)?t.segmentPageThreshold:null}function Re(e,t){return`${e}#s${t}`}function ze(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Be(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ge(e){const t=Oe(e);if(!t)return null;const s=Ne(e),r=Be(s,t),n=Fe(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Re(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function _e(e,t){const s=Ge(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function We(e,t){const s=Ge(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function qe(e){var t;const s=Oe(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ne(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Fe(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Be(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const He={kind:"first-wins"};function Ke(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let je=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Xe=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=He,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??He,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ze(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ze(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ze(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?_e(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ge(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...qe(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=He){const s=function(e,t=He){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ke(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new je(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ge(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=We(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Fe(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ge(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ge(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=We(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=We(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=_e(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ge(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Fe(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Oe(t);if(a){const r=Be(Ne(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Fe(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ze(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ge(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Xe.id="chapter-manager";let Ye=Xe;function Ze(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Je(e,t){return`${e}#s${t}`}function Qe(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function et(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ze(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Ze(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Je(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function tt(e){const[t,s]=e.localPageRange;return s-t+1}function st(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function rt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return st(t)?t.segmentPageThreshold:null}function nt(e,t){return`${e}#s${t}`}function at(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function it(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ot(e){const t=rt(e);if(!t)return null;const s=tt(e),r=it(s,t),n=st(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:nt(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function lt(e,t){const s=ot(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ht(e,t){const s=ot(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ct(e){var t;const s=rt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=tt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!st(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=it(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const dt={kind:"first-wins"};function ut(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let pt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const gt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=dt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??dt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=at(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=at(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=at(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?lt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ot(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ct(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=dt){const s=function(e,t=dt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ut(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new pt(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ot(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ht(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(st(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ot(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ot(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=ht(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=ht(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=lt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ot(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(st(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=rt(t);if(a){const r=it(tt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(st(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=at(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ot(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};gt.id="chapter-manager";let mt=gt;function ft(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const vt=792/612;function Pt(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function It(e){return 0===e.length?null:{width:Pt(e.map(e=>e.width)),height:Pt(e.map(e=>e.height))}}function St(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*vt)}}const bt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ft),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(mt.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=et(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Qe(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Qe(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=It(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=It(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=It(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=St(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?St(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=et(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Qe(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};bt.id="chapter-scroll";let Ct=bt;const yt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Ct.id),this.chapterManager=this.registry.getPlugin(Ye.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Mt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};yt.id="note";let wt=yt;function Mt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const xt={manifest:Te,create:e=>new wt(Ae,e),reducer:e=>e,initialState:{}},Lt="paragraph-bookmark",$t={id:Lt,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function kt(e){const[t,s]=e.localPageRange;return s-t+1}function Dt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ut(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Dt(t)?t.segmentPageThreshold:null}function Et(e,t){return`${e}#s${t}`}function Vt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function At(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Tt(e){const t=Ut(e);if(!t)return null;const s=kt(e),r=At(s,t),n=Dt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Et(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Nt(e,t){const s=Tt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ft(e,t){const s=Tt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ot(e){var t;const s=Ut(e);if(!s)return[];const r=[],{chapterId:n}=e,a=kt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Dt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=At(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Rt={kind:"first-wins"};function zt(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Bt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Gt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Rt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Rt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Vt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Vt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Vt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Nt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Tt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ot(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Rt){const s=function(e,t=Rt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,zt(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Bt(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Tt(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ft(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Dt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Tt(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Tt(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ft(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Ft(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Nt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Tt(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Dt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ut(t);if(a){const r=At(kt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Dt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Vt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Tt(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Gt.id="chapter-manager";let _t=Gt;function Wt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function qt(e,t){return`${e}#s${t}`}function Ht(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Kt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Wt(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Wt(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:qt(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function jt(e){const[t,s]=e.localPageRange;return s-t+1}function Xt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Yt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xt(t)?t.segmentPageThreshold:null}function Zt(e,t){return`${e}#s${t}`}function Jt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Qt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function es(e){const t=Yt(e);if(!t)return null;const s=jt(e),r=Qt(s,t),n=Xt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Zt(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ts(e,t){const s=es(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ss(e,t){const s=es(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function rs(e){var t;const s=Yt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=jt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Xt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Qt(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ns={kind:"first-wins"};function as(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let is=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const os=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ns,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ns,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Jt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Jt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Jt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?ts(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?es(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...rs(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ns){const s=function(e,t=ns){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,as(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new is(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?es(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ss(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Xt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=es(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=es(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=ss(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=ss(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=ts(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=es(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Xt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Yt(t);if(a){const r=Qt(jt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Xt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Jt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?es(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};os.id="chapter-manager";let ls=os;function hs(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const cs=792/612;function ds(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function us(e){return 0===e.length?null:{width:ds(e.map(e=>e.width)),height:ds(e.map(e=>e.height))}}function ps(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*cs)}}const gs=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,hs),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ls.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Kt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ht(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ht(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=us(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=us(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=us(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=ps(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?ps(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=Kt(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Ht(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};gs.id="chapter-scroll";let ms=gs;function fs(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function vs(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ps(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function Is(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??vs(n),o=t.markerAnchor??vs(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(Ps(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}function Ss(e,t,s,r){const n=s.length>0?s:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==r?void 0:r.globalPageIndex,globalPageNumber:null==r?void 0:r.globalPageNumber,rectPdfCoord:fs(n),rectsPdfCoord:n,markerAnchor:vs(n)}}const bs=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ms.id),this.chapterManager=this.registry.getPlugin(_t.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(Is(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};bs.id="paragraph-bookmark";let Cs=bs;const ys={manifest:$t,create:e=>new Cs(Lt,e),reducer:e=>e,initialState:{}},ws={"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 Ms{constructor(){this.specs=[]}register(e){if(this.specs.some(t=>t.id===e.id))throw new Error(`OperationRegistry: duplicate operation id "${e.id}"`);this.specs.push(e)}registerAll(e){for(const t of e)t&&this.register(t)}list(){return this.specs}buildToolbars(){const e=structuredClone(ws);for(const t of this.specs){const s=e[t.toolbarSlot];if(!s)continue;const r={type:"command-button",id:t.id,commandId:t.commandId,variant:"icon",...t.icon?{icon:t.icon}:{},...t.i18nKey?{labelKey:t.i18nKey}:{},...t.label?{label:t.label}:{},categories:t.categories??[]};s.items=xs(s.items,r,t.position)}return e}}function xs(e,t,s){return(null==s?void 0:s.after)||(null==s?void 0:s.before)?function(e,t,s){const r=e=>{const n=[];for(const a of e)"group"!==a.type?s.before&&a.id===s.before?n.push(t,a):(n.push(a),s.after&&a.id===s.after&&n.push(t)):n.push({...a,items:r(a.items)});return n};return r(e)}(e,t,s):(r=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,r]}:e));var r}const Ls={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function $s(e){var t,r,P,I,S,b;const C=e.toolbar??{},y=C.enabledModes??["view","annotate","shapes","insert","form","redact"],w=y.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,s,r,n,a,i;const o=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new Ms;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),c={};for(const u of o){if("view"===u)continue;const e=Ls[u];h[e]&&(c[e]=h[e])}const d=function(e){if(0===e.size)return null;const t=(e,t,s)=>({type:"command-button",id:`${e}-mode`,commandId:s,variant:"text",label:t,categories:["mode",e]});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:[...e.has("view")?[t("view","View","mode:view")]:[],...e.has("annotate")?[t("annotate","Annotate","mode:annotate")]:[],...e.has("shapes")?[t("shapes","Shapes","mode:shapes")]:[],...e.has("insert")?[t("insert","Insert","mode:insert")]:[],...e.has("form")?[t("form","Form","mode:form")]:[],...e.has("redact")?[t("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(o);return d&&(c["chapter-editor-main-toolbar"]=d),(null==(s=e.extend)?void 0:s.toolbars)&&Object.assign(c,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:c,menus:(null==(r=e.extend)?void 0:r.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(i=e.extend)?void 0:i.selectionMenus)??{}},operationRegistry:l}}({...C,enabledModes:y}),L={...w?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var r,n,a,i;const o=null==(r=e.getPlugin("ui"))?void 0:r.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();o&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),o.forDocument(t).closeToolbarSlot("top","secondary"),null==(i=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked(e.getPluginConfig(s.ANNOTATION_PLUGIN_ID).locked??{type:s.LockModeType.None}))},active:({state:e,documentId:t})=>!v.isToolbarOpen(e.plugins,t,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.None}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...w?ks(x.list()):{},...e.commands??{}},$=[n.createPluginRegistration(a.DocumentManagerPluginPackage,{initialDocuments:[],maxDocuments:Number.MAX_SAFE_INTEGER}),n.createPluginRegistration(ne,{manifest:e.manifest,overlapStrategy:e.overlapStrategy??Es.overlapStrategy,passwordProvider:e.passwordProvider??Es.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters??Es.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads??Es.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs??Es.unloadTimeoutMs}),n.createPluginRegistration(Ve,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(i.InteractionManagerPluginPackage),n.createPluginRegistration(o.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(c.HistoryPluginPackage),n.createPluginRegistration(s.AnnotationPluginPackage),n.createPluginRegistration(d.RedactionPluginPackage),n.createPluginRegistration(u.FormPluginPackage),n.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),n.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(L).length>0?[n.createPluginRegistration(m.CommandsPluginPackage,{commands:L})]:[],...w?[n.createPluginRegistration(f.I18nPluginPackage),n.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&$.push(n.createPluginRegistration(xt,{callbacks:e.notes.callbacks,ui:null==(r=null==(t=e.features)?void 0:t.notes)?void 0:r.marker})),e.bookmarks&&$.push(n.createPluginRegistration(ys,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(b=null==(S=e.features)?void 0:S.bookmarks)?void 0:b.hover})),{plugins:$,uiSchema:M,operationRegistry:x}}function ks(e){const t={};for(const s of e)s.handler&&(t[s.commandId]={id:s.commandId,labelKey:s.i18nKey,label:s.label,icon:s.icon,categories:s.categories,action:({documentId:e})=>{var t;null==(t=s.handler)||t.call(s,{documentId:e,chapterId:e})}});return t}const Ds=N();function Us(e){return $s({...e,toolbar:e.toolbar??{enabledModes:[]},features:N(e.features)})}const Es={overlapStrategy:{kind:"first-wins"},passwordProvider:new z(async()=>null),prefetchChapters:1,maxConcurrentSegmentLoads:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function Vs(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function As(e){return{...Es,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Es.overlapStrategy,prefetchChapters:e.prefetchChapters??Es.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads??Es.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs??Es.unloadTimeoutMs,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:N(e.features)}}function Ts(e){const t=As(Vs(e)),{plugins:s}=Us(t);return{plugins:s,features:t.features,editorOptions:t}}function Ns(e,t=.5,s=3){return Math.min(s,Math.max(t,e))}function Fs(e,t){var s;if(t<=0)return 1;let r=0;for(const n of e.pages){const e=(null==(s=null==n?void 0:n.size)?void 0:s.width)??0;e>r&&(r=e)}return r<=0?1:t/r}function Os(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function Rs(e,t,s,r){const n=Os(t,s);if(n<=0)return r;const a=Fs(e,n);return Math.min(r,a)}function zs(e,t,s){const r=R(t);if(r){for(const t of r.segments){const r=e.getDocument(t.documentId);r&&s(r,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&s(n,t.chapterId)}function Bs(e){return e instanceof HTMLElement?e.clientWidth:0}function Gs(e,t,s){return Math.min(s,Math.max(t,e))}const _s={chapters:[]};function Ws(s){const r=e.ref(null),{provides:i}=t.useCapability(re.id),o=e.computed(()=>{var e;return(null==(e=i.value)?void 0:e.getManifest())??_s}),l=e.computed(()=>{var e;return null==(e=s.value)?void 0:e.zoom}),{scale:h,setScale:c,zoomEnabled:d,minZoom:u,maxZoom:p}=function(s,r,i){const o=e.isRef(s)?s:e.computed(()=>s),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:c}=t.useCapability(re.id),d=e.ref(v()),u=e.ref(d.value),p=e.ref(0),g=e.ref(!1),m=()=>{var e;return null==(e=r.value)?void 0:e.pageWidth},f=()=>{return null!=(e=m())&&e>0;var e},v=()=>{var e;return(null==(e=r.value)?void 0:e.initial)??1},P=e.computed(()=>{var e;return function(e,t,s,r,n){if(!e||s<=0)return n;let a=n;for(const i of t.chapters)zs(e,i,e=>{a=Math.min(a,Rs(e,s,r,n))});return a}(h.value,o.value,p.value,m(),(null==(e=r.value)?void 0:e.max)??3)}),I=e.computed(()=>{var e;return Math.min((null==(e=r.value)?void 0:e.min)??.5,P.value)});let S;function b(e){const t=P.value,s=I.value,r=Ns(e,s,t);u.value=r,d.value=r,function(e,t,s,r=.5,a=3){const i=null==e?void 0:e.getStore();if(!i)return;const o=Ns(s,r,a);i.dispatchToCore(n.setDefaultScale(o));for(const l of t.chapters){const e=R(l);if(e)for(const t of e.segments)i.getState().core.documents[t.documentId]&&i.dispatchToCore(n.setScale(o,t.documentId));else i.getState().core.documents[l.chapterId]&&i.dispatchToCore(n.setScale(o,l.chapterId))}}(l.value,o.value,r,s,t)}function C(e){if(!h.value||!c.value)return;const t=c.value.resolvePageDocument(e,0),s=h.value.getDocument(t.documentId);if(!s)return;const r=Os(p.value,m());r<=0||b(Fs(s,r))}function y(e){if(!g.value)return f()?C(e):b(v()),void(g.value=!0);b(u.value)}return e.watch(()=>null==i?void 0:i.value,e=>{null==S||S(),S=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let s=null;const r=new ResizeObserver(()=>{t(Bs(s))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==s?(s&&r.unobserve(s),s=n,s?(r.observe(s),t(Bs(s))):t(0)):t(Bs(s))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const i=requestAnimationFrame(n);return()=>{cancelAnimationFrame(i),a.disconnect(),s&&r.unobserve(s),r.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==S?void 0:S()),e.watch([l,()=>v(),()=>f()],()=>{l.value&&(f()||b(v()))},{immediate:!0}),e.watch(P,e=>{u.value>e&&b(e)}),e.watch([c,o,()=>f(),()=>v()],()=>{const e=c.value;if(e){for(const t of o.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&y(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&y(e.chapterId)})}},{immediate:!0}),e.watch(h,(e,t,s)=>{e&&s(e.onDocumentOpened(()=>{g.value&&b(u.value)}))}),e.watch([p,()=>f(),c,o],()=>{if(f()&&!(p.value<=0)&&c.value&&!g.value)for(const e of o.value.chapters)if("loaded"===c.value.getChapterStatus(e.chapterId)){C(e.chapterId),g.value=!0;break}}),{scale:d,setScale:b,zoomEnabled:()=>{var e;return!1!==(null==(e=r.value)?void 0:e.enabled)},minZoom:I,maxZoom:P}}(o,l,r);return function(t,s){let r=null;e.watch([t,s],()=>{null==r||r();const e=s.value;r=function(e,t){if(!e||!1===t.enabled)return()=>{};let s=null,r=null,n=0;const a=()=>{const r=e.querySelector("[data-chapter-scroll-viewport]");return!!r&&(null==s||s(),s=function({container:e,getScale:t,setScale:s,minZoom:r=.5,maxZoom:n=3}){let a=0,i=1,o=null,l=1,h=1;const c=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===o?(h=t(),l=1):clearTimeout(o),l*=1-.01*e.deltaY,l=Gs(l,.1,10),s(Gs(h*l,r,n)),o=setTimeout(()=>{o=null},120))},d=new Map,u=e=>{if(d.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===d.size){const[e,s]=[...d.values()];a=Math.hypot(s.x-e.x,s.y-e.y),i=t()}},p=e=>{if(d.has(e.pointerId)&&(d.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===d.size&&a>0)){e.preventDefault();const[t,o]=[...d.values()],l=Math.hypot(o.x-t.x,o.y-t.y);s(Gs(i*(l/a),r,n))}},g=e=>{d.delete(e.pointerId),d.size<2&&(a=0)};return e.addEventListener("wheel",c,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",c),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),o&&clearTimeout(o)}}({container:r,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(r=new MutationObserver(()=>{a()&&(null==r||r.disconnect(),r=null)}),r.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==r||r.disconnect(),null==s||s()}}(t.value??null,{enabled:e.enabled,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom})},{deep:!0,flush:"post"}),e.onBeforeUnmount(()=>null==r?void 0:r())}(r,e.computed(()=>({enabled:d(),getScale:()=>h.value,setScale:c,minZoom:u.value,maxZoom:p.value}))),{hostRef:r,scale:h,setScale:c,zoomEnabled:d}}function qs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Hs(e,t){return`${e}#s${t}`}function Ks(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function js(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return qs(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=qs(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Hs(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Xs(e){const[t,s]=e.localPageRange;return s-t+1}function Ys(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Zs(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ys(t)?t.segmentPageThreshold:null}function Js(e,t){return`${e}#s${t}`}function Qs(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function er(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function tr(e){const t=Zs(e);if(!t)return null;const s=Xs(e),r=er(s,t),n=Ys(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Js(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function sr(e,t){const s=tr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function rr(e,t){const s=tr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function nr(e){var t;const s=Zs(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Xs(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ys(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=er(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ar={kind:"first-wins"};function ir(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class or{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const lr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ar,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ar,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Qs(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Qs(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Qs(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?sr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?tr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...nr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ar){const s=function(e,t=ar){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ir(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new or(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?tr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=rr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ys(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=tr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=tr(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=rr(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=rr(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=sr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=tr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ys(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Zs(t);if(a){const r=er(Xs(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ys(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Qs(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?tr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};lr.id="chapter-manager";let hr=lr;function cr(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const dr=792/612;function ur(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function pr(e){return 0===e.length?null:{width:ur(e.map(e=>e.width)),height:ur(e.map(e=>e.height))}}function gr(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*dr)}}const mr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,cr),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(hr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=js(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ks(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ks(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=pr(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=pr(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=pr(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=gr(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?gr(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=js(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Ks(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};mr.id="chapter-scroll";let fr=mr;const vr=["data-global-page-index","data-chapter-id","data-local-page-index"],Pr=(e=>{const t=e.__vccOpts||e;for(const[s,r]of[["__scopeId","data-v-e9ab4da3"]])t[s]=r;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(s){const{provides:r}=t.useCapability(fr.id),n=e.ref(null),a=e.ref(null);let i=null;const o=()=>{null==i||i(),i=null,r.value&&(r.value.registerViewport(n.value),i=r.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(o),e.onBeforeUnmount(()=>{var e;null==i||i(),null==(e=r.value)||e.registerViewport(null)}),e.watch(r,o),(t,s)=>{var r,i,o;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:n,"data-chapter-scroll-viewport":"",class:e.normalizeClass(t.$props.class),style:e.normalizeStyle({overflow:"auto",overflowX:"hidden",position:"relative",width:"100%",height:"100%",...t.$props.style})},[e.createElementVNode("div",{style:e.normalizeStyle({position:"relative",width:`${(null==(r=a.value)?void 0:r.totalWidth)??0}px`,height:`${(null==(i=a.value)?void 0:i.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(o=a.value)?void 0:o.items)??[],r=>(e.openBlock(),e.createElementBlock("div",{key:r.globalPageIndex,"data-global-page-index":r.globalPageIndex,"data-chapter-id":r.chapterId,"data-local-page-index":r.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${r.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${r.width}px`,height:`${r.height}px`,backgroundColor:r.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[r.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:r},()=>[s[0]||(s[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:r},void 0,!0)],12,vr))),128))],4)],6)}}})),Ir=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const s=t;return(r,n)=>(e.openBlock(),e.createBlock(e.unref(y.RenderLayer),{"document-id":s.pdfDocumentId??s.chapterId,"page-index":s.pdfPageIndex??s.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}});function Sr(e){const[t,s]=e.localPageRange;return s-t+1}function br(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Cr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return br(t)?t.segmentPageThreshold:null}function yr(e,t){return`${e}#s${t}`}function wr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Mr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function xr(e){const t=Cr(e);if(!t)return null;const s=Sr(e),r=Mr(s,t),n=br(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:yr(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Lr(e,t){const s=xr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function $r(e,t){const s=xr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function kr(e){var t;const s=Cr(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Sr(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!br(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Mr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Dr={kind:"first-wins"};function Ur(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Er=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Vr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Dr,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Dr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=wr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=wr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=wr(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Lr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?xr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...kr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Dr){const s=function(e,t=Dr){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ur(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Er(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?xr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=$r(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(br(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=xr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=xr(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=$r(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=$r(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Lr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=xr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(br(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Cr(t);if(a){const r=Mr(Sr(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(br(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=wr(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?xr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Vr.id="chapter-manager";let Ar=Vr;function Tr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Nr(e,t){return`${e}#s${t}`}function Fr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Or(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Tr(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Tr(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Nr(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Rr(e){const[t,s]=e.localPageRange;return s-t+1}function zr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Br(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zr(t)?t.segmentPageThreshold:null}function Gr(e,t){return`${e}#s${t}`}function _r(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Wr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function qr(e){const t=Br(e);if(!t)return null;const s=Rr(e),r=Wr(s,t),n=zr(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Gr(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Hr(e,t){const s=qr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Kr(e,t){const s=qr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function jr(e){var t;const s=Br(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Rr(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!zr(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Wr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Xr={kind:"first-wins"};function Yr(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Zr{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Jr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Xr,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Xr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=_r(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=_r(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=_r(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Hr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?qr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...jr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Xr){const s=function(e,t=Xr){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Yr(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Zr(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?qr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Kr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(zr(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=qr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=qr(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Kr(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Kr(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Hr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=qr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(zr(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Br(t);if(a){const r=Wr(Rr(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(zr(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=_r(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?qr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Jr.id="chapter-manager";let Qr=Jr;function en(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const tn=792/612;function sn(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function rn(e){return 0===e.length?null:{width:sn(e.map(e=>e.width)),height:sn(e.map(e=>e.height))}}function nn(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*tn)}}const an=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,en),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Qr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Or(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Fr(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Fr(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=rn(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=rn(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=rn(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=nn(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?nn(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=Or(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Fr(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};an.id="chapter-scroll";let on=an;const ln=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(on.id),this.chapterManager=this.registry.getPlugin(Ar.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:cn(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};ln.id="note";let hn=ln;function cn(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function dn(e){const{markerPdf:t,lineRects:s,sx:r,sy:n,cssPageWidth:a,iconSize:i,gapPx:o=6}=e,l=(null==s?void 0:s.length)?s[s.length-1]:void 0;let h,c;l?(h=(l.origin.x+l.size.width)*r+o,c=l.origin.y*n+(l.size.height*n-i)/2):(h=t.x*r-i/2,c=t.y*n-i-o);const d=Math.max(0,a-i-2);return h>d&&(h=d),c<0&&(c=0),{left:h,top:c}}const un={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},pn=["onMouseenter"],gn=["data-note-marker-zone","onMouseenter","onMouseleave"],mn=["onClick"],fn=["onClick"],vn=["onClick"],Pn=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(hn.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===r.chapterId&&e.localPageIndex===r.localPageIndex)})},{immediate:!0});let l=null;e.watch(o,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var s;const r=t.target;(null==(s=r.closest)?void 0:s.call(r,`[data-note-marker-zone="${e}"]`))||(o.value=null,i.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16}),c=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function d(e){const t=r.cssPageWidth/r.pdfPageWidth,s=r.cssPageHeight/r.pdfPageHeight,n=h.value,{left:a,top:i}=dn({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:s,cssPageWidth:r.cssPageWidth,iconSize:n}),l=function(e,t,s){let r=1/0,n=1/0,a=-1/0,i=-1/0;for(const o of e)r=Math.min(r,o.origin.x*t),n=Math.min(n,o.origin.y*s),a=Math.max(a,(o.origin.x+o.size.width)*t),i=Math.max(i,(o.origin.y+o.size.height)*s);return{left:r,top:n,width:a-r,height:i-n}}(e.rectsPdfCoord,t,s),c=o.value===e.noteId?72:0,d=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,i)-8);return{zoneLeft:d,zoneTop:u,zoneW:Math.min(r.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-d,zoneH:Math.max(l.top+l.height,i+n+6+c)+8-u,iconLeft:a,iconTop:i,sx:t,sy:s}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",un,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(s,r)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${r}`,style:e.normalizeStyle({position:"absolute",left:s.origin.x*d(t).sx+"px",top:s.origin.y*d(t).sy+"px",width:s.size.width*d(t).sx+"px",height:s.size.height*d(t).sy+"px",background:c.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>i.value=t.noteId},null,44,pn))),128)),i.value===t.noteId||o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${d(t).zoneLeft}px`,top:`${d(t).zoneTop}px`,width:`${d(t).zoneW}px`,height:`${d(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>i.value=t.noteId,onMouseleave:e=>o.value!==t.noteId&&(i.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:d(t).iconLeft-d(t).zoneLeft+"px",top:d(t).iconTop-d(t).zoneTop+"px",width:`${h.value}px`,height:`${h.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:r[0]||(r[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>o.value=o.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,mn),o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:d(t).iconLeft-d(t).zoneLeft+"px",top:`${d(t).iconTop-d(t).zoneTop+h.value+4}px`,minWidth:"120px",padding:"6px",borderRadius:"8px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)",zIndex:30}),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#334155",cursor:"pointer","text-align":"left"},onClick:e=>{return s=t,void(null==(r=n.value)||r.requestEditNote(s.noteId,s));var s,r}}," 编辑 ",8,fn),e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>{var s,r;return r=t.noteId,null==(s=n.value)||s.requestDeleteNote(r),void(o.value=null)}}," 删除 ",8,vn)],36)):e.createCommentVNode("",!0)],44,gn)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),In={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Sn=["title","onClick"],bn=["onClick"],Cn=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(Cs.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===r.chapterId&&e.anchor.localPageIndex===r.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(i,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=o.value)?void 0:t.contains(e.target))||(i.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const c=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16});function d(e){const{left:t,top:s}=function(e){var t;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return dn({markerPdf: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},lineRects:a,sx:s,sy:n,cssPageWidth:r.cssPageWidth,iconSize:c.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,s-6)}px`,width:`${c.value+12}px`,height:`${c.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",In,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(d(t)),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${c.value}px`,height:`${c.value}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",fontSize:"11px",padding:0}),onClick:e.withModifiers(e=>i.value=i.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Sn),i.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:o,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:r[0]||(r[0]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>async function(e){const t=n.value;t&&await t.requestRemoveBookmark(e)&&(i.value=null)}(t.id)}," 删除书签 ",8,bn)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function yn(e){return e.pdfDocumentId??e.chapterId}function wn(e){return e.pdfPageIndex??e.localPageIndex}function Mn(e,t){e.wait(t,()=>{})}const xn={display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px",borderRadius:"8px",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)"},Ln={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const $n=e.defineComponent({__name:"ChapterPageSurface",props:{item:{},features:{},showNoteMarkers:{type:Boolean},showBookmarkMarkers:{type:Boolean},showRedactionLayer:{type:Boolean},noteMarkerUi:{},bookmarkMarkerUi:{},buildSelectionMenu:{type:Function},createNote:{},annotationSelectionMenu:{},redactionSelectionMenu:{},renderPageOverlay:{type:Function}},setup(s){const r=s,n=e.computed(()=>yn(r.item)),i=e.computed(()=>wn(r.item));!function(s){const{provides:r}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([r,s],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:o}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),c=e.computed(()=>{var e,t;return null==(t=null==(e=o.value)?void 0:e.getDocument(n.value))?void 0:t.pages[i.value]});function d(t,s){var n,a,i,o;const h=r.createNote.value;if(h&&!1!==(null==(a=null==(n=r.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(o=null==(i=r.features)?void 0:i.selectionToolbar)?void 0:o.enabled))return r=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=r.placement)?void 0:n.suggestTop)?-40:r.rect.size.height+8};return e.h("div",r.menuWrapperProps,[e.h("div",{style:a},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!l.value)return;const e=l.value.getHighlightRectsForPage(wn(t),s);Mn(l.value.getSelectedText(s),s=>{var r,n,a;h((r=t,n=e,a=s.join("\n"),{chapterId:r.chapterId,localPageIndex:r.localPageIndex,globalPageIndex:r.globalPageIndex,globalPageNumber:r.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=r.buildSelectionMenu,t={item:r.item,defaultMenu:d(r.item,n.value),createNote:r.createNote.value};if(e){const s=e(t);if(s)return s}return t.defaultMenu}),p=function(t,s){var r,n;const{provides:a}=b.useAnnotationCapability(),i=null==(r=null==s?void 0:s.markup)?void 0:r.annotationMenu,o=!1!==(null==(n=null==s?void 0:s.markup)?void 0:n.enabled),l=!1!==(null==i?void 0:i.enabled);return e.computed(()=>{const s="string"==typeof t?t:t.value;if(o&&l&&a.value)return t=>{const{context:r,rect:n,placement:o,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==r.type)return e.h("span",l);if(r.structurallyLocked)return e.h("span",l);if(c=r.annotation.object.type,!A.has(c))return e.h("span",l);var c;const d=a.value.forDocument(s),{pageIndex:u,id:p}=r.annotation.object,g=()=>{null==d||d.deleteAnnotation(u,p)},m={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==o?void 0:o.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==o?void 0:o.suggestTop)?`${n.size.height+8}px`:void 0},f=(null==i?void 0:i.renderMenu)?i.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:Ln,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:xn,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(n,r.features),g=e.computed(()=>function(e,t){if(e||t)return s=>{if(e){const t=e(s);if(null!=t)return t}return(null==t?void 0:t(s))??null}}(r.annotationSelectionMenu,p.value)),m=e.computed(()=>{var e;return null==(e=r.renderPageOverlay)?void 0:e.call(r,r.item)}),f=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=r.features)?void 0:e.selectionToolbar)});return(t,r)=>s.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(P.GlobalPointerProvider),{key:0,"document-id":n.value},{default:e.withCtx(()=>[e.createVNode(e.unref(I.Rotate),{"document-id":n.value,"page-index":i.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":i.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(L)},{default:e.withCtx(()=>[e.createVNode(e.unref(Ir),{"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":i.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(S.SelectionLayer),{"document-id":n.value,"page-index":i.value,"text-style":f.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),s.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(C.RedactionLayer),{key:0,"document-id":n.value,"page-index":i.value,"selection-menu":s.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(b.AnnotationLayer),{"document-id":n.value,"page-index":i.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),s.showBookmarkMarkers&&c.value?(e.openBlock(),e.createBlock(Cn,{key:1,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":c.value.size.width,"pdf-page-height":c.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(m.value),{key:2})):e.createCommentVNode("",!0),s.showNoteMarkers&&c.value?(e.openBlock(),e.createBlock(Pn,{key:3,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":c.value.size.width,"pdf-page-height":c.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.noteMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"default")]),_:3},8,["document-id","page-index","style","onPointerdown"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),kn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(s){const r=s,n=e.computed(()=>yn(r.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:i}=t.useCapability(Cs.id),o=e.ref(null),l=e.ref(null),c=e.ref(null),d=e.ref(null),u=e.computed(()=>{var e;return(null==(e=r.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>d.value??c.value);let g=null,m=0;function f(){const e=a.value;if(!e)return;const t=e.forDocument(n.value).getState().geometry[r.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>r.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(m),l.value=null,!e)return;const t=e.forDocument(n.value);g=t.onSelectionChange(f);let s=!1;const a=()=>{if(!s){try{if(f(),t.getState().geometry[r.item.localPageIndex])return}catch{}m=requestAnimationFrame(a)}};return a(),()=>{s=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>r.pdfPageWidth,d,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&r.pdfPageWidth&&(v=e=>{if(d.value)return;const t=a.value;if(t)try{if(t.forDocument(n.value).getState().selecting)return void(c.value=null)}catch{}const s=o.value;if(!s)return;const i=s.getBoundingClientRect();if(e.clientX<i.left||e.clientX>i.right||e.clientY<i.top||e.clientY>i.bottom)return void(c.value=null);const u=function(e,t){const s=h.glyphAt(e,t);if(s<0)return null;const r=h.expandToLineBoundary(e,s);if(!r)return null;const n=h.rectsWithinSlice(e,r.from,r.to);return 0===n.length?null:{lineRects:n,charFrom:r.from,charTo:r.to}}(l.value,{x:(e.clientX-i.left)/(r.cssPageWidth/r.pdfPageWidth),y:(e.clientY-i.top)/(r.cssPageHeight/r.pdfPageHeight)});c.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(m),null==g||g()});const P=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?Ss(r.item.chapterId,r.item.localPageIndex,e,{globalPageIndex:r.item.globalPageIndex,globalPageNumber:r.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=i.value;return!(!e||!t)&&t.listBookmarks().some(t=>Is(t.anchor,e))});function S(){const e=i.value,t=P.value;e&&t&&!I.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),c.value=null,d.value=null)}const b=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!r.pdfPageWidth)return null;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*s+6,Math.max(0,r.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*s-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,r)=>{var n;return e.unref(i)&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:o,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[b.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${b.value.zoneLeft}px`,top:`${b.value.zoneTop}px`,width:`${b.value.size+20}px`,height:`${((null==(n=p.value[p.value.length-1])?void 0:n.size.height)??0)*(s.cssPageHeight/s.pdfPageHeight)+b.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:r[0]||(r[0]=e=>d.value=p.value),onMouseleave:r[1]||(r[1]=e=>d.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:b.value.iconLeft-b.value.zoneLeft+"px",top:b.value.iconTop-b.value.zoneTop+"px",width:`${b.value.size}px`,height:`${b.value.size}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"#3b82f6",color:"#fff",border:"none",borderRadius:"4px",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",padding:0}),onClick:e.withModifiers(S,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),Dn={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Un={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},En={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Vn={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},An={key:2,d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626","stroke-width":"2","stroke-linecap":"round",fill:"none"},Tn={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Nn={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Fn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(s,r)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",Dn,[...r[0]||(r[0]=[e.createElementVNode("rect",{x:"8.5",y:"8.5",width:"11",height:"13",rx:"2.25",fill:"#f1f5f9",stroke:"#94a3b8","stroke-width":"1.35"},null,-1),e.createElementVNode("rect",{x:"4.5",y:"3.5",width:"11",height:"13",rx:"2.25",fill:"#ffffff",stroke:"#334155","stroke-width":"1.5"},null,-1),e.createElementVNode("path",{d:"M7.5 7h5.5a1.5 1.5 0 0 1 1.5 1.5V14",stroke:"#64748b","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])])):"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",Un,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",En)):e.createCommentVNode("",!0),r[1]||(r[1]=e.createElementVNode("text",{x:"14",y:"19","text-anchor":"middle","font-size":"15","font-weight":"700","font-family":"system-ui, -apple-system, sans-serif",fill:"#0f172a"}," A ",-1)),"underline"===t.kind?(e.openBlock(),e.createElementBlock("path",Vn)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",An)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",Tn)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Nn,[...r[2]||(r[2]=[e.createElementVNode("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706","stroke-width":"1.2","stroke-linejoin":"round"},null,-1),e.createElementVNode("path",{d:"M16 3v4h4",stroke:"#d97706","stroke-width":"1.2"},null,-1),e.createElementVNode("path",{d:"M10 12h6M10 16h4",stroke:"#92400e","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])]))}),On=["title","aria-label","onMouseenter","onClick"],Rn=["title","onMouseenter","onClick"],zn={style:{"font-size":"11px","font-weight":"600"}},Bn=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:s}){const r=t,n=s,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],i=e.computed(()=>new Set(r.hiddenBuiltinActions??[])),o=e.computed(()=>!i.value.has("copy")),l=e.computed(()=>a.filter(e=>!i.value.has(e.id))),h=e.computed(()=>!i.value.has("note")),c=e.computed(()=>[...r.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),d=e.computed(()=>l.value.length>0||c.value.length>0),u=e.ref(null),p=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:r.placementAbove?void 0:`${r.anchorHeight+10}px`,bottom:r.placementAbove?`${r.anchorHeight+10}px`:void 0,display:"flex",alignItems:"center",gap:"2px",padding:"4px 6px",borderRadius:"12px",background:"rgba(255, 255, 255, 0.96)",border:"1px solid rgba(15, 23, 42, 0.06)",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.08), 0 12px 32px rgba(15, 23, 42, 0.1)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)"}));function g(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:u.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const m={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(s,r)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[o.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:r[0]||(r[0]=e=>u.value="copy"),onMouseleave:r[1]||(r[1]=e=>u.value=null),onClick:r[2]||(r[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(Fn,{key:1,kind:"copy"}))],36),d.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[3]||(r[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(Fn,{kind:t.id},null,8,["kind"])],44,On))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[4]||(r[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",zn,e.toDisplayString(t.label.slice(0,2)),1)],44,Rn))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[d.value||o.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(g("note",!0)),onMouseenter:r[5]||(r[5]=e=>u.value="note"),onMouseleave:r[6]||(r[6]=e=>u.value=null),onClick:r[7]||(r[7]=e=>n("action","note"))},[e.createVNode(Fn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Gn={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},_n=e.defineComponent({__name:"PdfChapterViewport",props:{className:{},features:{},buildSelectionMenu:{},annotationSelectionMenu:{},redactionSelectionMenu:{},showNoteMarkers:{type:Boolean,default:!0},showBookmarkMarkers:{type:Boolean,default:!0},showRedactionLayer:{type:Boolean,default:!1},renderPageOverlay:{},onExtraSelectionAction:{}},setup(r){const n=r,i=e.computed(()=>n.features),{hostRef:o}=Ws(i),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=n.features)?void 0:e.scrollViewport)?void 0:t.background)??$}}),c=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e,t,r;const n=null==(r=null==(t=null==(e=s.value)?void 0:e.getPlugin(wt.id))?void 0:t.provides)?void 0:r.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),d=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(wt.id))})}(),u=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(Cs.id))})}(),p=e.computed(()=>{var e,t;return n.showNoteMarkers&&d.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return n.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(r,n){const a=e.computed(()=>{var e;return null==(e=r())?void 0:e.selectionToolbar}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.markup)?void 0:t.enabled)}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.notes)?void 0:t.enabled)}),l=e.computed(()=>{var e,t;return!(null==(t=null==(e=a.value)?void 0:e.hiddenBuiltinActions)?void 0:t.includes("copy"))}),{provides:c}=t.useCapability(h.SelectionPlugin.id),{provides:d}=t.useCapability(s.AnnotationPlugin.id),{provides:u}=t.useCapability(wt.id);return e.computed(()=>{var t,s,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(i.value||o.value||l.value||(null==(h=null==(s=a.value)?void 0:s.extraActions)?void 0:h.length)))return t=>{const s=yn(t.item),h=wn(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(Bn,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(m=a.value)?void 0:m.hiddenBuiltinActions,extraActions:null==(f=a.value)?void 0:f.extraActions,renderCopyIcon:null==(v=a.value)?void 0:v.renderCopyIcon,onAction:e=>{var a,p,g;if("copy"!==e)if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!c.value||!u.value||!o.value)return;const e=c.value.getHighlightRectsForPage(h,s);return void Mn(c.value.getSelectedText(s),s=>{var r;null==(r=u.value)||r.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:s.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!c.value||!d.value||!i.value)return;V(s,Gn[e],d.value,c.value,null==(g=null==(p=r())?void 0:p.markup)?void 0:g.styles)}else{if(!c.value||!l.value)return;Mn(c.value.getSelectedText(s),e=>{!async function(e){var t;const s=e.trim();if(!s)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}catch{return!1}}(e.join("\n"))})}}}))}}})}(()=>n.features,{onExtraAction:n.onExtraSelectionAction}),v=e.computed(()=>{if(n.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return n.buildSelectionMenu?n.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(a.DocumentManagerPlugin.id);function I(t){var s;const r=[];if(m.value){const s=function(t){var s,r,a,i;const o=yn(t),l=wn(t),h=null==(r=null==(s=P.value)?void 0:s.getDocument(o))?void 0:r.pages[l];return t.isPlaceholder||!h?null:e.h(kn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(i=null==(a=n.features)?void 0:a.bookmarks)?void 0:i.hover})}(t);s&&r.push(s)}const a=null==(s=n.renderPageOverlay)?void 0:s.call(n,t);if(a&&r.push(a),r.length)return e.h("div",r)}return(t,s)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:o,class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(Pr),{class:e.normalizeClass(r.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var s,n,a,i;return[e.createVNode($n,{item:t,features:r.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":r.showRedactionLayer,"note-marker-ui":null==(n=null==(s=r.features)?void 0:s.notes)?void 0:n.marker,"bookmark-marker-ui":null==(i=null==(a=r.features)?void 0:a.bookmarks)?void 0:i.marker,"build-selection-menu":v.value,"create-note":e.unref(c),"annotation-selection-menu":r.annotationSelectionMenu,"redaction-selection-menu":r.redactionSelectionMenu,"render-page-overlay":I},null,8,["item","features","show-note-markers","show-bookmark-markers","show-redaction-layer","note-marker-ui","bookmark-marker-ui","build-selection-menu","create-note","annotation-selection-menu","redaction-selection-menu"])]}),_:1},8,["class","style"]),e.renderSlot(t.$slots,"default")],6))}}),Wn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},qn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(s){const r=s,n=e.computed(()=>function(e){if(e.options)return Ts(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=N(e.features),s={...e.editorOptions,prefetchChapters:e.editorOptions.prefetchChapters??Es.prefetchChapters,maxConcurrentSegmentLoads:e.editorOptions.maxConcurrentSegmentLoads??Es.maxConcurrentSegmentLoads,unloadTimeoutMs:e.editorOptions.unloadTimeoutMs??Es.unloadTimeoutMs,features:t},{plugins:r}=Us(s);return{plugins:r,features:t,editorOptions:s}}({engine:r.engine,options:r.options,editorOptions:r.editorOptions,features:r.features}));return(r,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:s.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",Wn,[e.renderSlot(r.$slots,"prepend"),e.createVNode(_n,{class:e.normalizeClass(s.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":s.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(r.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),Hn={class:"chapter-tree-row"},Kn=["aria-expanded"],jn={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Xn={class:"chapter-tree-label"},Yn={class:"chapter-tree-meta"},Zn={key:0},Jn=(e,t)=>{const s=e.__vccOpts||e;for(const[r,n]of t)s[r]=n;return s},Qn=Jn(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const s={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},r=t,n=e.computed(()=>r.node.children??[]),a=e.computed(()=>n.value.length>0),i=e.ref(r.depth<1),o=e.computed(()=>r.activeChapterId===r.node.id),l=e.computed(()=>r.chapterStatus[r.node.id]??"idle"),h=e.computed(()=>!a.value);return(r,c)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",Hn,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":i.value,onClick:c[0]||(c[0]=e=>i.value=!i.value)},e.toDisplayString(i.value?"▼":"▶"),9,Kn)):(e.openBlock(),e.createElementBlock("span",jn)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":o.value}]),onClick:c[1]||(c[1]=e=>r.$emit("select",t.node.id))},[e.createElementVNode("div",Xn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",Yn,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),h.value?(e.openBlock(),e.createElementBlock("span",Zn,e.toDisplayString(s[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&i.value?(e.openBlock(),e.createBlock(ea,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:c[2]||(c[2]=e=>r.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),ea=Jn(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(s,r)=>(e.openBlock(),e.createElementBlock("ul",{class:"chapter-tree-list",style:e.normalizeStyle({marginLeft:t.depth>0?"12px":"0"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.nodes,n=>(e.openBlock(),e.createBlock(Qn,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:r[0]||(r[0]=e=>s.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),ta={class:"chapter-tree"},sa={class:"chapter-tree-nav","aria-label":"章节目录"},ra=Jn(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(s,{emit:r}){const n=s,a=r,{provides:i}=t.useCapability(Ee.id),{provides:o}=t.useCapability(re.id),l=e.ref({});function h(){if(!o.value)return;const e={},t=s=>{var r;for(const n of s)e[n.id]=o.value.getChapterStatus(n.id),(null==(r=n.children)?void 0:r.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([o,()=>n.tree],h,{immediate:!0});let c=null;function d(e){var t;a("active-chapter-change",e),null==(t=i.value)||t.scrollToChapter(e)}return e.watch(o,e=>{null==c||c(),c=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==c?void 0:c()),(t,r)=>(e.openBlock(),e.createElementBlock("aside",ta,[r[0]||(r[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",sa,[e.createVNode(ea,{nodes:s.tree,depth:0,"active-chapter-id":s.activeChapterId,"chapter-status":l.value,onSelect:d},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),na=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,s)=>(e.openBlock(),e.createBlock(e.unref(qn),e.normalizeProps(e.guardReactiveProps(t.$props)),e.createSlots({default:e.withCtx(()=>[e.renderSlot(t.$slots,"default")]),_:2},[t.$slots.prepend?{name:"prepend",fn:e.withCtx(()=>[e.renderSlot(t.$slots,"prepend")]),key:"0"}:void 0]),1040))});function aa(e){const[t,s]=e.localPageRange;return s-t+1}function ia(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function oa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ia(t)?t.segmentPageThreshold:null}function la(e,t){return`${e}#s${t}`}function ha(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ca(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function da(e){const t=oa(e);if(!t)return null;const s=aa(e),r=ca(s,t),n=ia(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:la(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ua(e,t){const s=da(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function pa(e,t){const s=da(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ga(e){var t;const s=oa(e);if(!s)return[];const r=[],{chapterId:n}=e,a=aa(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ia(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ca(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ma={kind:"first-wins"};function fa(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let va=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Pa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ma,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ma,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ha(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ha(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ha(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?ua(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?da(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ga(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ma){const s=function(e,t=ma){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,fa(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new va(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?da(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=pa(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ia(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=da(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=da(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=pa(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=pa(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=ua(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=da(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ia(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=oa(t);if(a){const r=ca(aa(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ia(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ha(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?da(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Pa.id="chapter-manager";let Ia=Pa;function Sa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ba(e,t){return`${e}#s${t}`}function Ca(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ya(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Sa(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Sa(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ba(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function wa(e){const[t,s]=e.localPageRange;return s-t+1}function Ma(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function xa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ma(t)?t.segmentPageThreshold:null}function La(e,t){return`${e}#s${t}`}function $a(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ka(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Da(e){const t=xa(e);if(!t)return null;const s=wa(e),r=ka(s,t),n=Ma(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:La(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Ua(e,t){const s=Da(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ea(e,t){const s=Da(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Va(e){var t;const s=xa(e);if(!s)return[];const r=[],{chapterId:n}=e,a=wa(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ma(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ka(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Aa={kind:"first-wins"};function Ta(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Na{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Fa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Aa,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Aa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=$a(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=$a(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=$a(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Ua(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Da(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Va(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Aa){const s=function(e,t=Aa){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ta(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Na(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Da(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ea(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ma(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Da(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Da(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ea(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Ea(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Ua(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Da(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ma(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=xa(t);if(a){const r=ka(wa(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ma(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=$a(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Da(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Fa.id="chapter-manager";let Oa=Fa;function Ra(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const za=792/612;function Ba(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function Ga(e){return 0===e.length?null:{width:Ba(e.map(e=>e.width)),height:Ba(e.map(e=>e.height))}}function _a(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*za)}}function Wa(e){const[t,s]=e.localPageRange;return s-t+1}function qa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ha(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return qa(t)?t.segmentPageThreshold:null}function Ka(e,t){return`${e}#s${t}`}function ja(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Xa(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ya(e){const t=Ha(e);if(!t)return null;const s=Wa(e),r=Xa(s,t),n=qa(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Ka(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Za(e,t){const s=Ya(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ja(e,t){const s=Ya(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Qa(e){var t;const s=Ha(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Wa(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!qa(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Xa(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ra),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Oa.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=ya(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ca(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ca(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=Ga(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=Ga(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=Ga(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=_a(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?_a(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=ya(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Ca(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}}).id="chapter-scroll";const ei={kind:"first-wins"};function ti(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let si=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ri=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ei,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ei,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ja(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ja(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ja(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Za(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ya(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Qa(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ei){const s=function(e,t=ei){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ti(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new si(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ya(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ja(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(qa(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ya(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ya(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ja(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Ja(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Za(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ya(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(qa(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ha(t);if(a){const r=Xa(Wa(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(qa(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ja(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ya(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ri.id="chapter-manager";let ni=ri;function ai(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ii(e,t){return`${e}#s${t}`}function oi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function li(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ai(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=ai(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ii(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function hi(e){const[t,s]=e.localPageRange;return s-t+1}function ci(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function di(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ci(t)?t.segmentPageThreshold:null}function ui(e,t){return`${e}#s${t}`}function pi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function gi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function mi(e){const t=di(e);if(!t)return null;const s=hi(e),r=gi(s,t),n=ci(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:ui(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function fi(e,t){const s=mi(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function vi(e,t){const s=mi(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Pi(e){var t;const s=di(e);if(!s)return[];const r=[],{chapterId:n}=e,a=hi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ci(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=gi(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Ii={kind:"first-wins"};function Si(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let bi=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ci=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ii,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ii,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=pi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=pi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=pi(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?fi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?mi(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Pi(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Ii){const s=function(e,t=Ii){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Si(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new bi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?mi(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=vi(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ci(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=mi(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=mi(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=vi(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=vi(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=fi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=mi(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ci(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=di(t);if(a){const r=gi(hi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ci(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=pi(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?mi(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ci.id="chapter-manager";let yi=Ci;function wi(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const Mi=792/612;function xi(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function Li(e){return 0===e.length?null:{width:xi(e.map(e=>e.width)),height:xi(e.map(e=>e.height))}}function $i(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*Mi)}}const ki=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,wi),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(yi.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=li(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=oi(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=oi(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=Li(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=Li(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=Li(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=$i(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?$i(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=li(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=oi(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};ki.id="chapter-scroll";let Di=ki;const Ui=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Di.id),this.chapterManager=this.registry.getPlugin(ni.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Vi(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};Ui.id="note";let Ei=Ui;function Vi(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ai(e){const[t,s]=e.localPageRange;return s-t+1}function Ti(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ni(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ti(t)?t.segmentPageThreshold:null}function Fi(e,t){return`${e}#s${t}`}function Oi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ri(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function zi(e){const t=Ni(e);if(!t)return null;const s=Ai(e),r=Ri(s,t),n=Ti(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Fi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Bi(e,t){const s=zi(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Gi(e,t){const s=zi(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function _i(e){var t;const s=Ni(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ai(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ti(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Ri(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Wi={kind:"first-wins"};function qi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Hi=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ki=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Wi,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Wi,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Oi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Oi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Oi(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Bi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?zi(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(..._i(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Wi){const s=function(e,t=Wi){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,qi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Hi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?zi(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Gi(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ti(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=zi(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=zi(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Gi(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Gi(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Bi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=zi(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ti(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ni(t);if(a){const r=Ri(Ai(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ti(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Oi(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?zi(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ki.id="chapter-manager";let ji=Ki;function Xi(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Yi(e,t){return`${e}#s${t}`}function Zi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ji(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xi(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Xi(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Yi(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Qi(e){const[t,s]=e.localPageRange;return s-t+1}function eo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function to(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return eo(t)?t.segmentPageThreshold:null}function so(e,t){return`${e}#s${t}`}function ro(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function no(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ao(e){const t=to(e);if(!t)return null;const s=Qi(e),r=no(s,t),n=eo(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:so(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function io(e,t){const s=ao(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function oo(e,t){const s=ao(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function lo(e){var t;const s=to(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Qi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!eo(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=no(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ho={kind:"first-wins"};function co(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class uo{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const po=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ho,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ho,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ro(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ro(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ro(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?io(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ao(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...lo(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ho){const s=function(e,t=ho){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,co(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new uo(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ao(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=oo(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(eo(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ao(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ao(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=oo(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=oo(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=io(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ao(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(eo(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=to(t);if(a){const r=no(Qi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(eo(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ro(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ao(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};po.id="chapter-manager";let go=po;function mo(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const fo=792/612;function vo(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function Po(e){return 0===e.length?null:{width:vo(e.map(e=>e.width)),height:vo(e.map(e=>e.height))}}function Io(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*fo)}}const So=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,mo),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(go.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Ji(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Zi(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Zi(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=Po(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=Po(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=Po(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=Io(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?Io(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=Ji(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Zi(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};So.id="chapter-scroll";let bo=So;function Co(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function yo(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function wo(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??Co(n),o=t.markerAnchor??Co(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(yo(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}const Mo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(bo.id),this.chapterManager=this.registry.getPlugin(ji.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(wo(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};Mo.id="paragraph-bookmark";let xo=Mo;function Lo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $o(e,t){return`${e}#s${t}`}function ko(e,t){const s=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Lo(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Lo(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:$o(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Do(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,function(){const e=Do(void 0,{enabled:!0}),t=Do(void 0,{enabled:!0}),s=Do(void 0,{enabled:!0}),r=Do(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=Do(!1!==e.enabled||!1!==s.enabled,{enabled:!0});null==void 0||(void 0).background}();function Uo(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Eo(e){return{bookmarks:!1!==(null==e?void 0:e.bookmarks),notes:!1!==(null==e?void 0:e.notes),markup:!1!==(null==e?void 0:e.markup)}}function Vo(e){return new Promise((t,s)=>{e.wait(e=>t(e),e=>s(e))})}function Ao(e){var t,r,n,a;return{annotation:null==(t=e.getPlugin(s.AnnotationPlugin.id))?void 0:t.provides(),note:null==(r=e.getPlugin(Ei.id))?void 0:r.provides(),bookmark:null==(n=e.getPlugin(xo.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(Ia.id))?void 0:a.provides()}}async function To(e,t,s){if(!s||!e)return;const r=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==r)throw new Error(`章节 ${t} 未加载成功(${r}),无法导入/导出划线`)}async function No(e,t,s){const r=Eo(s),{annotation:n,note:a,bookmark:i,chapterManager:o}=Ao(e),l={chapterId:t};if(r.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=i.listBookmarksForChapter(t)}if(r.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(r.markup){if(!n)throw new Error("annotation 插件未注册");await To(o,t,!1!==(null==s?void 0:s.ensureChapterLoaded));const e=await async function(e,t,s){const r=t.getSegmentPlan(s);if(!r)return Vo(e.forDocument(s).exportAnnotations());const n=[];for(const a of r.segments){if(!t.isSegmentLoaded(s,a.index))continue;const r=await Vo(e.forDocument(a.documentId).exportAnnotations());for(const e of r){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,o,t);l.markup=function(e){return e.map(e=>{if(!(e.ctx&&"data"in e.ctx&&e.ctx.data instanceof ArrayBuffer))return{annotation:e.annotation};const t=e.ctx;return{annotation:e.annotation,ctx:{dataBase64:Uo(t.data),mimeType:t.mimeType}}})}(e)}return l}async function Fo(e,t,s){const r=Eo(s),n=(null==s?void 0:s.mode)??"replace",{annotation:a,note:i,bookmark:o,chapterManager:l}=Ao(e),h=t.chapterId;if(r.bookmarks&&t.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)o.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)o.addBookmark(e)}if(r.notes&&t.notes){if(!i)throw new Error("note 插件未注册");if("replace"===n)i.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)i.registerNote(e)}if(r.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await To(l,h,!1!==(null==s?void 0:s.ensureChapterLoaded)),function(e,t,s,r,n){const a=t.getSegmentPlan(s);if(!a){const t=e.forDocument(s);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(r)}const i=t.getChapter(s);if(!i)return;const o=new Map;for(const l of r){const e=l.annotation.pageIndex,t=ko(i,e),s=a.segments[t];if(!s)continue;const r=o.get(t)??[];r.push({...l,annotation:{...l.annotation,pageIndex:e-s.localPageStart}}),o.set(t,r)}for(const l of a.segments){const t=e.forDocument(l.documentId),s=o.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),s.length>0&&t.importAnnotations(s)}}(a,l,h,function(e){return e.map(e=>{var t;if(!(null==(t=e.ctx)?void 0:t.dataBase64))return{annotation:e.annotation};const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:s,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==s?void 0:s.persistNotes)&&i&&await s.persistNotes(i.listAllNotes()),(null==s?void 0:s.persistBookmarks)&&o&&await s.persistBookmarks(o.listBookmarks())}function Oo(e){return JSON.stringify(e,null,2)}function Ro(e){return JSON.stringify(e,null,2)}function zo(e,t){const s=new Blob([t],{type:"application/json;charset=utf-8"}),r=URL.createObjectURL(s),n=document.createElement("a");n.href=r,n.download=e,n.click(),URL.revokeObjectURL(r)}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT;function Bo(e){const[t,s]=e.localPageRange;return s-t+1}function Go(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function _o(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Go(t)?t.segmentPageThreshold:null}function Wo(e,t){return`${e}#s${t}`}function qo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ho(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ko(e){const t=_o(e);if(!t)return null;const s=Bo(e),r=Ho(s,t),n=Go(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Wo(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function jo(e,t){const s=Ko(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Xo(e,t){const s=Ko(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Yo(e){var t;const s=_o(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Bo(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Go(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Ho(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Zo={kind:"first-wins"};function Jo(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Qo{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}function el(e,t=Zo){const s=function(e,t=Zo){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Jo(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Qo(a)}const tl=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Zo,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Zo,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=qo(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=qo(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=qo(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?jo(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ko(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Yo(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=el(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ko(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!!s&&(!!this.pendingSegmentLoadPromises.has(s)||!(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Xo(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&("error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e))}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!Go(s)&&((!s||!("url"in s||"buffer"in s||"load"in s))&&!!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||(!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1))}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ko(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);if(i)return i.globalPageIndex;return 1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ko(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Xo(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Xo(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=jo(this.findChapter(e.chapterId),e.localPageIndex);if(this.documentManager.provides().isDocumentOpen(t.documentId)){this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus){if("loaded"!==r)continue;t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ko(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Go(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=_o(t);if(a){const r=Ho(Bo(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Go(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a)){return c.closeDocument(o).wait(()=>{},()=>{}),"closed"}this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=qo(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}if(!l)return void this.updateStatus(s,"password-required");this.updateStatus(s,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ko(t):null,n=e=>{if(s.isDocumentOpen(e)){s.closeDocument(e).wait(()=>{},()=>{})}};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};tl.id="chapter-manager";let sl=tl;function rl(e){const t=e.endPage-e.startPage+1;return{chapterId:e.chapterId,title:e.title,globalPageRange:[e.startPage,e.endPage],localPageRange:[0,t-1],...e.source?{source:e.source}:{},...null!=e.segmentPageThreshold?{segmentPageThreshold:e.segmentPageThreshold}:{},...e.encrypted?{encrypted:e.encrypted}:{}}}function nl(e){const t=[],s=e=>{var r;for(const n of e)t.push(rl(n)),(null==(r=n.children)?void 0:r.length)&&s(n.children)};return s(e),t}function al(e){return e.map(e=>{var t;return{id:e.chapterId,title:e.title,startPage:e.startPage,endPage:e.endPage,children:(null==(t=e.children)?void 0:t.length)?al(e.children):void 0}})}Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>t.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>t.useCapability}),Object.defineProperty(exports,"useRegistry",{enumerable:!0,get:()=>t.useRegistry}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>w.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=z,exports.ChapterManagerPlugin=sl,exports.ChapterPdfViewer=na,exports.ChapterTreePanel=ra,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Ds,exports.PdfChapterViewport=_n,exports.applySelectionMarkup=V,exports.buildChapterViewerCatalog=function(e){return{tree:al(e),manifest:{chapters:nl(e)}}},exports.buildParagraphBookmarkAnchor=Ss,exports.chapterAnnotationsArchiveToJson=Oo,exports.chapterAnnotationsSnapshotToJson=Ro,exports.chapterDescriptorFromTreeNode=rl,exports.copyTextToClipboard=async function(e){var t;const s=e.trim();if(!s)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}catch{return!1}},exports.createChapterViewerBundle=Ts,exports.createChapterViewerEditor=Us,exports.createChapterViewerEditorOptions=function(e){const{features:t,...s}=As(Vs(e));return s},exports.createPdfChapterEditor=$s,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){zo(t,Oo(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){zo(t??`chapter-annotations-${e.chapterId}.json`,Ro(e))},exports.downloadJsonFile=zo,exports.exportAllChapterAnnotations=async function(e,t,s){const r={};for(const n of t.chapters){const t=await No(e,n.chapterId,s),{chapterId:a,...i}=t;r[n.chapterId]=i}return{version:1,exportedAt:(new Date).toISOString(),chapters:r}},exports.exportChapterAnnotations=No,exports.flattenChapterTree=nl,exports.importChapterAnnotations=Fo,exports.importChapterAnnotationsArchive=async function(e,t,s){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[r,n]of Object.entries(t.chapters))await Fo(e,{chapterId:r,...n},s)},exports.overlapStrategyForSamePageOwner=function(e){return"last"===e?{kind:"last-wins"}:{kind:"first-wins"}},exports.parseChapterAnnotationsArchiveJson=function(e){const t=JSON.parse(e);if(!t||"object"!=typeof t||!t.chapters)throw new Error("无效的章节标注 JSON");return t},exports.parseChapterAnnotationsSnapshotJson=function(e){const t=JSON.parse(e);if(!(null==t?void 0:t.chapterId))throw new Error("无效的章节标注 JSON:缺少 chapterId");return t},exports.toChapterTreeNodes=al;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),s=require("@embedpdf/plugin-annotation"),r=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),i=require("@embedpdf/plugin-interaction-manager"),o=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),c=require("@embedpdf/plugin-history"),d=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),m=require("@embedpdf/plugin-commands"),f=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),P=require("@embedpdf/plugin-interaction-manager/vue"),I=require("@embedpdf/plugin-rotate/vue"),S=require("@embedpdf/plugin-selection/vue"),b=require("@embedpdf/plugin-annotation/vue"),C=require("@embedpdf/plugin-redaction/vue"),y=require("@embedpdf/plugin-render/vue"),w=require("@embedpdf/engines/vue"),M={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function L(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const $="#f1f5f9",k={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},D={highlight:r.PdfAnnotationSubtype.HIGHLIGHT,underline:r.PdfAnnotationSubtype.UNDERLINE,squiggly:r.PdfAnnotationSubtype.SQUIGGLY,strikeout:r.PdfAnnotationSubtype.STRIKEOUT};function U(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function E(e){let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function V(e,t,n,a,i){const o=n.forDocument(e),l=a.forDocument(e);if(!o||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",c=n.getTool(h);if(!c)return!1;const d=c.defaults,u={...k[g=t],...null==(m=i)?void 0:m[g]},p=l.getFormattedSelection();var g,m;if(0===p.length)return!1;o.setLocked({type:s.LockModeType.Exclude,categories:["markup","shape"]});for(const s of p){const e=r.uuidV4(),n=u.color??d.color??d.strokeColor,a=u.opacity??d.opacity,i=u.thickness??d.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(s.segmentRects,l):s.segmentRects,c="underline"===t||"squiggly"===t||"strikeout"===t?E(h):s.rect;o.createAnnotation(s.pageIndex,{id:e,created:new Date,flags:["print"],type:D[t],..."highlight"===t?{blendMode:r.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=i?{strokeWidth:i}:{},pageIndex:s.pageIndex,rect:c,segmentRects:h})}return l.clear(),!0}const A=new Set([r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT]);function T(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}function N(e){var t;const s=T(null==e?void 0:e.markup,{enabled:!0}),r=T(null==e?void 0:e.bookmarks,{enabled:!0}),n=T(null==e?void 0:e.notes,{enabled:!0}),a=T(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),i=T(void 0===(null==e?void 0:e.selectionToolbar)?!1!==s.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:s,bookmarks:r,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??$},selectionToolbar:i}}function F(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function O(e,t){return`${e}#s${t}`}function R(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return F(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=F(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:O(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}let z=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const B="chapter-manager",G={id:B,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,maxConcurrentSegmentLoads:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function _(e){const[t,s]=e.localPageRange;return s-t+1}function W(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function q(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return W(t)?t.segmentPageThreshold:null}function H(e,t){return`${e}#s${t}`}function K(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function j(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function X(e){const t=q(e);if(!t)return null;const s=_(e),r=j(s,t),n=W(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:H(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Y(e,t){const s=X(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Z(e,t){const s=X(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function J(e){var t;const s=q(e);if(!s)return[];const r=[],{chapterId:n}=e,a=_(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!W(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=j(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Q={kind:"first-wins"};function ee(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let te=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const se=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Q,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Q,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=K(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=K(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=K(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Y(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?X(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...J(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Q){const s=function(e,t=Q){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ee(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new te(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?X(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Z(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(W(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=X(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=X(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Z(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Z(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Y(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=X(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(W(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=q(t);if(a){const r=j(_(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(W(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=K(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?X(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};se.id="chapter-manager";let re=se;const ne={manifest:G,create:e=>new re(B,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",ie={id:ae,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:0,placeholderPageWidth:0,bufferSize:2,pageGap:20}};function oe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function le(e,t){return`${e}#s${t}`}function he(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ce(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return oe(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=oe(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function de(e){const[t,s]=e.localPageRange;return s-t+1}function ue(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function pe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ue(t)?t.segmentPageThreshold:null}function ge(e,t){return`${e}#s${t}`}function me(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function fe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ve(e){const t=pe(e);if(!t)return null;const s=de(e),r=fe(s,t),n=ue(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:ge(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Pe(e,t){const s=ve(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ie(e,t){const s=ve(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Se(e){var t;const s=pe(e);if(!s)return[];const r=[],{chapterId:n}=e,a=de(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ue(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=fe(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const be={kind:"first-wins"};function Ce(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ye=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const we=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=be,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??be,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=me(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=me(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=me(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Pe(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ve(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Se(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=be){const s=function(e,t=be){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ce(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ye(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ve(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ie(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ue(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ve(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ve(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ie(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Ie(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Pe(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ve(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ue(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=pe(t);if(a){const r=fe(de(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ue(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=me(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ve(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};we.id="chapter-manager";let Me=we;function xe(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const Le=792/612;function $e(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function ke(e){return 0===e.length?null:{width:$e(e.map(e=>e.width)),height:$e(e.map(e=>e.height))}}function De(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*Le)}}const Ue=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,xe),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Me.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=ce(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=ke(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=ke(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=ke(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=De(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?De(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=ce(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=he(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Ue.id="chapter-scroll";let Ee=Ue;const Ve={manifest:ie,create:e=>new Ee(ae,e),reducer:e=>e,initialState:{}},Ae="note",Te={id:Ae,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}};function Ne(e){const[t,s]=e.localPageRange;return s-t+1}function Fe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Oe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fe(t)?t.segmentPageThreshold:null}function Re(e,t){return`${e}#s${t}`}function ze(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Be(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ge(e){const t=Oe(e);if(!t)return null;const s=Ne(e),r=Be(s,t),n=Fe(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Re(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function _e(e,t){const s=Ge(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function We(e,t){const s=Ge(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function qe(e){var t;const s=Oe(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ne(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Fe(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Be(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const He={kind:"first-wins"};function Ke(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let je=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Xe=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=He,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??He,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ze(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ze(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ze(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?_e(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ge(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...qe(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=He){const s=function(e,t=He){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ke(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new je(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ge(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=We(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Fe(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ge(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ge(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=We(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=We(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=_e(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ge(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Fe(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Oe(t);if(a){const r=Be(Ne(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Fe(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ze(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ge(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Xe.id="chapter-manager";let Ye=Xe;function Ze(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Je(e,t){return`${e}#s${t}`}function Qe(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function et(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ze(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Ze(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Je(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function tt(e){const[t,s]=e.localPageRange;return s-t+1}function st(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function rt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return st(t)?t.segmentPageThreshold:null}function nt(e,t){return`${e}#s${t}`}function at(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function it(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ot(e){const t=rt(e);if(!t)return null;const s=tt(e),r=it(s,t),n=st(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:nt(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function lt(e,t){const s=ot(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ht(e,t){const s=ot(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ct(e){var t;const s=rt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=tt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!st(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=it(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const dt={kind:"first-wins"};function ut(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let pt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const gt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=dt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??dt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=at(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=at(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=at(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?lt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ot(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ct(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=dt){const s=function(e,t=dt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ut(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new pt(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ot(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ht(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(st(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ot(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ot(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=ht(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=ht(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=lt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ot(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(st(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=rt(t);if(a){const r=it(tt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(st(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=at(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ot(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};gt.id="chapter-manager";let mt=gt;function ft(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const vt=792/612;function Pt(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function It(e){return 0===e.length?null:{width:Pt(e.map(e=>e.width)),height:Pt(e.map(e=>e.height))}}function St(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*vt)}}const bt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ft),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(mt.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=et(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Qe(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Qe(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=It(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=It(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=It(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=St(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?St(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=et(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Qe(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};bt.id="chapter-scroll";let Ct=bt;const yt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Ct.id),this.chapterManager=this.registry.getPlugin(Ye.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Mt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};yt.id="note";let wt=yt;function Mt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const xt={manifest:Te,create:e=>new wt(Ae,e),reducer:e=>e,initialState:{}},Lt="paragraph-bookmark",$t={id:Lt,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function kt(e){const[t,s]=e.localPageRange;return s-t+1}function Dt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ut(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Dt(t)?t.segmentPageThreshold:null}function Et(e,t){return`${e}#s${t}`}function Vt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function At(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Tt(e){const t=Ut(e);if(!t)return null;const s=kt(e),r=At(s,t),n=Dt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Et(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Nt(e,t){const s=Tt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ft(e,t){const s=Tt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ot(e){var t;const s=Ut(e);if(!s)return[];const r=[],{chapterId:n}=e,a=kt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Dt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=At(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Rt={kind:"first-wins"};function zt(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Bt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Gt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Rt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Rt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Vt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Vt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Vt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Nt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Tt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ot(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Rt){const s=function(e,t=Rt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,zt(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Bt(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Tt(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ft(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Dt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Tt(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Tt(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ft(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Ft(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Nt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Tt(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Dt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ut(t);if(a){const r=At(kt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Dt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Vt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Tt(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Gt.id="chapter-manager";let _t=Gt;function Wt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function qt(e,t){return`${e}#s${t}`}function Ht(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Kt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Wt(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Wt(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:qt(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function jt(e){const[t,s]=e.localPageRange;return s-t+1}function Xt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Yt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xt(t)?t.segmentPageThreshold:null}function Zt(e,t){return`${e}#s${t}`}function Jt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Qt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function es(e){const t=Yt(e);if(!t)return null;const s=jt(e),r=Qt(s,t),n=Xt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Zt(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ts(e,t){const s=es(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ss(e,t){const s=es(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function rs(e){var t;const s=Yt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=jt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Xt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Qt(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ns={kind:"first-wins"};function as(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let is=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const os=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ns,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ns,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Jt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Jt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Jt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?ts(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?es(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...rs(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ns){const s=function(e,t=ns){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,as(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new is(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?es(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ss(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Xt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=es(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=es(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=ss(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=ss(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=ts(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=es(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Xt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Yt(t);if(a){const r=Qt(jt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Xt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Jt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?es(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};os.id="chapter-manager";let ls=os;function hs(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const cs=792/612;function ds(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function us(e){return 0===e.length?null:{width:ds(e.map(e=>e.width)),height:ds(e.map(e=>e.height))}}function ps(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*cs)}}const gs=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,hs),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ls.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Kt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ht(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ht(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=us(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=us(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=us(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=ps(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?ps(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=Kt(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Ht(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};gs.id="chapter-scroll";let ms=gs;function fs(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function vs(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ps(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function Is(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??vs(n),o=t.markerAnchor??vs(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(Ps(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}function Ss(e,t,s,r){const n=s.length>0?s:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==r?void 0:r.globalPageIndex,globalPageNumber:null==r?void 0:r.globalPageNumber,rectPdfCoord:fs(n),rectsPdfCoord:n,markerAnchor:vs(n)}}const bs=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ms.id),this.chapterManager=this.registry.getPlugin(_t.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(Is(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};bs.id="paragraph-bookmark";let Cs=bs;const ys={manifest:$t,create:e=>new Cs(Lt,e),reducer:e=>e,initialState:{}},ws={"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 Ms{constructor(){this.specs=[]}register(e){if(this.specs.some(t=>t.id===e.id))throw new Error(`OperationRegistry: duplicate operation id "${e.id}"`);this.specs.push(e)}registerAll(e){for(const t of e)t&&this.register(t)}list(){return this.specs}buildToolbars(){const e=structuredClone(ws);for(const t of this.specs){const s=e[t.toolbarSlot];if(!s)continue;const r={type:"command-button",id:t.id,commandId:t.commandId,variant:"icon",...t.icon?{icon:t.icon}:{},...t.i18nKey?{labelKey:t.i18nKey}:{},...t.label?{label:t.label}:{},categories:t.categories??[]};s.items=xs(s.items,r,t.position)}return e}}function xs(e,t,s){return(null==s?void 0:s.after)||(null==s?void 0:s.before)?function(e,t,s){const r=e=>{const n=[];for(const a of e)"group"!==a.type?s.before&&a.id===s.before?n.push(t,a):(n.push(a),s.after&&a.id===s.after&&n.push(t)):n.push({...a,items:r(a.items)});return n};return r(e)}(e,t,s):(r=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,r]}:e));var r}const Ls={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function $s(e){var t,r,P,I,S,b;const C=e.toolbar??{},y=C.enabledModes??["view","annotate","shapes","insert","form","redact"],w=y.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,s,r,n,a,i;const o=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new Ms;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),c={};for(const u of o){if("view"===u)continue;const e=Ls[u];h[e]&&(c[e]=h[e])}const d=function(e){if(0===e.size)return null;const t=(e,t,s)=>({type:"command-button",id:`${e}-mode`,commandId:s,variant:"text",label:t,categories:["mode",e]});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:[...e.has("view")?[t("view","View","mode:view")]:[],...e.has("annotate")?[t("annotate","Annotate","mode:annotate")]:[],...e.has("shapes")?[t("shapes","Shapes","mode:shapes")]:[],...e.has("insert")?[t("insert","Insert","mode:insert")]:[],...e.has("form")?[t("form","Form","mode:form")]:[],...e.has("redact")?[t("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(o);return d&&(c["chapter-editor-main-toolbar"]=d),(null==(s=e.extend)?void 0:s.toolbars)&&Object.assign(c,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:c,menus:(null==(r=e.extend)?void 0:r.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(i=e.extend)?void 0:i.selectionMenus)??{}},operationRegistry:l}}({...C,enabledModes:y}),L={...w?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var r,n,a,i;const o=null==(r=e.getPlugin("ui"))?void 0:r.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();o&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),o.forDocument(t).closeToolbarSlot("top","secondary"),null==(i=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked(e.getPluginConfig(s.ANNOTATION_PLUGIN_ID).locked??{type:s.LockModeType.None}))},active:({state:e,documentId:t})=>!v.isToolbarOpen(e.plugins,t,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.None}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...w?ks(x.list()):{},...e.commands??{}},$=[n.createPluginRegistration(a.DocumentManagerPluginPackage,{initialDocuments:[],maxDocuments:Number.MAX_SAFE_INTEGER}),n.createPluginRegistration(ne,{manifest:e.manifest,overlapStrategy:e.overlapStrategy??Es.overlapStrategy,passwordProvider:e.passwordProvider??Es.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters??Es.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads??Es.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs??Es.unloadTimeoutMs}),n.createPluginRegistration(Ve,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(i.InteractionManagerPluginPackage),n.createPluginRegistration(o.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(c.HistoryPluginPackage),n.createPluginRegistration(s.AnnotationPluginPackage),n.createPluginRegistration(d.RedactionPluginPackage),n.createPluginRegistration(u.FormPluginPackage),n.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),n.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(L).length>0?[n.createPluginRegistration(m.CommandsPluginPackage,{commands:L})]:[],...w?[n.createPluginRegistration(f.I18nPluginPackage),n.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&$.push(n.createPluginRegistration(xt,{callbacks:e.notes.callbacks,ui:null==(r=null==(t=e.features)?void 0:t.notes)?void 0:r.marker})),e.bookmarks&&$.push(n.createPluginRegistration(ys,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(b=null==(S=e.features)?void 0:S.bookmarks)?void 0:b.hover})),{plugins:$,uiSchema:M,operationRegistry:x}}function ks(e){const t={};for(const s of e)s.handler&&(t[s.commandId]={id:s.commandId,labelKey:s.i18nKey,label:s.label,icon:s.icon,categories:s.categories,action:({documentId:e})=>{var t;null==(t=s.handler)||t.call(s,{documentId:e,chapterId:e})}});return t}const Ds=N();function Us(e){return $s({...e,toolbar:e.toolbar??{enabledModes:[]},features:N(e.features)})}const Es={overlapStrategy:{kind:"first-wins"},passwordProvider:new z(async()=>null),prefetchChapters:1,maxConcurrentSegmentLoads:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function Vs(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function As(e){return{...Es,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Es.overlapStrategy,prefetchChapters:e.prefetchChapters??Es.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads??Es.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs??Es.unloadTimeoutMs,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:N(e.features)}}function Ts(e){const t=As(Vs(e)),{plugins:s}=Us(t);return{plugins:s,features:t.features,editorOptions:t}}function Ns(e,t=.5,s=3){return Math.min(s,Math.max(t,e))}function Fs(e,t){var s;if(t<=0)return 1;let r=0;for(const n of e.pages){const e=(null==(s=null==n?void 0:n.size)?void 0:s.width)??0;e>r&&(r=e)}return r<=0?1:t/r}function Os(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function Rs(e,t,s,r){const n=Os(t,s);if(n<=0)return r;const a=Fs(e,n);return Math.min(r,a)}function zs(e,t,s){const r=R(t);if(r){for(const t of r.segments){const r=e.getDocument(t.documentId);r&&s(r,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&s(n,t.chapterId)}function Bs(e){return e instanceof HTMLElement?e.clientWidth:0}function Gs(e,t,s){return Math.min(s,Math.max(t,e))}const _s={chapters:[]};function Ws(s){const r=e.ref(null),{provides:i}=t.useCapability(re.id),o=e.computed(()=>{var e;return(null==(e=i.value)?void 0:e.getManifest())??_s}),l=e.computed(()=>{var e;return null==(e=s.value)?void 0:e.zoom}),{scale:h,setScale:c,zoomEnabled:d,minZoom:u,maxZoom:p}=function(s,r,i){const o=e.isRef(s)?s:e.computed(()=>s),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:c}=t.useCapability(re.id),d=e.ref(v()),u=e.ref(d.value),p=e.ref(0),g=e.ref(!1),m=()=>{var e;return null==(e=r.value)?void 0:e.pageWidth},f=()=>{return null!=(e=m())&&e>0;var e},v=()=>{var e;return(null==(e=r.value)?void 0:e.initial)??1},P=e.computed(()=>{var e;return function(e,t,s,r,n){if(!e||s<=0)return n;let a=n;for(const i of t.chapters)zs(e,i,e=>{a=Math.min(a,Rs(e,s,r,n))});return a}(h.value,o.value,p.value,m(),(null==(e=r.value)?void 0:e.max)??3)}),I=e.computed(()=>{var e;return Math.min((null==(e=r.value)?void 0:e.min)??.5,P.value)});let S;function b(e){const t=P.value,s=I.value,r=Ns(e,s,t);u.value=r,d.value=r,function(e,t,s,r=.5,a=3){const i=null==e?void 0:e.getStore();if(!i)return;const o=Ns(s,r,a);i.dispatchToCore(n.setDefaultScale(o));for(const l of t.chapters){const e=R(l);if(e)for(const t of e.segments)i.getState().core.documents[t.documentId]&&i.dispatchToCore(n.setScale(o,t.documentId));else i.getState().core.documents[l.chapterId]&&i.dispatchToCore(n.setScale(o,l.chapterId))}}(l.value,o.value,r,s,t)}function C(e){if(!h.value||!c.value)return;const t=c.value.resolvePageDocument(e,0),s=h.value.getDocument(t.documentId);if(!s)return;const r=Os(p.value,m());r<=0||b(Fs(s,r))}function y(e){if(!g.value)return f()?C(e):b(v()),void(g.value=!0);b(u.value)}return e.watch(()=>null==i?void 0:i.value,e=>{null==S||S(),S=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let s=null;const r=new ResizeObserver(()=>{t(Bs(s))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==s?(s&&r.unobserve(s),s=n,s?(r.observe(s),t(Bs(s))):t(0)):t(Bs(s))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const i=requestAnimationFrame(n);return()=>{cancelAnimationFrame(i),a.disconnect(),s&&r.unobserve(s),r.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==S?void 0:S()),e.watch([l,()=>v(),()=>f()],()=>{l.value&&(f()||b(v()))},{immediate:!0}),e.watch(P,e=>{u.value>e&&b(e)}),e.watch([c,o,()=>f(),()=>v()],()=>{const e=c.value;if(e){for(const t of o.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&y(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&y(e.chapterId)})}},{immediate:!0}),e.watch(h,(e,t,s)=>{e&&s(e.onDocumentOpened(()=>{g.value&&b(u.value)}))}),e.watch([p,()=>f(),c,o],()=>{if(f()&&!(p.value<=0)&&c.value&&!g.value)for(const e of o.value.chapters)if("loaded"===c.value.getChapterStatus(e.chapterId)){C(e.chapterId),g.value=!0;break}}),{scale:d,setScale:b,zoomEnabled:()=>{var e;return!1!==(null==(e=r.value)?void 0:e.enabled)},minZoom:I,maxZoom:P}}(o,l,r);return function(t,s){let r=null;e.watch([t,s],()=>{null==r||r();const e=s.value;r=function(e,t){if(!e||!1===t.enabled)return()=>{};let s=null,r=null,n=0;const a=()=>{const r=e.querySelector("[data-chapter-scroll-viewport]");return!!r&&(null==s||s(),s=function({container:e,getScale:t,setScale:s,minZoom:r=.5,maxZoom:n=3}){let a=0,i=1,o=null,l=1,h=1;const c=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===o?(h=t(),l=1):clearTimeout(o),l*=1-.01*e.deltaY,l=Gs(l,.1,10),s(Gs(h*l,r,n)),o=setTimeout(()=>{o=null},120))},d=new Map,u=e=>{if(d.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===d.size){const[e,s]=[...d.values()];a=Math.hypot(s.x-e.x,s.y-e.y),i=t()}},p=e=>{if(d.has(e.pointerId)&&(d.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===d.size&&a>0)){e.preventDefault();const[t,o]=[...d.values()],l=Math.hypot(o.x-t.x,o.y-t.y);s(Gs(i*(l/a),r,n))}},g=e=>{d.delete(e.pointerId),d.size<2&&(a=0)};return e.addEventListener("wheel",c,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",c),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),o&&clearTimeout(o)}}({container:r,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(r=new MutationObserver(()=>{a()&&(null==r||r.disconnect(),r=null)}),r.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==r||r.disconnect(),null==s||s()}}(t.value??null,{enabled:e.enabled,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom})},{deep:!0,flush:"post"}),e.onBeforeUnmount(()=>null==r?void 0:r())}(r,e.computed(()=>({enabled:d(),getScale:()=>h.value,setScale:c,minZoom:u.value,maxZoom:p.value}))),{hostRef:r,scale:h,setScale:c,zoomEnabled:d}}function qs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Hs(e,t){return`${e}#s${t}`}function Ks(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function js(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return qs(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=qs(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Hs(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Xs(e){const[t,s]=e.localPageRange;return s-t+1}function Ys(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Zs(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ys(t)?t.segmentPageThreshold:null}function Js(e,t){return`${e}#s${t}`}function Qs(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function er(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function tr(e){const t=Zs(e);if(!t)return null;const s=Xs(e),r=er(s,t),n=Ys(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Js(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function sr(e,t){const s=tr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function rr(e,t){const s=tr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function nr(e){var t;const s=Zs(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Xs(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ys(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=er(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ar={kind:"first-wins"};function ir(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class or{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const lr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ar,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ar,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Qs(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Qs(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Qs(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?sr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?tr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...nr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ar){const s=function(e,t=ar){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ir(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new or(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?tr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=rr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ys(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=tr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=tr(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=rr(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=rr(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=sr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=tr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ys(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Zs(t);if(a){const r=er(Xs(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ys(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Qs(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?tr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};lr.id="chapter-manager";let hr=lr;function cr(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const dr=792/612;function ur(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function pr(e){return 0===e.length?null:{width:ur(e.map(e=>e.width)),height:ur(e.map(e=>e.height))}}function gr(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*dr)}}const mr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,cr),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(hr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=js(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ks(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ks(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=pr(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=pr(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=pr(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=gr(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?gr(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=js(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Ks(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};mr.id="chapter-scroll";let fr=mr;const vr=["data-global-page-index","data-chapter-id","data-local-page-index"],Pr=(e=>{const t=e.__vccOpts||e;for(const[s,r]of[["__scopeId","data-v-e9ab4da3"]])t[s]=r;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(s){const{provides:r}=t.useCapability(fr.id),n=e.ref(null),a=e.ref(null);let i=null;const o=()=>{null==i||i(),i=null,r.value&&(r.value.registerViewport(n.value),i=r.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(o),e.onBeforeUnmount(()=>{var e;null==i||i(),null==(e=r.value)||e.registerViewport(null)}),e.watch(r,o),(t,s)=>{var r,i,o;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:n,"data-chapter-scroll-viewport":"",class:e.normalizeClass(t.$props.class),style:e.normalizeStyle({overflow:"auto",overflowX:"hidden",position:"relative",width:"100%",height:"100%",...t.$props.style})},[e.createElementVNode("div",{style:e.normalizeStyle({position:"relative",width:`${(null==(r=a.value)?void 0:r.totalWidth)??0}px`,height:`${(null==(i=a.value)?void 0:i.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(o=a.value)?void 0:o.items)??[],r=>(e.openBlock(),e.createElementBlock("div",{key:r.globalPageIndex,"data-global-page-index":r.globalPageIndex,"data-chapter-id":r.chapterId,"data-local-page-index":r.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${r.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${r.width}px`,height:`${r.height}px`,backgroundColor:r.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[r.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:r},()=>[s[0]||(s[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:r},void 0,!0)],12,vr))),128))],4)],6)}}})),Ir=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const s=t;return(r,n)=>(e.openBlock(),e.createBlock(e.unref(y.RenderLayer),{"document-id":s.pdfDocumentId??s.chapterId,"page-index":s.pdfPageIndex??s.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}});function Sr(e){const[t,s]=e.localPageRange;return s-t+1}function br(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Cr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return br(t)?t.segmentPageThreshold:null}function yr(e,t){return`${e}#s${t}`}function wr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Mr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function xr(e){const t=Cr(e);if(!t)return null;const s=Sr(e),r=Mr(s,t),n=br(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:yr(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Lr(e,t){const s=xr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function $r(e,t){const s=xr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function kr(e){var t;const s=Cr(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Sr(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!br(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Mr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Dr={kind:"first-wins"};function Ur(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Er=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Vr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Dr,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Dr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=wr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=wr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=wr(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Lr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?xr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...kr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Dr){const s=function(e,t=Dr){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ur(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Er(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?xr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=$r(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(br(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=xr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=xr(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=$r(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=$r(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Lr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=xr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(br(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Cr(t);if(a){const r=Mr(Sr(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(br(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=wr(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?xr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Vr.id="chapter-manager";let Ar=Vr;function Tr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Nr(e,t){return`${e}#s${t}`}function Fr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Or(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Tr(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Tr(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Nr(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Rr(e){const[t,s]=e.localPageRange;return s-t+1}function zr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Br(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zr(t)?t.segmentPageThreshold:null}function Gr(e,t){return`${e}#s${t}`}function _r(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Wr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function qr(e){const t=Br(e);if(!t)return null;const s=Rr(e),r=Wr(s,t),n=zr(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Gr(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Hr(e,t){const s=qr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Kr(e,t){const s=qr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function jr(e){var t;const s=Br(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Rr(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!zr(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Wr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Xr={kind:"first-wins"};function Yr(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Zr{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Jr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Xr,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Xr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=_r(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=_r(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=_r(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Hr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?qr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...jr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Xr){const s=function(e,t=Xr){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Yr(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Zr(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?qr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Kr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(zr(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=qr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=qr(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Kr(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Kr(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Hr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=qr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(zr(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Br(t);if(a){const r=Wr(Rr(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(zr(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=_r(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?qr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Jr.id="chapter-manager";let Qr=Jr;function en(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const tn=792/612;function sn(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function rn(e){return 0===e.length?null:{width:sn(e.map(e=>e.width)),height:sn(e.map(e=>e.height))}}function nn(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*tn)}}const an=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,en),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Qr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Or(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Fr(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Fr(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=rn(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=rn(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=rn(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=nn(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?nn(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=Or(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=Fr(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};an.id="chapter-scroll";let on=an;const ln=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(on.id),this.chapterManager=this.registry.getPlugin(Ar.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:cn(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};ln.id="note";let hn=ln;function cn(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function dn(e){const{markerPdf:t,lineRects:s,sx:r,sy:n,cssPageWidth:a,iconSize:i,gapPx:o=6}=e,l=(null==s?void 0:s.length)?s[s.length-1]:void 0;let h,c;l?(h=(l.origin.x+l.size.width)*r+o,c=l.origin.y*n+(l.size.height*n-i)/2):(h=t.x*r-i/2,c=t.y*n-i-o);const d=Math.max(0,a-i-2);return h>d&&(h=d),c<0&&(c=0),{left:h,top:c}}const un={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},pn=["onMouseenter"],gn=["data-note-marker-zone","onMouseenter","onMouseleave"],mn=["onClick"],fn=["onClick"],vn=["onClick"],Pn=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(hn.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===r.chapterId&&e.localPageIndex===r.localPageIndex)})},{immediate:!0});let l=null;e.watch(o,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var s;const r=t.target;(null==(s=r.closest)?void 0:s.call(r,`[data-note-marker-zone="${e}"]`))||(o.value=null,i.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16}),c=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function d(e){const t=r.cssPageWidth/r.pdfPageWidth,s=r.cssPageHeight/r.pdfPageHeight,n=h.value,{left:a,top:i}=dn({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:s,cssPageWidth:r.cssPageWidth,iconSize:n}),l=function(e,t,s){let r=1/0,n=1/0,a=-1/0,i=-1/0;for(const o of e)r=Math.min(r,o.origin.x*t),n=Math.min(n,o.origin.y*s),a=Math.max(a,(o.origin.x+o.size.width)*t),i=Math.max(i,(o.origin.y+o.size.height)*s);return{left:r,top:n,width:a-r,height:i-n}}(e.rectsPdfCoord,t,s),c=o.value===e.noteId?72:0,d=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,i)-8);return{zoneLeft:d,zoneTop:u,zoneW:Math.min(r.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-d,zoneH:Math.max(l.top+l.height,i+n+6+c)+8-u,iconLeft:a,iconTop:i,sx:t,sy:s}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",un,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(s,r)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${r}`,style:e.normalizeStyle({position:"absolute",left:s.origin.x*d(t).sx+"px",top:s.origin.y*d(t).sy+"px",width:s.size.width*d(t).sx+"px",height:s.size.height*d(t).sy+"px",background:c.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>i.value=t.noteId},null,44,pn))),128)),i.value===t.noteId||o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${d(t).zoneLeft}px`,top:`${d(t).zoneTop}px`,width:`${d(t).zoneW}px`,height:`${d(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>i.value=t.noteId,onMouseleave:e=>o.value!==t.noteId&&(i.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:d(t).iconLeft-d(t).zoneLeft+"px",top:d(t).iconTop-d(t).zoneTop+"px",width:`${h.value}px`,height:`${h.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:r[0]||(r[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>o.value=o.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,mn),o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:d(t).iconLeft-d(t).zoneLeft+"px",top:`${d(t).iconTop-d(t).zoneTop+h.value+4}px`,minWidth:"120px",padding:"6px",borderRadius:"8px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)",zIndex:30}),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#334155",cursor:"pointer","text-align":"left"},onClick:e=>{return s=t,void(null==(r=n.value)||r.requestEditNote(s.noteId,s));var s,r}}," 编辑 ",8,fn),e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>{var s,r;return r=t.noteId,null==(s=n.value)||s.requestDeleteNote(r),void(o.value=null)}}," 删除 ",8,vn)],36)):e.createCommentVNode("",!0)],44,gn)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),In={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Sn=["title","onClick"],bn=["onClick"],Cn=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(Cs.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===r.chapterId&&e.anchor.localPageIndex===r.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(i,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=o.value)?void 0:t.contains(e.target))||(i.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const c=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16});function d(e){const{left:t,top:s}=function(e){var t;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return dn({markerPdf: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},lineRects:a,sx:s,sy:n,cssPageWidth:r.cssPageWidth,iconSize:c.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,s-6)}px`,width:`${c.value+12}px`,height:`${c.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",In,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(d(t)),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${c.value}px`,height:`${c.value}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",fontSize:"11px",padding:0}),onClick:e.withModifiers(e=>i.value=i.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Sn),i.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:o,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:r[0]||(r[0]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>async function(e){const t=n.value;t&&await t.requestRemoveBookmark(e)&&(i.value=null)}(t.id)}," 删除书签 ",8,bn)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}}),yn="embedpdf-chapter-copy-toast";function wn(e){return e.pdfDocumentId??e.chapterId}function Mn(e){return e.pdfPageIndex??e.localPageIndex}function xn(e,t){e.wait(t,()=>{})}const Ln={display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px",borderRadius:"8px",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)"},$n={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const kn=e.defineComponent({__name:"ChapterPageSurface",props:{item:{},features:{},showNoteMarkers:{type:Boolean},showBookmarkMarkers:{type:Boolean},showRedactionLayer:{type:Boolean},noteMarkerUi:{},bookmarkMarkerUi:{},buildSelectionMenu:{type:Function},createNote:{},annotationSelectionMenu:{},redactionSelectionMenu:{},renderPageOverlay:{type:Function}},setup(s){const r=s,n=e.computed(()=>wn(r.item)),i=e.computed(()=>Mn(r.item));!function(s){const{provides:r}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([r,s],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:o}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),c=e.computed(()=>{var e,t;return null==(t=null==(e=o.value)?void 0:e.getDocument(n.value))?void 0:t.pages[i.value]});function d(t,s){var n,a,i,o;const h=r.createNote.value;if(h&&!1!==(null==(a=null==(n=r.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(o=null==(i=r.features)?void 0:i.selectionToolbar)?void 0:o.enabled))return r=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=r.placement)?void 0:n.suggestTop)?-40:r.rect.size.height+8};return e.h("div",r.menuWrapperProps,[e.h("div",{style:a},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!l.value)return;const e=l.value.getHighlightRectsForPage(Mn(t),s);xn(l.value.getSelectedText(s),s=>{var r,n,a;h((r=t,n=e,a=s.join("\n"),{chapterId:r.chapterId,localPageIndex:r.localPageIndex,globalPageIndex:r.globalPageIndex,globalPageNumber:r.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=r.buildSelectionMenu,t={item:r.item,defaultMenu:d(r.item,n.value),createNote:r.createNote.value};if(e){const s=e(t);if(s)return s}return t.defaultMenu}),p=function(t,s){var r,n;const{provides:a}=b.useAnnotationCapability(),i=null==(r=null==s?void 0:s.markup)?void 0:r.annotationMenu,o=!1!==(null==(n=null==s?void 0:s.markup)?void 0:n.enabled),l=!1!==(null==i?void 0:i.enabled);return e.computed(()=>{const s="string"==typeof t?t:t.value;if(o&&l&&a.value)return t=>{const{context:r,rect:n,placement:o,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==r.type)return e.h("span",l);if(r.structurallyLocked)return e.h("span",l);if(c=r.annotation.object.type,!A.has(c))return e.h("span",l);var c;const d=a.value.forDocument(s),{pageIndex:u,id:p}=r.annotation.object,g=()=>{null==d||d.deleteAnnotation(u,p)},m={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==o?void 0:o.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==o?void 0:o.suggestTop)?`${n.size.height+8}px`:void 0},f=(null==i?void 0:i.renderMenu)?i.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:$n,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:Ln,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(n,r.features),g=e.computed(()=>function(e,t){if(e||t)return s=>{if(e){const t=e(s);if(null!=t)return t}return(null==t?void 0:t(s))??null}}(r.annotationSelectionMenu,p.value)),m=e.computed(()=>{var e;return null==(e=r.renderPageOverlay)?void 0:e.call(r,r.item)}),f=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=r.features)?void 0:e.selectionToolbar)});return(t,r)=>s.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(P.GlobalPointerProvider),{key:0,"document-id":n.value},{default:e.withCtx(()=>[e.createVNode(e.unref(I.Rotate),{"document-id":n.value,"page-index":i.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":i.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(L)},{default:e.withCtx(()=>[e.createVNode(e.unref(Ir),{"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":i.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(S.SelectionLayer),{"document-id":n.value,"page-index":i.value,"text-style":f.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),s.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(C.RedactionLayer),{key:0,"document-id":n.value,"page-index":i.value,"selection-menu":s.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(b.AnnotationLayer),{"document-id":n.value,"page-index":i.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),s.showBookmarkMarkers&&c.value?(e.openBlock(),e.createBlock(Cn,{key:1,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":c.value.size.width,"pdf-page-height":c.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(m.value),{key:2})):e.createCommentVNode("",!0),s.showNoteMarkers&&c.value?(e.openBlock(),e.createBlock(Pn,{key:3,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":c.value.size.width,"pdf-page-height":c.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.noteMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"default")]),_:3},8,["document-id","page-index","style","onPointerdown"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),Dn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(s){const r=s,n=e.computed(()=>wn(r.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:i}=t.useCapability(Cs.id),o=e.ref(null),l=e.ref(null),c=e.ref(null),d=e.ref(null),u=e.computed(()=>{var e;return(null==(e=r.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>d.value??c.value);let g=null,m=0;function f(){const e=a.value;if(!e)return;const t=e.forDocument(n.value).getState().geometry[r.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>r.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(m),l.value=null,!e)return;const t=e.forDocument(n.value);g=t.onSelectionChange(f);let s=!1;const a=()=>{if(!s){try{if(f(),t.getState().geometry[r.item.localPageIndex])return}catch{}m=requestAnimationFrame(a)}};return a(),()=>{s=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>r.pdfPageWidth,d,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&r.pdfPageWidth&&(v=e=>{if(d.value)return;const t=a.value;if(t)try{if(t.forDocument(n.value).getState().selecting)return void(c.value=null)}catch{}const s=o.value;if(!s)return;const i=s.getBoundingClientRect();if(e.clientX<i.left||e.clientX>i.right||e.clientY<i.top||e.clientY>i.bottom)return void(c.value=null);const u=function(e,t){const s=h.glyphAt(e,t);if(s<0)return null;const r=h.expandToLineBoundary(e,s);if(!r)return null;const n=h.rectsWithinSlice(e,r.from,r.to);return 0===n.length?null:{lineRects:n,charFrom:r.from,charTo:r.to}}(l.value,{x:(e.clientX-i.left)/(r.cssPageWidth/r.pdfPageWidth),y:(e.clientY-i.top)/(r.cssPageHeight/r.pdfPageHeight)});c.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(m),null==g||g()});const P=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?Ss(r.item.chapterId,r.item.localPageIndex,e,{globalPageIndex:r.item.globalPageIndex,globalPageNumber:r.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=i.value;return!(!e||!t)&&t.listBookmarks().some(t=>Is(t.anchor,e))});function S(){const e=i.value,t=P.value;e&&t&&!I.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),c.value=null,d.value=null)}const b=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!r.pdfPageWidth)return null;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*s+6,Math.max(0,r.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*s-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,r)=>{var n;return e.unref(i)&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:o,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[b.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${b.value.zoneLeft}px`,top:`${b.value.zoneTop}px`,width:`${b.value.size+20}px`,height:`${((null==(n=p.value[p.value.length-1])?void 0:n.size.height)??0)*(s.cssPageHeight/s.pdfPageHeight)+b.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:r[0]||(r[0]=e=>d.value=p.value),onMouseleave:r[1]||(r[1]=e=>d.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:b.value.iconLeft-b.value.zoneLeft+"px",top:b.value.iconTop-b.value.zoneTop+"px",width:`${b.value.size}px`,height:`${b.value.size}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"#3b82f6",color:"#fff",border:"none",borderRadius:"4px",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",padding:0}),onClick:e.withModifiers(S,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),Un="#64748b",En={key:0,width:"20",height:"20",viewBox:"0 0 1024 1024",fill:"none","aria-hidden":""},Vn=["d","fill"],An={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},Tn={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Nn={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Fn={key:2,d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626","stroke-width":"2","stroke-linecap":"round",fill:"none"},On={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Rn={key:2,width:"20",height:"20",viewBox:"0 0 1024 1024",fill:"none","aria-hidden":""},zn=["d","fill"],Bn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(s,r)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",En,[e.createElementVNode("path",{d:e.unref("M753.312 698.848 753.312 383.6736c0-62.048-50.3104-112.3264-112.288-112.3264L395.3024 271.3472 324.288 271.3472l-53.7344 0-29.536 0c-62.048 0-112.288 50.272-112.288 112.3264l0 400.0512c0 61.9776 50.24 112.2752 112.288 112.2752l400.0128 0c62.048 0 112.288-50.2976 112.288-112.2752l0-31.0656 0.8768 0 0-54.0352C753.888 698.624 753.6768 698.7776 753.312 698.848zM660.6016 681.728l0 42.5984c0 0.864-0.2368 1.792-0.2368 2.6688-1.4272 42.3552-36.064 76.3008-78.7328 76.3008L300.3392 803.296c-43.5968 0-78.9056-35.3664-78.9056-78.9696L221.4336 442.9888c0-42.2336 33.2608-76.4928 75.0144-78.5984 1.2928-0.064 2.5984-0.3712 3.8912-0.3712l41.4272 0L581.632 364.0192c43.6608 0 78.9696 35.4048 78.9696 78.9696L660.6016 681.728zM895.1232 555.5008 895.1232 240.3264c0-62.048-50.3104-112.3264-112.288-112.3264L537.1136 128 466.0992 128l-53.7344 0-29.536 0c-62.048 0-112.288 50.272-112.288 112.3264l0 4.4736 115.0784 0c13.4912-13.8112 32.0256-22.72 52.6464-23.7568 1.2864-0.064 2.592-0.3712 3.8848-0.3712l41.4272 0 239.8656 0c43.6608 0 78.9696 35.4048 78.9696 78.9696l0 238.7328 0 42.5984c0 0.864-0.2368 1.792-0.2368 2.6688-0.8768 25.9136-14.208 48.6336-34.176 62.4l0 106.6048 14.8352 0c62.048 0 112.288-50.2976 112.288-112.2752l0-31.0656L896 609.3056l0-54.0352C895.6992 555.2768 895.488 555.424 895.1232 555.5008z"),fill:e.unref(Un)},null,8,Vn)])):"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",An,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",Tn)):e.createCommentVNode("",!0),r[0]||(r[0]=e.createElementVNode("text",{x:"14",y:"19","text-anchor":"middle","font-size":"15","font-weight":"700","font-family":"system-ui, -apple-system, sans-serif",fill:"#0f172a"}," A ",-1)),"underline"===t.kind?(e.openBlock(),e.createElementBlock("path",Nn)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",Fn)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",On)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Rn,[e.createElementVNode("path",{d:e.unref("M725.333333 85.333333a170.666667 170.666667 0 0 1 170.666667 170.666667v512a170.666667 170.666667 0 0 1-170.666667 170.666667H298.666667a170.666667 170.666667 0 0 1-170.666667-170.666667V256a170.666667 170.666667 0 0 1 170.666667-170.666667h426.666666z m0 85.333334H298.666667a85.333333 85.333333 0 0 0-85.12 78.933333L213.333333 256v512a85.333333 85.333333 0 0 0 78.933334 85.12L298.666667 853.333333h426.666666a85.333333 85.333333 0 0 0 85.12-78.933333L810.666667 768V256a85.333333 85.333333 0 0 0-78.933334-85.12L725.333333 170.666667z m-42.666666 469.333333a42.666667 42.666667 0 0 1 4.992 85.034667L682.666667 725.333333H341.333333a42.666667 42.666667 0 0 1-4.992-85.034666L341.333333 640h341.333334z m0-170.666667a42.666667 42.666667 0 1 1 0 85.333334H341.333333a42.666667 42.666667 0 1 1 0-85.333334h341.333334z m-170.666667-170.666666a42.666667 42.666667 0 0 1 4.992 85.034666L512 384H341.333333a42.666667 42.666667 0 0 1-4.992-85.034667L341.333333 298.666667h170.666667z"),fill:e.unref(Un)},null,8,zn)]))}),Gn=["title","aria-label","onMouseenter","onClick"],_n=["title","onMouseenter","onClick"],Wn={style:{"font-size":"11px","font-weight":"600"}},qn=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:s}){const r=t,n=s,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],i=e.computed(()=>new Set(r.hiddenBuiltinActions??[])),o=e.computed(()=>!i.value.has("copy")),l=e.computed(()=>a.filter(e=>!i.value.has(e.id))),h=e.computed(()=>!i.value.has("note")),c=e.computed(()=>[...r.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),d=e.computed(()=>l.value.length>0||c.value.length>0),u=e.ref(null),p=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:r.placementAbove?void 0:`${r.anchorHeight+10}px`,bottom:r.placementAbove?`${r.anchorHeight+10}px`:void 0,display:"flex",alignItems:"center",gap:"2px",padding:"4px 6px",borderRadius:"12px",background:"rgba(255, 255, 255, 0.96)",border:"1px solid rgba(15, 23, 42, 0.06)",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.08), 0 12px 32px rgba(15, 23, 42, 0.1)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)"}));function g(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:u.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const m={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(s,r)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[o.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:r[0]||(r[0]=e=>u.value="copy"),onMouseleave:r[1]||(r[1]=e=>u.value=null),onClick:r[2]||(r[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(Bn,{key:1,kind:"copy"}))],36),d.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[3]||(r[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(Bn,{kind:t.id},null,8,["kind"])],44,Gn))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[4]||(r[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",Wn,e.toDisplayString(t.label.slice(0,2)),1)],44,_n))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[d.value||o.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(g("note",!0)),onMouseenter:r[5]||(r[5]=e=>u.value="note"),onMouseleave:r[6]||(r[6]=e=>u.value=null),onClick:r[7]||(r[7]=e=>n("action","note"))},[e.createVNode(Bn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Hn={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},Kn=e.defineComponent({__name:"PdfChapterViewport",props:{className:{},features:{},buildSelectionMenu:{},annotationSelectionMenu:{},redactionSelectionMenu:{},showNoteMarkers:{type:Boolean,default:!0},showBookmarkMarkers:{type:Boolean,default:!0},showRedactionLayer:{type:Boolean,default:!1},renderPageOverlay:{},onExtraSelectionAction:{}},setup(r){const n=r,i=e.computed(()=>n.features),{hostRef:o}=Ws(i),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=n.features)?void 0:e.scrollViewport)?void 0:t.background)??$}}),c=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e,t,r;const n=null==(r=null==(t=null==(e=s.value)?void 0:e.getPlugin(wt.id))?void 0:t.provides)?void 0:r.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),d=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(wt.id))})}(),u=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(Cs.id))})}(),p=e.computed(()=>{var e,t;return n.showNoteMarkers&&d.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return n.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(r,n){const a=e.computed(()=>{var e;return null==(e=r())?void 0:e.selectionToolbar}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.markup)?void 0:t.enabled)}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.notes)?void 0:t.enabled)}),l=e.computed(()=>{var e,t;return!(null==(t=null==(e=a.value)?void 0:e.hiddenBuiltinActions)?void 0:t.includes("copy"))}),{provides:c}=t.useCapability(h.SelectionPlugin.id),{provides:d}=t.useCapability(s.AnnotationPlugin.id),{provides:u}=t.useCapability(wt.id);return e.computed(()=>{var t,s,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(i.value||o.value||l.value||(null==(h=null==(s=a.value)?void 0:s.extraActions)?void 0:h.length)))return t=>{const s=wn(t.item),h=Mn(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(qn,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(m=a.value)?void 0:m.hiddenBuiltinActions,extraActions:null==(f=a.value)?void 0:f.extraActions,renderCopyIcon:null==(v=a.value)?void 0:v.renderCopyIcon,onAction:e=>{var a,p,g;if("copy"!==e)if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!c.value||!u.value||!o.value)return;const e=c.value.getHighlightRectsForPage(h,s);return void xn(c.value.getSelectedText(s),s=>{var r;null==(r=u.value)||r.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:s.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!c.value||!d.value||!i.value)return;V(s,Hn[e],d.value,c.value,null==(g=null==(p=r())?void 0:p.markup)?void 0:g.styles)}else{if(!c.value||!l.value)return;xn(c.value.getSelectedText(s),e=>{!async function(e){var t;const s=e.trim();if(!s)return!1;const r=()=>{!function(e="已复制"){var t;if("undefined"==typeof document)return;null==(t=document.getElementById(yn))||t.remove();const s=document.createElement("div");s.id=yn,s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),s.textContent=e,Object.assign(s.style,{position:"fixed",left:"50%",bottom:"48px",transform:"translateX(-50%)",padding:"10px 18px",borderRadius:"8px",background:"rgba(15, 23, 42, 0.88)",color:"#fff",fontSize:"13px",lineHeight:"1.4",fontFamily:"system-ui, -apple-system, sans-serif",zIndex:"99999",pointerEvents:"none",boxShadow:"0 4px 16px rgba(15, 23, 42, 0.2)",opacity:"0",transition:"opacity 200ms ease"}),document.body.appendChild(s),requestAnimationFrame(()=>{s.style.opacity="1"}),window.setTimeout(()=>{s.style.opacity="0",window.setTimeout(()=>s.remove(),200)},1800)}("已复制")};try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),r(),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t&&r(),t}catch{return!1}}(e.join("\n"))})}}}))}}})}(()=>n.features,{onExtraAction:n.onExtraSelectionAction}),v=e.computed(()=>{if(n.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return n.buildSelectionMenu?n.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(a.DocumentManagerPlugin.id);function I(t){var s;const r=[];if(m.value){const s=function(t){var s,r,a,i;const o=wn(t),l=Mn(t),h=null==(r=null==(s=P.value)?void 0:s.getDocument(o))?void 0:r.pages[l];return t.isPlaceholder||!h?null:e.h(Dn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(i=null==(a=n.features)?void 0:a.bookmarks)?void 0:i.hover})}(t);s&&r.push(s)}const a=null==(s=n.renderPageOverlay)?void 0:s.call(n,t);if(a&&r.push(a),r.length)return e.h("div",r)}return(t,s)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:o,class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(Pr),{class:e.normalizeClass(r.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var s,n,a,i;return[e.createVNode(kn,{item:t,features:r.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":r.showRedactionLayer,"note-marker-ui":null==(n=null==(s=r.features)?void 0:s.notes)?void 0:n.marker,"bookmark-marker-ui":null==(i=null==(a=r.features)?void 0:a.bookmarks)?void 0:i.marker,"build-selection-menu":v.value,"create-note":e.unref(c),"annotation-selection-menu":r.annotationSelectionMenu,"redaction-selection-menu":r.redactionSelectionMenu,"render-page-overlay":I},null,8,["item","features","show-note-markers","show-bookmark-markers","show-redaction-layer","note-marker-ui","bookmark-marker-ui","build-selection-menu","create-note","annotation-selection-menu","redaction-selection-menu"])]}),_:1},8,["class","style"]),e.renderSlot(t.$slots,"default")],6))}}),jn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},Xn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(s){const r=s,n=e.computed(()=>function(e){if(e.options)return Ts(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=N(e.features),s={...e.editorOptions,prefetchChapters:e.editorOptions.prefetchChapters??Es.prefetchChapters,maxConcurrentSegmentLoads:e.editorOptions.maxConcurrentSegmentLoads??Es.maxConcurrentSegmentLoads,unloadTimeoutMs:e.editorOptions.unloadTimeoutMs??Es.unloadTimeoutMs,features:t},{plugins:r}=Us(s);return{plugins:r,features:t,editorOptions:s}}({engine:r.engine,options:r.options,editorOptions:r.editorOptions,features:r.features}));return(r,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:s.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",jn,[e.renderSlot(r.$slots,"prepend"),e.createVNode(Kn,{class:e.normalizeClass(s.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":s.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(r.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),Yn={class:"chapter-tree-row"},Zn=["aria-expanded"],Jn={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Qn={class:"chapter-tree-label"},ea={class:"chapter-tree-meta"},ta={key:0},sa=(e,t)=>{const s=e.__vccOpts||e;for(const[r,n]of t)s[r]=n;return s},ra=sa(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const s={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},r=t,n=e.computed(()=>r.node.children??[]),a=e.computed(()=>n.value.length>0),i=e.ref(r.depth<1),o=e.computed(()=>r.activeChapterId===r.node.id),l=e.computed(()=>r.chapterStatus[r.node.id]??"idle"),h=e.computed(()=>!a.value);return(r,c)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",Yn,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":i.value,onClick:c[0]||(c[0]=e=>i.value=!i.value)},e.toDisplayString(i.value?"▼":"▶"),9,Zn)):(e.openBlock(),e.createElementBlock("span",Jn)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":o.value}]),onClick:c[1]||(c[1]=e=>r.$emit("select",t.node.id))},[e.createElementVNode("div",Qn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",ea,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),h.value?(e.openBlock(),e.createElementBlock("span",ta,e.toDisplayString(s[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&i.value?(e.openBlock(),e.createBlock(na,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:c[2]||(c[2]=e=>r.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),na=sa(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(s,r)=>(e.openBlock(),e.createElementBlock("ul",{class:"chapter-tree-list",style:e.normalizeStyle({marginLeft:t.depth>0?"12px":"0"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.nodes,n=>(e.openBlock(),e.createBlock(ra,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:r[0]||(r[0]=e=>s.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),aa={class:"chapter-tree"},ia={class:"chapter-tree-nav","aria-label":"章节目录"},oa=sa(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(s,{emit:r}){const n=s,a=r,{provides:i}=t.useCapability(Ee.id),{provides:o}=t.useCapability(re.id),l=e.ref({});function h(){if(!o.value)return;const e={},t=s=>{var r;for(const n of s)e[n.id]=o.value.getChapterStatus(n.id),(null==(r=n.children)?void 0:r.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([o,()=>n.tree],h,{immediate:!0});let c=null;function d(e){var t;a("active-chapter-change",e),null==(t=i.value)||t.scrollToChapter(e)}return e.watch(o,e=>{null==c||c(),c=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==c?void 0:c()),(t,r)=>(e.openBlock(),e.createElementBlock("aside",aa,[r[0]||(r[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",ia,[e.createVNode(na,{nodes:s.tree,depth:0,"active-chapter-id":s.activeChapterId,"chapter-status":l.value,onSelect:d},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),la=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,s)=>(e.openBlock(),e.createBlock(e.unref(Xn),e.normalizeProps(e.guardReactiveProps(t.$props)),e.createSlots({default:e.withCtx(()=>[e.renderSlot(t.$slots,"default")]),_:2},[t.$slots.prepend?{name:"prepend",fn:e.withCtx(()=>[e.renderSlot(t.$slots,"prepend")]),key:"0"}:void 0]),1040))});function ha(e){const[t,s]=e.localPageRange;return s-t+1}function ca(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function da(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ca(t)?t.segmentPageThreshold:null}function ua(e,t){return`${e}#s${t}`}function pa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ga(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ma(e){const t=da(e);if(!t)return null;const s=ha(e),r=ga(s,t),n=ca(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:ua(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function fa(e,t){const s=ma(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function va(e,t){const s=ma(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Pa(e){var t;const s=da(e);if(!s)return[];const r=[],{chapterId:n}=e,a=ha(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ca(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ga(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Ia={kind:"first-wins"};function Sa(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ba=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ca=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ia,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ia,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=pa(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=pa(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=pa(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?fa(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ma(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Pa(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Ia){const s=function(e,t=Ia){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Sa(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ba(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ma(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=va(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ca(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ma(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ma(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=va(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=va(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=fa(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ma(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ca(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=da(t);if(a){const r=ga(ha(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ca(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=pa(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ma(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ca.id="chapter-manager";let ya=Ca;function wa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ma(e,t){return`${e}#s${t}`}function xa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function La(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wa(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=wa(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Ma(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function $a(e){const[t,s]=e.localPageRange;return s-t+1}function ka(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Da(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ka(t)?t.segmentPageThreshold:null}function Ua(e,t){return`${e}#s${t}`}function Ea(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Va(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Aa(e){const t=Da(e);if(!t)return null;const s=$a(e),r=Va(s,t),n=ka(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Ua(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Ta(e,t){const s=Aa(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Na(e,t){const s=Aa(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Fa(e){var t;const s=Da(e);if(!s)return[];const r=[],{chapterId:n}=e,a=$a(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ka(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Va(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Oa={kind:"first-wins"};function Ra(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class za{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Ba=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Oa,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Oa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ea(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ea(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ea(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Ta(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Aa(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Fa(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Oa){const s=function(e,t=Oa){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ra(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new za(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Aa(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Na(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ka(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Aa(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Aa(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Na(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Na(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Ta(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Aa(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ka(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Da(t);if(a){const r=Va($a(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ka(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ea(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Aa(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ba.id="chapter-manager";let Ga=Ba;function _a(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const Wa=792/612;function qa(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function Ha(e){return 0===e.length?null:{width:qa(e.map(e=>e.width)),height:qa(e.map(e=>e.height))}}function Ka(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*Wa)}}function ja(e){const[t,s]=e.localPageRange;return s-t+1}function Xa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ya(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xa(t)?t.segmentPageThreshold:null}function Za(e,t){return`${e}#s${t}`}function Ja(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Qa(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ei(e){const t=Ya(e);if(!t)return null;const s=ja(e),r=Qa(s,t),n=Xa(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Za(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ti(e,t){const s=ei(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function si(e,t){const s=ei(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ri(e){var t;const s=Ya(e);if(!s)return[];const r=[],{chapterId:n}=e,a=ja(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Xa(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Qa(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,_a),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ga.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=La(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=xa(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=xa(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=Ha(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=Ha(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=Ha(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=Ka(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?Ka(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=La(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=xa(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}}).id="chapter-scroll";const ni={kind:"first-wins"};function ai(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ii=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const oi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ni,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ni,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ja(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ja(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ja(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?ti(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ei(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ri(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ni){const s=function(e,t=ni){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ai(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ii(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ei(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=si(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Xa(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ei(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ei(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=si(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=si(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=ti(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ei(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Xa(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ya(t);if(a){const r=Qa(ja(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Xa(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ja(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ei(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};oi.id="chapter-manager";let li=oi;function hi(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ci(e,t){return`${e}#s${t}`}function di(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ui(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return hi(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=hi(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ci(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function pi(e){const[t,s]=e.localPageRange;return s-t+1}function gi(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function mi(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return gi(t)?t.segmentPageThreshold:null}function fi(e,t){return`${e}#s${t}`}function vi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Pi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ii(e){const t=mi(e);if(!t)return null;const s=pi(e),r=Pi(s,t),n=gi(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:fi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Si(e,t){const s=Ii(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function bi(e,t){const s=Ii(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ci(e){var t;const s=mi(e);if(!s)return[];const r=[],{chapterId:n}=e,a=pi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!gi(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Pi(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const yi={kind:"first-wins"};function wi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Mi=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const xi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=yi,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??yi,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=vi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=vi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=vi(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Si(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ii(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ci(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=yi){const s=function(e,t=yi){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,wi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Mi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ii(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=bi(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(gi(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ii(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ii(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=bi(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=bi(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Si(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ii(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(gi(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=mi(t);if(a){const r=Pi(pi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(gi(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=vi(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ii(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};xi.id="chapter-manager";let Li=xi;function $i(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const ki=792/612;function Di(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function Ui(e){return 0===e.length?null:{width:Di(e.map(e=>e.width)),height:Di(e.map(e=>e.height))}}function Ei(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*ki)}}const Vi=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,$i),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Li.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=ui(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=di(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=di(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=Ui(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=Ui(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=Ui(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=Ei(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?Ei(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=ui(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=di(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Vi.id="chapter-scroll";let Ai=Vi;const Ti=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Ai.id),this.chapterManager=this.registry.getPlugin(li.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Fi(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};Ti.id="note";let Ni=Ti;function Fi(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Oi(e){const[t,s]=e.localPageRange;return s-t+1}function Ri(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function zi(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ri(t)?t.segmentPageThreshold:null}function Bi(e,t){return`${e}#s${t}`}function Gi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function _i(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Wi(e){const t=zi(e);if(!t)return null;const s=Oi(e),r=_i(s,t),n=Ri(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Bi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function qi(e,t){const s=Wi(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Hi(e,t){const s=Wi(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ki(e){var t;const s=zi(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Oi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ri(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=_i(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ji={kind:"first-wins"};function Xi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Yi=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Zi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ji,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ji,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Gi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Gi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Gi(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?qi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Wi(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ki(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ji){const s=function(e,t=ji){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Xi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Yi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Wi(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Hi(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ri(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Wi(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Wi(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=Hi(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=Hi(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=qi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Wi(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ri(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=zi(t);if(a){const r=_i(Oi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ri(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Gi(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Wi(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Zi.id="chapter-manager";let Ji=Zi;function Qi(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function eo(e,t){return`${e}#s${t}`}function to(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function so(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Qi(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Qi(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:eo(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ro(e){const[t,s]=e.localPageRange;return s-t+1}function no(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ao(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return no(t)?t.segmentPageThreshold:null}function io(e,t){return`${e}#s${t}`}function oo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function lo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ho(e){const t=ao(e);if(!t)return null;const s=ro(e),r=lo(s,t),n=no(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:io(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function co(e,t){const s=ho(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function uo(e,t){const s=ho(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function po(e){var t;const s=ao(e);if(!s)return[];const r=[],{chapterId:n}=e,a=ro(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!no(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=lo(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const go={kind:"first-wins"};function mo(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class fo{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const vo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=go,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??go,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=oo(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=oo(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=oo(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?co(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ho(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...po(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=go){const s=function(e,t=go){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,mo(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new fo(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ho(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=uo(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(no(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=ho(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=ho(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=uo(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=uo(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=co(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=ho(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(no(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ao(t);if(a){const r=lo(ro(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(no(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a))return c.closeDocument(o).wait(()=>{},()=>{}),"closed";this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=oo(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?ho(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};vo.id="chapter-manager";let Po=vo;function Io(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const So=792/612;function bo(e){if(0===e.length)return 0;const t=[...e].sort((e,t)=>e-t),s=Math.floor(t.length/2);return t.length%2==0?(t[s-1]+t[s])/2:t[s]}function Co(e){return 0===e.length?null:{width:bo(e.map(e=>e.width)),height:bo(e.map(e=>e.height))}}function yo(e,t){const s=e>0?e:612*Math.max(t,.1),r=Math.max(1,s);return{width:r,height:Math.max(1,r*So)}}const wo=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Io),this.visibleChange$=n.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.lastLoadIndicesKey="",this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0,this.suppressScrollLoadsUntil=0,this.inferredPlaceholder=null,this.chapterInferredPlaceholder=new Map,this.layoutScaleHint=1,this.pendingScaleHarvestChapterIds=new Set,this.scaleLayoutSyncRaf=null,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Po.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??0,placeholderPageWidth:e.placeholderPageWidth??0,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.layoutScaleHint=this.coreState.core.defaultScale??1,this.recomputeInferredPlaceholder(),this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.chapterInferredPlaceholder.clear(),this.inferredPlaceholder=null,this.lastLoadIndicesKey="",this.recomputeInferredPlaceholder(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=so(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(e=!1){if(!this.virtualPageMap||0===this.currentVisible.length)return;const t=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===t.length)return;const s=this.chapterManager.provides(),r=s.visibleRangeNeedsSegmentLoad(t),n=t.join(",");(e||n!==this.lastLoadIndicesKey||r)&&(this.lastLoadIndicesKey=n,s.setVisibleGlobalPages(t,e?{jump:!0}:void 0))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=to(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=to(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",null!=this.scaleLayoutSyncRaf&&(cancelAnimationFrame(this.scaleLayoutSyncRaf),this.scaleLayoutSyncRaf=null),this.pendingScaleHarvestChapterIds.clear(),this.chapterInferredPlaceholder.clear(),this.layoutChange$.clear(),this.visibleChange$.clear()}getEffectiveLayoutScale(){return this.layoutScaleHint>0?this.layoutScaleHint:1}getConfigPlaceholderOverride(){const e=this.config.placeholderPageWidth,t=this.config.placeholderPageHeight;return e>0&&t>0?{width:e,height:t}:null}recomputeInferredPlaceholder(){var e;const t=this.getConfigPlaceholderOverride();if(t){this.inferredPlaceholder=t,this.chapterInferredPlaceholder.clear();for(const[e]of this.groupLoadedSizesByChapter()){const t=Co(this.collectKnownSizesForChapter(e));t&&this.chapterInferredPlaceholder.set(e,t)}return}const s=[];this.chapterInferredPlaceholder.clear();for(const[a]of this.groupLoadedSizesByChapter()){const e=this.collectKnownSizesForChapter(a),t=Co(e);t&&(this.chapterInferredPlaceholder.set(a,t),s.push(...e))}const r=Co(s);if(r)return void(this.inferredPlaceholder=r);const n=(null==(e=this.viewportEl)?void 0:e.clientWidth)??0;this.inferredPlaceholder=yo(n,this.getEffectiveLayoutScale())}groupLoadedSizesByChapter(){const e=new Map;if(!this.virtualPageMap)return e;for(const[t,s]of this.pageSizes){const r=this.virtualPageMap.atIndex(t);if(!r)continue;const n=e.get(r.chapterId);n?n.push(s):e.set(r.chapterId,[s])}return e}collectKnownSizesForChapter(e){if(!this.virtualPageMap)return[];const t=[];for(const s of this.virtualPageMap.pagesOfChapter(e)){const e=this.pageSizes.get(s.globalPageIndex);e&&t.push(e)}return t}getPlaceholderSize(e){var t,s;const r=this.getConfigPlaceholderOverride();if(r)return r;const n=null==(t=this.virtualPageMap)?void 0:t.atIndex(e);if(n){const e=this.chapterInferredPlaceholder.get(n.chapterId);if(e)return e}if(this.inferredPlaceholder)return this.inferredPlaceholder;const a=(null==(s=this.viewportEl)?void 0:s.clientWidth)??0;return a>0?yo(a,this.getEffectiveLayoutScale()):function(e){const t=Math.max(e,.1);return{width:612*t,height:792*t}}(this.getEffectiveLayoutScale())}getPageSize(e){return this.pageSizes.get(e)??this.getPlaceholderSize(e)}applyLayoutChangeWithScrollCompensation(){const e=this.scrollAnchorIndex??this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible(),null!=this.scrollAnchorIndex&&this.alignScrollToAnchor()}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}mergeChapterPageSizes(e,t){if(!this.virtualPageMap)return!1;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}return s}applyChapterPageSizes(e,t){var s;if(this.mergeChapterPageSizes(e,t)&&(this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation(),null!=this.scrollAnchorIndex)){const t=null==(s=this.virtualPageMap)?void 0:s.atIndex(this.scrollAnchorIndex);(null==t?void 0:t.chapterId)===e&&this.pageSizes.has(this.scrollAnchorIndex)&&(this.scrollAnchorIndex=null,this.scrollAnchorTopOffset=0)}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}collectChapterSizes(e){if(!this.virtualPageMap)return[];const t=this.chapterManager.provides(),s=t.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!s||0===r.length)return[];const n=so(s),a=this.documentManager.provides(),i=[],o=(e,t,s,r)=>{var n;const o=a.getDocument(e);if(!(null==(n=null==o?void 0:o.pages)?void 0:n.length))return;const l=this.getDocumentScale(e);for(let a=0;a<r;a++){const e=o.pages[s+a];(null==e?void 0:e.size)&&i.push({localPageIndex:t+a,width:e.size.width*l,height:e.size.height*l})}};if(n)for(const l of n.segments){if(!t.isSegmentLoaded(e,l.index))continue;const s=l.localPageEnd-l.localPageStart+1;o(l.documentId,l.localPageStart,0,s)}else t.isSegmentLoaded(e,0)&&o(e,0,0,r.length);return i}harvestChapterSizes(e,t=0){const s=this.collectChapterSizes(e);0!==s.length?this.applyChapterPageSizes(e,s):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e,t){const s=this.coreState.core.documents[e];if(!s||"loaded"!==s.status)return;const{chapterId:r}=to(e);this.chapterManager.provides().getChapter(r)&&(t>0&&(this.layoutScaleHint=t),this.pendingScaleHarvestChapterIds.add(r),this.scheduleScaleLayoutSync())}scheduleScaleLayoutSync(){null==this.scaleLayoutSyncRaf&&(this.scaleLayoutSyncRaf=requestAnimationFrame(()=>{this.scaleLayoutSyncRaf=null,this.flushScaleLayoutSync()}))}flushScaleLayoutSync(){const e=[...this.pendingScaleHarvestChapterIds];this.pendingScaleHarvestChapterIds.clear();let t=!1;for(const n of e){const e=this.collectChapterSizes(n);e.length>0&&(t=this.mergeChapterPageSizes(n,e)||t)}const s=this.inferredPlaceholder;this.recomputeInferredPlaceholder();const r=!(!s||!this.inferredPlaceholder||s.width===this.inferredPlaceholder.width&&s.height===this.inferredPlaceholder.height);(t||r||0===this.pageSizes.size)&&this.applyLayoutChangeWithScrollCompensation()}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.chapterInferredPlaceholder.delete(e),this.recomputeInferredPlaceholder(),this.applyLayoutChangeWithScrollCompensation())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.onViewportScroll(),r=new ResizeObserver(()=>{const e=this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"";this.recomputeInferredPlaceholder(),e!==(this.inferredPlaceholder?`${this.inferredPlaceholder.width}:${this.inferredPlaceholder.height}`:"")?this.applyLayoutChangeWithScrollCompensation():this.recomputeVisible()});e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(e){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 s=this.viewportEl.scrollTop,r=s+this.viewportEl.clientHeight,n=this.findFirstVisibleIndex(s);let a=n;for(;a<t;){const e=this.getPageSize(a);if(e.height<=0)break;const t=this.offsets[a];if(e.height,t>=r)break;a++}const i=[];let o=n,l=-1;for(let h=n;h<a;h++){i.push(h);const e=this.offsets[h],t=e+this.getPageSize(h).height,n=Math.max(0,Math.min(t,r)-Math.max(e,s));n>l&&(l=n,o=h)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.pushVisibleLoads((null==e?void 0:e.jump)??!1),this.layoutChange$.emit(this.computeLayout())}onViewportScroll(){performance.now()<this.suppressScrollLoadsUntil||this.recomputeVisible()}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.getPlaceholderSize(0).width,items:n,pageGap:this.config.pageGap}}firstIndexOfChapterOrDescendant(e){if(!this.virtualPageMap)return-1;const t=this.virtualPageMap.firstIndexOfChapter(e);if(t>=0)return t;const s=this.chapterManager.provides().getManifest().chapters,r=s.findIndex(t=>t.chapterId===e);if(r<0)return-1;for(let n=r+1;n<s.length;n++){const e=this.virtualPageMap.firstIndexOfChapter(s[n].chapterId);if(e>=0)return e}return-1}alignScrollToAnchor(){if(null==this.scrollAnchorIndex||!this.viewportEl)return;const e=this.scrollAnchorIndex;if(e<0||e>=this.offsets.length)return;const t=Math.max(0,(this.offsets[e]??0)-this.scrollAnchorTopOffset);Math.abs(this.viewportEl.scrollTop-t)>1&&(this.viewportEl.scrollTop=t),this.recomputeVisible()}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(null==t?void 0:t.topOffset)??0;this.scrollAnchorIndex=e,this.scrollAnchorTopOffset=s,this.currentGlobalPageIndex=e,this.suppressScrollLoadsUntil=performance.now()+400;const r=Math.max(0,(this.offsets[e]??0)-s);this.viewportEl.scrollTo({top:r,behavior:"auto"}),this.recomputeVisible({jump:!0}),this.lastLoadIndicesKey="",requestAnimationFrame(()=>{this.scrollAnchorIndex===e&&this.alignScrollToAnchor()})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,c=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,c),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.firstIndexOfChapterOrDescendant(e);s<0||this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};wo.id="chapter-scroll";let Mo=wo;function xo(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Lo(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function $o(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??xo(n),o=t.markerAnchor??xo(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(Lo(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}const ko=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Mo.id),this.chapterManager=this.registry.getPlugin(Ji.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if($o(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};ko.id="paragraph-bookmark";let Do=ko;function Uo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Eo(e,t){return`${e}#s${t}`}function Vo(e,t){const s=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Uo(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Uo(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Eo(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ao(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,function(){const e=Ao(void 0,{enabled:!0}),t=Ao(void 0,{enabled:!0}),s=Ao(void 0,{enabled:!0}),r=Ao(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=Ao(!1!==e.enabled||!1!==s.enabled,{enabled:!0});null==void 0||(void 0).background}();const To="embedpdf-chapter-copy-toast";function No(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Fo(e){return{bookmarks:!1!==(null==e?void 0:e.bookmarks),notes:!1!==(null==e?void 0:e.notes),markup:!1!==(null==e?void 0:e.markup)}}function Oo(e){return new Promise((t,s)=>{e.wait(e=>t(e),e=>s(e))})}function Ro(e){var t,r,n,a;return{annotation:null==(t=e.getPlugin(s.AnnotationPlugin.id))?void 0:t.provides(),note:null==(r=e.getPlugin(Ni.id))?void 0:r.provides(),bookmark:null==(n=e.getPlugin(Do.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(ya.id))?void 0:a.provides()}}async function zo(e,t,s){if(!s||!e)return;const r=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==r)throw new Error(`章节 ${t} 未加载成功(${r}),无法导入/导出划线`)}async function Bo(e,t,s){const r=Fo(s),{annotation:n,note:a,bookmark:i,chapterManager:o}=Ro(e),l={chapterId:t};if(r.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=i.listBookmarksForChapter(t)}if(r.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(r.markup){if(!n)throw new Error("annotation 插件未注册");await zo(o,t,!1!==(null==s?void 0:s.ensureChapterLoaded));const e=await async function(e,t,s){const r=t.getSegmentPlan(s);if(!r)return Oo(e.forDocument(s).exportAnnotations());const n=[];for(const a of r.segments){if(!t.isSegmentLoaded(s,a.index))continue;const r=await Oo(e.forDocument(a.documentId).exportAnnotations());for(const e of r){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,o,t);l.markup=function(e){return e.map(e=>{if(!(e.ctx&&"data"in e.ctx&&e.ctx.data instanceof ArrayBuffer))return{annotation:e.annotation};const t=e.ctx;return{annotation:e.annotation,ctx:{dataBase64:No(t.data),mimeType:t.mimeType}}})}(e)}return l}async function Go(e,t,s){const r=Fo(s),n=(null==s?void 0:s.mode)??"replace",{annotation:a,note:i,bookmark:o,chapterManager:l}=Ro(e),h=t.chapterId;if(r.bookmarks&&t.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)o.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)o.addBookmark(e)}if(r.notes&&t.notes){if(!i)throw new Error("note 插件未注册");if("replace"===n)i.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)i.registerNote(e)}if(r.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await zo(l,h,!1!==(null==s?void 0:s.ensureChapterLoaded)),function(e,t,s,r,n){const a=t.getSegmentPlan(s);if(!a){const t=e.forDocument(s);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(r)}const i=t.getChapter(s);if(!i)return;const o=new Map;for(const l of r){const e=l.annotation.pageIndex,t=Vo(i,e),s=a.segments[t];if(!s)continue;const r=o.get(t)??[];r.push({...l,annotation:{...l.annotation,pageIndex:e-s.localPageStart}}),o.set(t,r)}for(const l of a.segments){const t=e.forDocument(l.documentId),s=o.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),s.length>0&&t.importAnnotations(s)}}(a,l,h,function(e){return e.map(e=>{var t;if(!(null==(t=e.ctx)?void 0:t.dataBase64))return{annotation:e.annotation};const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:s,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==s?void 0:s.persistNotes)&&i&&await s.persistNotes(i.listAllNotes()),(null==s?void 0:s.persistBookmarks)&&o&&await s.persistBookmarks(o.listBookmarks())}function _o(e){return JSON.stringify(e,null,2)}function Wo(e){return JSON.stringify(e,null,2)}function qo(e,t){const s=new Blob([t],{type:"application/json;charset=utf-8"}),r=URL.createObjectURL(s),n=document.createElement("a");n.href=r,n.download=e,n.click(),URL.revokeObjectURL(r)}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT;function Ho(e){const[t,s]=e.localPageRange;return s-t+1}function Ko(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function jo(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ko(t)?t.segmentPageThreshold:null}function Xo(e,t){return`${e}#s${t}`}function Yo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Zo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Jo(e){const t=jo(e);if(!t)return null;const s=Ho(e),r=Zo(s,t),n=Ko(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Xo(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Qo(e,t){const s=Jo(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function el(e,t){const s=Jo(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function tl(e){var t;const s=jo(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ho(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ko(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Zo(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const sl={kind:"first-wins"};function rl(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class nl{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}function al(e,t=sl){const s=function(e,t=sl){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,rl(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new nl(a)}const il=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=sl,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.visibleChapterIds=new Set,this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??sl,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Yo(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Yo(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Yo(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:(e,t)=>this.handleVisibleChange(e,t),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Qo(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Jo(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...tl(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=al(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Jo(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!!s&&(!!this.pendingSegmentLoadPromises.has(s)||!(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=el(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&("error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e))}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!Ko(s)&&((!s||!("url"in s||"buffer"in s||"load"in s))&&!!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||(!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1))}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Jo(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);if(i)return i.globalPageIndex;return 1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.isChapterVisibleForLoad(e.chapterId))continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}unloadChaptersOutside(e){for(const t of this.manifest.chapters){const{chapterId:s}=t;e.has(s)||this.anySegmentOpen(s)&&this.closeChapter(s)}}isChapterVisibleForLoad(e){return this.visibleChapterIds.has(e)}handleVisibleChange(e,t){if(!this.virtualPageMap||0===e.length)return;const s=new Set;for(const d of e){const e=this.virtualPageMap.atIndex(d);e&&s.add(e.chapterId)}this.visibleChapterIds=s,(null==t?void 0:t.jump)&&(this.clearVisibleSegmentBacklog(),this.unloadChaptersOutside(s),this.lastVisibleIndicesKey="");const r=e.join(","),n=this.visibleRangeNeedsSegmentLoad(e);if(r===this.lastVisibleIndicesKey&&!n)return;this.lastVisibleIndicesKey=r;const a=Date.now(),i=e[Math.floor(e.length/2)]??e[0],o=new Map,l=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Jo(s);if(r&&t>=r.segments.length)return;const n=`${e}:${t}`,a=this.segmentStartGlobalIndex(e,t),l=Math.abs(a-i),h=o.get(n);(void 0===h||l<h)&&o.set(n,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;const t=this.findChapter(e.chapterId);if(!t)continue;const s=el(t,e.localPageIndex);l(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===s.size)return;const h=this.virtualPageMap.atIndex(i);for(const d of s)this.chapterLastUsed.set(d,a);const c=[...o.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(c),h){const e=this.findChapter(h.chapterId);if(e){const t=el(e,h.localPageIndex);this.isSegmentDocumentOpen(h.chapterId,t)||(this.prepareChapterForSegmentLoad(h.chapterId),this.loadSegmentNow(h.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(i);if(e){const t=Qo(this.findChapter(e.chapterId),e.localPageIndex);if(this.documentManager.provides().isDocumentOpen(t.documentId)){this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus){if("loaded"!==r)continue;t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Jo(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ko(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=jo(t);if(a){const r=Zo(Ho(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ko(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),c=this.documentManager.provides(),d="url"in h?c.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):c.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});if(await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),c.isDocumentOpen(o)){if(!this.isChapterVisibleForLoad(a)){return c.closeDocument(o).wait(()=>{},()=>{}),"closed"}this.syncChapterStatusFromDocuments(a)}return this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Yo(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}if(!l)return void this.updateStatus(s,"password-required");this.updateStatus(s,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Jo(t):null,n=e=>{if(s.isDocumentOpen(e)){s.closeDocument(e).wait(()=>{},()=>{})}};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};il.id="chapter-manager";let ol=il;function ll(e){const t=e.endPage-e.startPage+1;return{chapterId:e.chapterId,title:e.title,globalPageRange:[e.startPage,e.endPage],localPageRange:[0,t-1],...e.source?{source:e.source}:{},...null!=e.segmentPageThreshold?{segmentPageThreshold:e.segmentPageThreshold}:{},...e.encrypted?{encrypted:e.encrypted}:{}}}function hl(e){const t=[],s=e=>{var r;for(const n of e)t.push(ll(n)),(null==(r=n.children)?void 0:r.length)&&s(n.children)};return s(e),t}function cl(e){return e.map(e=>{var t;return{id:e.chapterId,title:e.title,startPage:e.startPage,endPage:e.endPage,children:(null==(t=e.children)?void 0:t.length)?cl(e.children):void 0}})}Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>t.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>t.useCapability}),Object.defineProperty(exports,"useRegistry",{enumerable:!0,get:()=>t.useRegistry}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>w.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=z,exports.ChapterManagerPlugin=ol,exports.ChapterPdfViewer=la,exports.ChapterTreePanel=oa,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Ds,exports.PdfChapterViewport=Kn,exports.applySelectionMarkup=V,exports.buildChapterViewerCatalog=function(e){return{tree:cl(e),manifest:{chapters:hl(e)}}},exports.buildParagraphBookmarkAnchor=Ss,exports.chapterAnnotationsArchiveToJson=_o,exports.chapterAnnotationsSnapshotToJson=Wo,exports.chapterDescriptorFromTreeNode=ll,exports.copyTextToClipboard=async function(e,t){var s;const r=e.trim();if(!r)return!1;const n=()=>{!1!==(null==t?void 0:t.toastMessage)&&function(e="已复制"){var t;if("undefined"==typeof document)return;null==(t=document.getElementById(To))||t.remove();const s=document.createElement("div");s.id=To,s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),s.textContent=e,Object.assign(s.style,{position:"fixed",left:"50%",bottom:"48px",transform:"translateX(-50%)",padding:"10px 18px",borderRadius:"8px",background:"rgba(15, 23, 42, 0.88)",color:"#fff",fontSize:"13px",lineHeight:"1.4",fontFamily:"system-ui, -apple-system, sans-serif",zIndex:"99999",pointerEvents:"none",boxShadow:"0 4px 16px rgba(15, 23, 42, 0.2)",opacity:"0",transition:"opacity 200ms ease"}),document.body.appendChild(s),requestAnimationFrame(()=>{s.style.opacity="1"}),window.setTimeout(()=>{s.style.opacity="0",window.setTimeout(()=>s.remove(),200)},1800)}((null==t?void 0:t.toastMessage)??"已复制")};try{if("undefined"!=typeof navigator&&(null==(s=navigator.clipboard)?void 0:s.writeText))return await navigator.clipboard.writeText(r),n(),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=r,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t&&n(),t}catch{return!1}},exports.createChapterViewerBundle=Ts,exports.createChapterViewerEditor=Us,exports.createChapterViewerEditorOptions=function(e){const{features:t,...s}=As(Vs(e));return s},exports.createPdfChapterEditor=$s,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){qo(t,_o(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){qo(t??`chapter-annotations-${e.chapterId}.json`,Wo(e))},exports.downloadJsonFile=qo,exports.exportAllChapterAnnotations=async function(e,t,s){const r={};for(const n of t.chapters){const t=await Bo(e,n.chapterId,s),{chapterId:a,...i}=t;r[n.chapterId]=i}return{version:1,exportedAt:(new Date).toISOString(),chapters:r}},exports.exportChapterAnnotations=Bo,exports.flattenChapterTree=hl,exports.importChapterAnnotations=Go,exports.importChapterAnnotationsArchive=async function(e,t,s){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[r,n]of Object.entries(t.chapters))await Go(e,{chapterId:r,...n},s)},exports.overlapStrategyForSamePageOwner=function(e){return"last"===e?{kind:"last-wins"}:{kind:"first-wins"}},exports.parseChapterAnnotationsArchiveJson=function(e){const t=JSON.parse(e);if(!t||"object"!=typeof t||!t.chapters)throw new Error("无效的章节标注 JSON");return t},exports.parseChapterAnnotationsSnapshotJson=function(e){const t=JSON.parse(e);if(!(null==t?void 0:t.chapterId))throw new Error("无效的章节标注 JSON:缺少 chapterId");return t},exports.toChapterTreeNodes=cl;
2
2
  //# sourceMappingURL=index.cjs.map