@embedpdf-editor/vue3-chapter-viewer 1.0.2 → 1.0.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/README.md +29 -51
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +57 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5937 -4757
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
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"),a=require("@embedpdf/models"),r=require("@embedpdf/core"),n=require("@embedpdf/plugin-document-manager"),o=require("@embedpdf/plugin-interaction-manager"),i=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),d=require("@embedpdf/plugin-selection"),h=require("@embedpdf/plugin-history"),c=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"),b=require("@embedpdf/plugin-selection/vue"),C=require("@embedpdf/plugin-annotation/vue"),S=require("@embedpdf/plugin-redaction/vue"),w=require("@embedpdf/plugin-render/vue"),y=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",D={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},k={highlight:a.PdfAnnotationSubtype.HIGHLIGHT,underline:a.PdfAnnotationSubtype.UNDERLINE,squiggly:a.PdfAnnotationSubtype.SQUIGGLY,strikeout:a.PdfAnnotationSubtype.STRIKEOUT};function T(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,a=-1/0,r=-1/0;for(const n of e)t=Math.min(t,n.origin.x),s=Math.min(s,n.origin.y),a=Math.max(a,n.origin.x+n.size.width),r=Math.max(r,n.origin.y+n.size.height);return{origin:{x:t,y:s},size:{width:a-t,height:r-s}}}function O(e,t,r,n,o){const i=r.forDocument(e),l=n.forDocument(e);if(!i||!l)return!1;const d="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",h=r.getTool(d);if(!h)return!1;const c=h.defaults,u={...D[g=t],...null==(m=o)?void 0:m[g]},p=l.getFormattedSelection();var g,m;if(0===p.length)return!1;i.setLocked({type:s.LockModeType.Exclude,categories:["markup","shape"]});for(const s of p){const e=a.uuidV4(),r=u.color??c.color??c.strokeColor,n=u.opacity??c.opacity,o=u.thickness??c.strokeWidth,l=u.offsetY??0,d="underline"===t||"squiggly"===t||"strikeout"===t?T(s.segmentRects,l):s.segmentRects,h="underline"===t||"squiggly"===t||"strikeout"===t?E(d):s.rect;i.createAnnotation(s.pageIndex,{id:e,created:new Date,flags:["print"],type:k[t],..."highlight"===t?{blendMode:a.PdfBlendMode.Multiply}:{},strokeColor:r,opacity:n,...null!=o?{strokeWidth:o}:{},pageIndex:s.pageIndex,rect:h,segmentRects:d})}return l.clear(),!0}const N=new Set([a.PdfAnnotationSubtype.HIGHLIGHT,a.PdfAnnotationSubtype.UNDERLINE,a.PdfAnnotationSubtype.SQUIGGLY,a.PdfAnnotationSubtype.STRIKEOUT]);function A(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 z(e){var t;const s=A(null==e?void 0:e.markup,{enabled:!0}),a=A(null==e?void 0:e.bookmarks,{enabled:!0}),r=A(null==e?void 0:e.notes,{enabled:!0}),n=A(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),o=A(void 0===(null==e?void 0:e.selectionToolbar)?!1!==s.enabled||!1!==r.enabled:e.selectionToolbar,{enabled:!0});return{markup:s,bookmarks:a,notes:r,zoom:n,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??$},selectionToolbar:o}}function F(e,t){return`${e}#s${t}`}function G(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:F(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}let V=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const R="chapter-manager",_={id:R,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function B(e){const[t,s]=e.localPageRange;return s-t+1}function U(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function q(e,t){return`${e}#s${t}`}function H(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function W(e){const t=e.source;if(!U(t))return null;const s=t.segmentPageThreshold,a=B(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:q(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function j(e,t){const s=W(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Z(e,t){const s=W(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Y(e){var t;const s=e.source;if(!U(s))return[];const a=[],{chapterId:r}=e,n=B(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const J={kind:"first-wins"};function K(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 X=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 Q=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=J,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??J,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=H(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=H(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=H(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=>this.handleVisibleChange(e),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?j(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?W(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Y(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=J){const s=function(e,t=J){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,K(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new X(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?W(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Z(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=j(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=W(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(U(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=H(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?W(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Q.id="chapter-manager";let ee=Q;const te={manifest:_,create:e=>new ee(R,e),reducer:e=>e,initialState:{}},se="chapter-scroll",ae={id:se,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}};function re(e,t){return`${e}#s${t}`}function ne(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function oe(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:re(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function ie(e){const[t,s]=e.localPageRange;return s-t+1}function le(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function de(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),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function ce(e){const t=e.source;if(!le(t))return null;const s=t.segmentPageThreshold,a=ie(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:de(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function ue(e,t){const s=ce(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function pe(e,t){const s=ce(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function ge(e){var t;const s=e.source;if(!le(s))return[];const a=[],{chapterId:r}=e,n=ie(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const me={kind:"first-wins"};function fe(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 ve=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 Pe=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=me,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??me,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=he(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=he(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=he(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=>this.handleVisibleChange(e),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?ue(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ce(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ge(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=me){const s=function(e,t=me){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,fe(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new ve(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ce(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=pe(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=ue(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=ce(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(le(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=he(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?ce(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Pe.id="chapter-manager";let Ie=Pe;function be(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const Ce=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,be),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ie.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=oe(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=ne(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=ne(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=oe(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=ne(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(s,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Ce.id="chapter-scroll";let Se=Ce;const we={manifest:ae,create:e=>new Se(se,e),reducer:e=>e,initialState:{}},ye="note",Me={id:ye,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 xe(e){const[t,s]=e.localPageRange;return s-t+1}function Le(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $e(e,t){return`${e}#s${t}`}function De(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function ke(e){const t=e.source;if(!Le(t))return null;const s=t.segmentPageThreshold,a=xe(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:$e(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Te(e,t){const s=ke(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Ee(e,t){const s=ke(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Oe(e){var t;const s=e.source;if(!Le(s))return[];const a=[],{chapterId:r}=e,n=xe(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Ne={kind:"first-wins"};function Ae(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 ze=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 Fe=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Ne,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ne,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=De(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=De(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=De(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=>this.handleVisibleChange(e),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?Te(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ke(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Oe(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Ne){const s=function(e,t=Ne){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Ae(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new ze(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ke(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ee(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Te(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=ke(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Le(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=De(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?ke(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Fe.id="chapter-manager";let Ge=Fe;function Ve(e,t){return`${e}#s${t}`}function Re(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function _e(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:Ve(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function Be(e){const[t,s]=e.localPageRange;return s-t+1}function Ue(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function qe(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),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function We(e){const t=e.source;if(!Ue(t))return null;const s=t.segmentPageThreshold,a=Be(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:qe(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function je(e,t){const s=We(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Ze(e,t){const s=We(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Ye(e){var t;const s=e.source;if(!Ue(s))return[];const a=[],{chapterId:r}=e,n=Be(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Je={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 Xe=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 Qe=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Je,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Je,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=He(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=He(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=He(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=>this.handleVisibleChange(e),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?je(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?We(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ye(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Je){const s=function(e,t=Je){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Ke(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new Xe(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?We(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ze(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=je(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=We(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Ue(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=He(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?We(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Qe.id="chapter-manager";let et=Qe;function tt(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const st=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,tt),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(et.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=_e(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=Re(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=Re(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=_e(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Re(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(s,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};st.id="chapter-scroll";let at=st;const rt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(at.id),this.chapterManager=this.registry.getPlugin(Ge.id),this.documentManager=this.registry.getPlugin(n.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 a=this.notes.get(e);a&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,a),this.noteActivated$.emit({noteId:e,anchor:a}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,a]of this.notes.entries())a.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:ot(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:a}=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),a=this.config.callbacks.onCreateNote;if(!a)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await a(s)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const n={...s,noteId:r.noteId};return this.registerNote(n),n}async deleteNote(t){var s,a;if(this.notes.has(t)){try{await(null==(a=(s=this.config.callbacks).onDeleteNote)?void 0:a.call(s,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var a,r;const n=this.notes.get(t);if(!n)return;const o={...n,content:s};try{await(null==(r=(a=this.config.callbacks).onUpdateNote)?void 0:r.call(a,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const a=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(s.chapterId);const n=r.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(n.documentId))?void 0:t.pages[n.pageIndex])?(a.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),a.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):a.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 a=setTimeout(()=>{r(),s(null)},2500),r=t.onLayoutChange(t=>{const n=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);n&&(clearTimeout(a),r(),s(n))})})}};rt.id="note";let nt=rt;function ot(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const it={manifest:Me,create:e=>new nt(ye,e),reducer:e=>e,initialState:{}},lt="paragraph-bookmark",dt={id:lt,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function ht(e){const[t,s]=e.localPageRange;return s-t+1}function ct(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ut(e,t){return`${e}#s${t}`}function pt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function gt(e){const t=e.source;if(!ct(t))return null;const s=t.segmentPageThreshold,a=ht(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:ut(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function mt(e,t){const s=gt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function ft(e,t){const s=gt(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function vt(e){var t;const s=e.source;if(!ct(s))return[];const a=[],{chapterId:r}=e,n=ht(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Pt={kind:"first-wins"};function It(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 Ct=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Pt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Pt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=pt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=pt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=pt(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=>this.handleVisibleChange(e),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?mt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?gt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...vt(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Pt){const s=function(e,t=Pt){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,It(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new bt(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?gt(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=ft(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=mt(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=gt(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(ct(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=pt(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?gt(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ct.id="chapter-manager";let St=Ct;function wt(e,t){return`${e}#s${t}`}function yt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Mt(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:wt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function xt(e){const[t,s]=e.localPageRange;return s-t+1}function Lt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $t(e,t){return`${e}#s${t}`}function Dt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function kt(e){const t=e.source;if(!Lt(t))return null;const s=t.segmentPageThreshold,a=xt(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:$t(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Tt(e,t){const s=kt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Et(e,t){const s=kt(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Ot(e){var t;const s=e.source;if(!Lt(s))return[];const a=[],{chapterId:r}=e,n=xt(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Nt={kind:"first-wins"};function At(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 zt=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 Ft=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Nt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Nt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Dt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Dt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Dt(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=>this.handleVisibleChange(e),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?Tt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?kt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ot(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Nt){const s=function(e,t=Nt){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,At(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new zt(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?kt(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Et(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Tt(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=kt(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Lt(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=Dt(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?kt(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ft.id="chapter-manager";let Gt=Ft;function Vt(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const Rt=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Vt),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Gt.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Mt(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=yt(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=yt(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=Mt(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=yt(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(s,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Rt.id="chapter-scroll";let _t=Rt;function Bt(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,s=1/0,a=-1/0,r=-1/0;for(const n of e)t=Math.min(t,n.origin.x),s=Math.min(s,n.origin.y),a=Math.max(a,n.origin.x+n.size.width),r=Math.max(r,n.origin.y+n.size.height);return{origin:{x:t,y:s},size:{width:a-t,height:r-s}}}function Ut(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function qt(e,t){const s=e.origin.y,a=e.origin.y+e.size.height,r=t.origin.y,n=t.origin.y+t.size.height,o=Math.max(a,n)-Math.min(s,r);return o<=0?0:Math.max(0,Math.min(a,n)-Math.max(s,r))/o}function Ht(e,t){var s,a;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],n=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??Ut(r),i=t.markerAnchor??Ut(n);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of r)for(const e of n){if(qt(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 Wt(e,t,s,a){const r=s.length>0?s:[];if(0===r.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==a?void 0:a.globalPageIndex,globalPageNumber:null==a?void 0:a.globalPageNumber,rectPdfCoord:Bt(r),rectsPdfCoord:r,markerAnchor:Ut(r)}}const jt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(_t.id),this.chapterManager=this.registry.getPlugin(St.id),this.documentManager=this.registry.getPlugin(n.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(a){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",a)}}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 a of this.entries.values())if(Ht(a.anchor,e.anchor))return a;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,a;this.entries.delete(e)&&(this.notifyAndPersist(),null==(a=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||a.call(s,e))}async requestRemoveBookmark(t){var s,a;const r=this.entries.get(t);if(!r)return!1;const n=null==(a=null==(s=this.config)?void 0:s.callbacks)?void 0:a.onRequestRemove;if(n)try{if(!(await n(r)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!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,a]of this.entries.entries())a.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 a=this.list();this.change$.emit(a),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(a)).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(),a=this.chapterManager.provides();await a.ensureAllSegmentsLoaded(t.anchor.chapterId);let r=t.anchor.globalPageIndex;if(void 0===r){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;r=e.globalPageIndex}const n=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 a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const r=setTimeout(()=>{n(),a(null)},s),n=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(r),n(),a(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,r,n)}};jt.id="paragraph-bookmark";let Zt=jt;const Yt={manifest:dt,create:e=>new Zt(lt,e),reducer:e=>e,initialState:{}},Jt={"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 Kt{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(Jt);for(const t of this.specs){const s=e[t.toolbarSlot];if(!s)continue;const a={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=Xt(s.items,a,t.position)}return e}}function Xt(e,t,s){return(null==s?void 0:s.after)||(null==s?void 0:s.before)?function(e,t,s){const a=e=>{const r=[];for(const n of e)"group"!==n.type?s.before&&n.id===s.before?r.push(t,n):(r.push(n),s.after&&n.id===s.after&&r.push(t)):r.push({...n,items:a(n.items)});return r};return a(e)}(e,t,s):(a=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,a]}:e));var a}const Qt={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function es(e){var t,a,P,I,b,C;const S=e.toolbar??{},w=S.enabledModes??["view","annotate","shapes","insert","form","redact"],y=w.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,s,a,r,n,o;const i=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new Kt;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const d=l.buildToolbars(),h={};for(const u of i){if("view"===u)continue;const e=Qt[u];d[e]&&(h[e]=d[e])}const c=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}]}}(i);return c&&(h["chapter-editor-main-toolbar"]=c),(null==(s=e.extend)?void 0:s.toolbars)&&Object.assign(h,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:h,menus:(null==(a=e.extend)?void 0:a.menus)??{},sidebars:(null==(r=e.extend)?void 0:r.sidebars)??{},modals:(null==(n=e.extend)?void 0:n.modals)??{},selectionMenus:(null==(o=e.extend)?void 0:o.selectionMenus)??{}},operationRegistry:l}}({...S,enabledModes:w}),L={...y?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var a,r,n,o;const i=null==(a=e.getPlugin("ui"))?void 0:a.provides(),l=null==(r=e.getPlugin("interaction-manager"))?void 0:r.provides();i&&l&&(null==(n=l.forDocument(t))||n.activateDefaultMode(),i.forDocument(t).closeToolbarSlot("top","secondary"),null==(o=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||o.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 a,r;const n=null==(a=e.getPlugin("ui"))?void 0:a.provides();n&&(n.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(r=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||r.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 a,r;const n=null==(a=e.getPlugin("ui"))?void 0:a.provides();n&&(n.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(r=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||r.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 a,r;const n=null==(a=e.getPlugin("ui"))?void 0:a.provides();n&&(n.setActiveToolbar("top","secondary","insert-toolbar",t),null==(r=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||r.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 a,r;const n=null==(a=e.getPlugin("ui"))?void 0:a.provides();n&&(n.setActiveToolbar("top","secondary","form-toolbar",t),null==(r=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||r.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 a,r;const n=null==(a=e.getPlugin("ui"))?void 0:a.provides();n&&(n.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(r=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...y?ts(x.list()):{},...e.commands??{}},$=[r.createPluginRegistration(n.DocumentManagerPluginPackage,{initialDocuments:[]}),r.createPluginRegistration(te,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),r.createPluginRegistration(we,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),r.createPluginRegistration(o.InteractionManagerPluginPackage),r.createPluginRegistration(i.RenderPluginPackage),r.createPluginRegistration(l.RotatePluginPackage),r.createPluginRegistration(d.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),r.createPluginRegistration(h.HistoryPluginPackage),r.createPluginRegistration(s.AnnotationPluginPackage),r.createPluginRegistration(c.RedactionPluginPackage),r.createPluginRegistration(u.FormPluginPackage),r.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),r.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(L).length>0?[r.createPluginRegistration(m.CommandsPluginPackage,{commands:L})]:[],...y?[r.createPluginRegistration(f.I18nPluginPackage),r.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&$.push(r.createPluginRegistration(it,{callbacks:e.notes.callbacks,ui:null==(a=null==(t=e.features)?void 0:t.notes)?void 0:a.marker})),e.bookmarks&&$.push(r.createPluginRegistration(Yt,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(C=null==(b=e.features)?void 0:b.bookmarks)?void 0:C.hover})),{plugins:$,uiSchema:M,operationRegistry:x}}function ts(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 ss=z();function as(e){return es({...e,toolbar:e.toolbar??{enabledModes:[]},features:z(e.features)})}const rs={overlapStrategy:{kind:"first-wins"},passwordProvider:new V(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function ns(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function os(e){return{...rs,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??rs.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:z(e.features)}}function is(e){const t=os(ns(e)),{plugins:s}=as(t);return{plugins:s,features:t.features,editorOptions:t}}function ls(e,t=.5,s=3){return Math.min(s,Math.max(t,e))}function ds(e,t){var s;if(t<=0)return 1;let a=0;for(const r of e.pages){const e=(null==(s=null==r?void 0:r.size)?void 0:s.width)??0;e>a&&(a=e)}return a<=0?1:t/a}function hs(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function cs(e,t,s,a){const r=hs(t,s);if(r<=0)return a;const n=ds(e,r);return Math.min(a,n)}function us(e,t,s){const a=G(t);if(a){for(const t of a.segments){const a=e.getDocument(t.documentId);a&&s(a,t.documentId)}return}const r=e.getDocument(t.chapterId);r&&s(r,t.chapterId)}function ps(e){return e instanceof HTMLElement?e.clientWidth:0}function gs(e,t,s){return Math.min(s,Math.max(t,e))}const ms={chapters:[]};function fs(s){const a=e.ref(null),{provides:o}=t.useCapability(ee.id),i=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??ms}),l=e.computed(()=>{var e;return null==(e=s.value)?void 0:e.zoom}),{scale:d,setScale:h,zoomEnabled:c,minZoom:u,maxZoom:p}=function(s,a,o){const i=e.isRef(s)?s:e.computed(()=>s),{registry:l}=t.useRegistry(),{provides:d}=t.useCapability(n.DocumentManagerPlugin.id),{provides:h}=t.useCapability(ee.id),c=e.ref(f()),u=e.ref(c.value),p=e.ref(0),g=()=>{var e;return null==(e=a.value)?void 0:e.pageWidth},m=()=>{return null!=(e=g())&&e>0;var e},f=()=>{var e;return(null==(e=a.value)?void 0:e.initial)??1},v=e.computed(()=>{var e;return function(e,t,s,a,r){if(!e||s<=0)return r;let n=r;for(const o of t.chapters)us(e,o,e=>{n=Math.min(n,cs(e,s,a,r))});return n}(d.value,i.value,p.value,g(),(null==(e=a.value)?void 0:e.max)??3)}),P=e.computed(()=>{var e;return Math.min((null==(e=a.value)?void 0:e.min)??.5,v.value)});let I;function b(e){const t=v.value,s=P.value,a=ls(e,s,t);u.value=a,c.value=a,function(e,t,s,a=.5,n=3){const o=null==e?void 0:e.getStore();if(!o)return;const i=ls(s,a,n);o.dispatchToCore(r.setDefaultScale(i));for(const l of t.chapters){const e=G(l);if(e)for(const t of e.segments)o.getState().core.documents[t.documentId]&&o.dispatchToCore(r.setScale(i,t.documentId));else o.getState().core.documents[l.chapterId]&&o.dispatchToCore(r.setScale(i,l.chapterId))}}(l.value,i.value,a,s,t)}function C(e){if(!d.value||!h.value)return;const t=h.value.resolvePageDocument(e,0),s=d.value.getDocument(t.documentId);if(!s)return;const a=hs(p.value,g());a<=0||b(ds(s,a))}function S(e){m()?C(e):b(f())}return e.watch(()=>null==o?void 0:o.value,e=>{null==I||I(),I=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let s=null;const a=new ResizeObserver(()=>{t(ps(s))}),r=()=>{const r=e.querySelector("[data-chapter-scroll-viewport]");r!==s?(s&&a.unobserve(s),s=r,s?(a.observe(s),t(ps(s))):t(0)):t(ps(s))};r();const n=new MutationObserver(r);n.observe(e,{childList:!0,subtree:!0});const o=requestAnimationFrame(r);return()=>{cancelAnimationFrame(o),n.disconnect(),s&&a.unobserve(s),a.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==I?void 0:I()),e.watch([l,()=>f(),()=>m()],()=>{l.value&&(m()||b(f()))},{immediate:!0}),e.watch(v,e=>{u.value>e&&b(e)}),e.watch([h,i,()=>m(),()=>f()],()=>{const e=h.value;if(e){for(const t of i.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&S(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&S(e.chapterId)})}},{immediate:!0}),e.watch([p,()=>m(),h,i],()=>{if(m()&&!(p.value<=0)&&h.value)for(const e of i.value.chapters)if("loaded"===h.value.getChapterStatus(e.chapterId)){C(e.chapterId);break}}),{scale:c,setScale:b,zoomEnabled:()=>{var e;return!1!==(null==(e=a.value)?void 0:e.enabled)},minZoom:P,maxZoom:v}}(i,l,a);return function(t,s){let a=null;e.watch([t,s],()=>{null==a||a();const e=s.value;a=function(e,t){if(!e||!1===t.enabled)return()=>{};let s=null,a=null,r=0;const n=()=>{const a=e.querySelector("[data-chapter-scroll-viewport]");return!!a&&(null==s||s(),s=function({container:e,getScale:t,setScale:s,minZoom:a=.5,maxZoom:r=3}){let n=0,o=1,i=null,l=1,d=1;const h=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===i?(d=t(),l=1):clearTimeout(i),l*=1-.01*e.deltaY,l=gs(l,.1,10),s(gs(d*l,a,r)),i=setTimeout(()=>{i=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,s]=[...c.values()];n=Math.hypot(s.x-e.x,s.y-e.y),o=t()}},p=e=>{if(c.has(e.pointerId)&&(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size&&n>0)){e.preventDefault();const[t,i]=[...c.values()],l=Math.hypot(i.x-t.x,i.y-t.y);s(gs(o*(l/n),a,r))}},g=e=>{c.delete(e.pointerId),c.size<2&&(n=0)};return e.addEventListener("wheel",h,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",h),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),i&&clearTimeout(i)}}({container:a,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return n()||(a=new MutationObserver(()=>{n()&&(null==a||a.disconnect(),a=null)}),a.observe(e,{childList:!0,subtree:!0}),r=requestAnimationFrame(()=>n())),()=>{r&&cancelAnimationFrame(r),null==a||a.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==a?void 0:a())}(a,e.computed(()=>({enabled:c(),getScale:()=>d.value,setScale:h,minZoom:u.value,maxZoom:p.value}))),{hostRef:a,scale:d,setScale:h,zoomEnabled:c}}function vs(e,t){return`${e}#s${t}`}function Ps(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Is(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:vs(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function bs(e){const[t,s]=e.localPageRange;return s-t+1}function Cs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ss(e,t){return`${e}#s${t}`}function ws(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function ys(e){const t=e.source;if(!Cs(t))return null;const s=t.segmentPageThreshold,a=bs(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:Ss(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Ms(e,t){const s=ys(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function xs(e,t){const s=ys(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Ls(e){var t;const s=e.source;if(!Cs(s))return[];const a=[],{chapterId:r}=e,n=bs(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const $s={kind:"first-wins"};function Ds(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 ks{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 Ts=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=$s,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??$s,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ws(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ws(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ws(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=>this.handleVisibleChange(e),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?Ms(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ys(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ls(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=$s){const s=function(e,t=$s){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Ds(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new ks(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ys(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=xs(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Ms(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=ys(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Cs(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=ws(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?ys(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ts.id="chapter-manager";let Es=Ts;function Os(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const Ns=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Os),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Es.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Is(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=Ps(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=Ps(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=Is(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Ps(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(s,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Ns.id="chapter-scroll";let As=Ns;const zs=["data-global-page-index","data-chapter-id","data-local-page-index"],Fs=(e=>{const t=e.__vccOpts||e;for(const[s,a]of[["__scopeId","data-v-e9ab4da3"]])t[s]=a;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(s){const{provides:a}=t.useCapability(As.id),r=e.ref(null),n=e.ref(null);let o=null;const i=()=>{null==o||o(),o=null,a.value&&(a.value.registerViewport(r.value),o=a.value.onLayoutChange(e=>{n.value=e}))};return e.onMounted(i),e.onBeforeUnmount(()=>{var e;null==o||o(),null==(e=a.value)||e.registerViewport(null)}),e.watch(a,i),(t,s)=>{var a,o,i;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:r,"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==(a=n.value)?void 0:a.totalWidth)??0}px`,height:`${(null==(o=n.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(i=n.value)?void 0:i.items)??[],a=>(e.openBlock(),e.createElementBlock("div",{key:a.globalPageIndex,"data-global-page-index":a.globalPageIndex,"data-chapter-id":a.chapterId,"data-local-page-index":a.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${a.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${a.width}px`,height:`${a.height}px`,backgroundColor:a.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[a.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:a},()=>[s[0]||(s[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:a},void 0,!0)],12,zs))),128))],4)],6)}}})),Gs=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const s=t;return(a,r)=>(e.openBlock(),e.createBlock(e.unref(w.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 Vs(e){const[t,s]=e.localPageRange;return s-t+1}function Rs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function _s(e,t){return`${e}#s${t}`}function Bs(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Us(e){const t=e.source;if(!Rs(t))return null;const s=t.segmentPageThreshold,a=Vs(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:_s(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function qs(e,t){const s=Us(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Hs(e,t){const s=Us(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Ws(e){var t;const s=e.source;if(!Rs(s))return[];const a=[],{chapterId:r}=e,n=Vs(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const js={kind:"first-wins"};function Zs(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 Ys=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 Js=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=js,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??js,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Bs(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Bs(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Bs(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=>this.handleVisibleChange(e),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?qs(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Us(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ws(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=js){const s=function(e,t=js){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Zs(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new Ys(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Us(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Hs(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=qs(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=Us(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Rs(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=Bs(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?Us(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Js.id="chapter-manager";let Ks=Js;function Xs(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),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function ea(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:Xs(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function ta(e){const[t,s]=e.localPageRange;return s-t+1}function sa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function aa(e,t){return`${e}#s${t}`}function ra(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function na(e){const t=e.source;if(!sa(t))return null;const s=t.segmentPageThreshold,a=ta(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:aa(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function oa(e,t){const s=na(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function ia(e,t){const s=na(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function la(e){var t;const s=e.source;if(!sa(s))return[];const a=[],{chapterId:r}=e,n=ta(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const da={kind:"first-wins"};function ha(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 ca{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 ua=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=da,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??da,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ra(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ra(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ra(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=>this.handleVisibleChange(e),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?oa(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?na(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...la(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=da){const s=function(e,t=da){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,ha(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new ca(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?na(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=ia(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=oa(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=na(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(sa(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=ra(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?na(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ua.id="chapter-manager";let pa=ua;function ga(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const ma=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ga),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(pa.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=ea(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=Qs(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=Qs(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=ea(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Qs(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(s,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};ma.id="chapter-scroll";let fa=ma;const va=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(fa.id),this.chapterManager=this.registry.getPlugin(Ks.id),this.documentManager=this.registry.getPlugin(n.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 a=this.notes.get(e);a&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,a),this.noteActivated$.emit({noteId:e,anchor:a}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,a]of this.notes.entries())a.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:Ia(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:a}=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),a=this.config.callbacks.onCreateNote;if(!a)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await a(s)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const n={...s,noteId:r.noteId};return this.registerNote(n),n}async deleteNote(t){var s,a;if(this.notes.has(t)){try{await(null==(a=(s=this.config.callbacks).onDeleteNote)?void 0:a.call(s,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var a,r;const n=this.notes.get(t);if(!n)return;const o={...n,content:s};try{await(null==(r=(a=this.config.callbacks).onUpdateNote)?void 0:r.call(a,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const a=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(s.chapterId);const n=r.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(n.documentId))?void 0:t.pages[n.pageIndex])?(a.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),a.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):a.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 a=setTimeout(()=>{r(),s(null)},2500),r=t.onLayoutChange(t=>{const n=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);n&&(clearTimeout(a),r(),s(n))})})}};va.id="note";let Pa=va;function Ia(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function ba(e){const{markerPdf:t,lineRects:s,sx:a,sy:r,cssPageWidth:n,iconSize:o,gapPx:i=6}=e,l=(null==s?void 0:s.length)?s[s.length-1]:void 0;let d,h;l?(d=(l.origin.x+l.size.width)*a+i,h=l.origin.y*r+(l.size.height*r-o)/2):(d=t.x*a-o/2,h=t.y*r-o-i);const c=Math.max(0,n-o-2);return d>c&&(d=c),h<0&&(h=0),{left:d,top:h}}const Ca={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Sa=["onMouseenter"],wa=["data-note-marker-zone","onMouseenter","onMouseleave"],ya=["onClick"],Ma=["onClick"],xa=["onClick"],La=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const a=s,{provides:r}=t.useCapability(Pa.id),n=e.ref([]),o=e.ref(null),i=e.ref(null);e.watch(r,e=>{if(e)return e.onNotesChange(e=>{n.value=e.filter(e=>e.chapterId===a.chapterId&&e.localPageIndex===a.localPageIndex)})},{immediate:!0});let l=null;e.watch(i,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var s;const a=t.target;(null==(s=a.closest)?void 0:s.call(a,`[data-note-marker-zone="${e}"]`))||(i.value=null,o.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const d=e.computed(()=>{var e;return(null==(e=a.ui)?void 0:e.iconSize)??16}),h=e.computed(()=>{var e;return(null==(e=a.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=a.cssPageWidth/a.pdfPageWidth,s=a.cssPageHeight/a.pdfPageHeight,r=d.value,{left:n,top:o}=ba({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:s,cssPageWidth:a.cssPageWidth,iconSize:r}),l=function(e,t,s){let a=1/0,r=1/0,n=-1/0,o=-1/0;for(const i of e)a=Math.min(a,i.origin.x*t),r=Math.min(r,i.origin.y*s),n=Math.max(n,(i.origin.x+i.size.width)*t),o=Math.max(o,(i.origin.y+i.size.height)*s);return{left:a,top:r,width:n-a,height:o-r}}(e.rectsPdfCoord,t,s),h=i.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,n)-8),u=Math.max(0,Math.min(l.top,o)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(a.cssPageWidth,Math.max(l.left+l.width,n+r)+8)-c,zoneH:Math.max(l.top+l.height,o+r+6+h)+8-u,iconLeft:n,iconTop:o,sx:t,sy:s}}return(t,a)=>e.unref(r)&&n.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Ca,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(s,a)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${a}`,style:e.normalizeStyle({position:"absolute",left:s.origin.x*c(t).sx+"px",top:s.origin.y*c(t).sy+"px",width:s.size.width*c(t).sx+"px",height:s.size.height*c(t).sy+"px",background:h.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>o.value=t.noteId},null,44,Sa))),128)),o.value===t.noteId||i.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${c(t).zoneLeft}px`,top:`${c(t).zoneTop}px`,width:`${c(t).zoneW}px`,height:`${c(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>o.value=t.noteId,onMouseleave:e=>i.value!==t.noteId&&(o.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:c(t).iconTop-c(t).zoneTop+"px",width:`${d.value}px`,height:`${d.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:a[0]||(a[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>i.value=i.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,ya),i.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:`${c(t).iconTop-c(t).zoneTop+d.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:a[1]||(a[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==(a=r.value)||a.requestEditNote(s.noteId,s));var s,a}}," 编辑 ",8,Ma),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,a;return a=t.noteId,null==(s=r.value)||s.requestDeleteNote(a),void(i.value=null)}}," 删除 ",8,xa)],36)):e.createCommentVNode("",!0)],44,wa)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),$a={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Da=["title","onClick"],ka=["onClick"],Ta=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const a=s,{provides:r}=t.useCapability(Zt.id),n=e.ref([]),o=e.ref(null),i=e.ref(null);function l(){const e=r.value;e&&(n.value=e.listBookmarks().filter(e=>e.anchor.chapterId===a.chapterId&&e.anchor.localPageIndex===a.localPageIndex))}e.watch(r,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let d=null;e.watch(o,e=>{d&&(document.removeEventListener("mousedown",d),d=null),e&&(d=e=>{var t;(null==(t=i.value)?void 0:t.contains(e.target))||(o.value=null)},document.addEventListener("mousedown",d))}),e.onBeforeUnmount(()=>{d&&document.removeEventListener("mousedown",d)});const h=e.computed(()=>{var e;return(null==(e=a.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:s}=function(e){var t;const s=a.cssPageWidth/a.pdfPageWidth,r=a.cssPageHeight/a.pdfPageHeight,n=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return ba({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:n,sx:s,sy:r,cssPageWidth:a.cssPageWidth,iconSize:h.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,s-6)}px`,width:`${h.value+12}px`,height:`${h.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,a)=>e.unref(r)&&n.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",$a,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(c(t)),onMousedown:a[1]||(a[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${h.value}px`,height:`${h.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=>o.value=o.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Da),o.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:i,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:a[0]||(a[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=r.value;t&&await t.requestRemoveBookmark(e)&&(o.value=null)}(t.id)}," 删除书签 ",8,ka)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function Ea(e){return e.pdfDocumentId??e.chapterId}function Oa(e){return e.pdfPageIndex??e.localPageIndex}function Na(e,t){e.wait(t,()=>{})}const Aa={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)"},za={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const Fa=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 a=s,r=e.computed(()=>Ea(a.item)),o=e.computed(()=>Oa(a.item));!function(s){const{provides:a}=t.useCapability(n.DocumentManagerPlugin.id);e.watch([a,s],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(r);const{provides:i}=t.useCapability(n.DocumentManagerPlugin.id),{provides:l}=t.useCapability(d.SelectionPlugin.id),h=e.computed(()=>{var e,t;return null==(t=null==(e=i.value)?void 0:e.getDocument(r.value))?void 0:t.pages[o.value]});function c(t,s){var r,n,o,i;const d=a.createNote.value;if(d&&!1!==(null==(n=null==(r=a.features)?void 0:r.notes)?void 0:n.enabled)&&!1!==(null==(i=null==(o=a.features)?void 0:o.selectionToolbar)?void 0:i.enabled))return a=>{var r;const n={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(r=a.placement)?void 0:r.suggestTop)?-40:a.rect.size.height+8};return e.h("div",a.menuWrapperProps,[e.h("div",{style:n},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(Oa(t),s);Na(l.value.getSelectedText(s),s=>{var a,r,n;d((a=t,r=e,n=s.join("\n"),{chapterId:a.chapterId,localPageIndex:a.localPageIndex,globalPageIndex:a.globalPageIndex,globalPageNumber:a.globalPageNumber,rectsPdfCoord:r,selectedText:n}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=a.buildSelectionMenu,t={item:a.item,defaultMenu:c(a.item,r.value),createNote:a.createNote.value};if(e){const s=e(t);if(s)return s}return t.defaultMenu}),p=function(t,s){var a,r;const{provides:n}=C.useAnnotationCapability(),o=null==(a=null==s?void 0:s.markup)?void 0:a.annotationMenu,i=!1!==(null==(r=null==s?void 0:s.markup)?void 0:r.enabled),l=!1!==(null==o?void 0:o.enabled);return e.computed(()=>{const s="string"==typeof t?t:t.value;if(i&&l&&n.value)return t=>{const{context:a,rect:r,placement:i,menuWrapperProps:l,selected:d}=t;if(!d||"annotation"!==a.type)return e.h("span",l);if(a.structurallyLocked)return e.h("span",l);if(h=a.annotation.object.type,!N.has(h))return e.h("span",l);var h;const c=n.value.forDocument(s),{pageIndex:u,id:p}=a.annotation.object,g=()=>{null==c||c.deleteAnnotation(u,p)},m={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==i?void 0:i.suggestTop)?void 0:`${r.size.height+8}px`,bottom:(null==i?void 0:i.suggestTop)?`${r.size.height+8}px`:void 0},f=(null==o?void 0:o.renderMenu)?o.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:za,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:Aa,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(r,a.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}}(a.annotationSelectionMenu,p.value)),m=e.computed(()=>{var e;return null==(e=a.renderPageOverlay)?void 0:e.call(a,a.item)});return(t,a)=>s.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(P.GlobalPointerProvider),{key:0,"document-id":r.value},{default:e.withCtx(()=>[e.createVNode(e.unref(I.Rotate),{"document-id":r.value,"page-index":o.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":r.value,"page-index":o.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(L)},{default:e.withCtx(()=>[e.createVNode(e.unref(Gs),{"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-document-id":r.value,"pdf-page-index":o.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(b.SelectionLayer),{"document-id":r.value,"page-index":o.value,"selection-menu":u.value},null,8,["document-id","page-index","selection-menu"]),s.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(S.RedactionLayer),{key:0,"document-id":r.value,"page-index":o.value,"selection-menu":s.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(C.AnnotationLayer),{"document-id":r.value,"page-index":o.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),s.showBookmarkMarkers&&h.value?(e.openBlock(),e.createBlock(Ta,{key:1,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":h.value.size.width,"pdf-page-height":h.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&&h.value?(e.openBlock(),e.createBlock(La,{key:3,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":h.value.size.width,"pdf-page-height":h.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"]))}}),Ga=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(s){const a=s,r=e.computed(()=>Ea(a.item)),{provides:n}=t.useCapability(d.SelectionPlugin.id),{provides:o}=t.useCapability(Zt.id),i=e.ref(null),l=e.ref(null),h=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=a.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??h.value);let g=null,m=0;function f(){const e=n.value;if(!e)return;const t=e.forDocument(r.value).getState().geometry[a.item.localPageIndex];t&&(l.value=t)}e.watch([n,r,()=>a.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(m),l.value=null,!e)return;const t=e.forDocument(r.value);g=t.onSelectionChange(f);let s=!1;const n=()=>{if(!s){try{if(f(),t.getState().geometry[a.item.localPageIndex])return}catch{}m=requestAnimationFrame(n)}};return n(),()=>{s=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>a.pdfPageWidth,c,n],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&a.pdfPageWidth&&(v=e=>{if(c.value)return;const t=n.value;if(t)try{if(t.forDocument(r.value).getState().selecting)return void(h.value=null)}catch{}const s=i.value;if(!s)return;const o=s.getBoundingClientRect();if(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)return void(h.value=null);const u=function(e,t){const s=d.glyphAt(e,t);if(s<0)return null;const a=d.expandToLineBoundary(e,s);if(!a)return null;const r=d.rectsWithinSlice(e,a.from,a.to);return 0===r.length?null:{lineRects:r,charFrom:a.from,charTo:a.to}}(l.value,{x:(e.clientX-o.left)/(a.cssPageWidth/a.pdfPageWidth),y:(e.clientY-o.top)/(a.cssPageHeight/a.pdfPageHeight)});h.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)?Wt(a.item.chapterId,a.item.localPageIndex,e,{globalPageIndex:a.item.globalPageIndex,globalPageNumber:a.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=o.value;return!(!e||!t)&&t.listBookmarks().some(t=>Ht(t.anchor,e))});function b(){const e=o.value,t=P.value;e&&t&&!I.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),h.value=null,c.value=null)}const C=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!a.pdfPageWidth)return null;const s=a.cssPageWidth/a.pdfPageWidth,r=a.cssPageHeight/a.pdfPageHeight,n=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*s+6,Math.max(0,a.cssPageWidth-n-2)),iconTop:t.origin.y*r+(t.size.height*r-n)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*s-4),zoneTop:Math.max(0,t.origin.y*r-4),size:n}});return(t,a)=>{var r;return e.unref(o)&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:i,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[C.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${C.value.zoneLeft}px`,top:`${C.value.zoneTop}px`,width:`${C.value.size+20}px`,height:`${((null==(r=p.value[p.value.length-1])?void 0:r.size.height)??0)*(s.cssPageHeight/s.pdfPageHeight)+C.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:a[0]||(a[0]=e=>c.value=p.value),onMouseleave:a[1]||(a[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:C.value.iconLeft-C.value.zoneLeft+"px",top:C.value.iconTop-C.value.zoneTop+"px",width:`${C.value.size}px`,height:`${C.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(b,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),Va={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Ra={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},_a={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Ba={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Ua={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"},qa={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Ha={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Wa=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(s,a)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",Va,[...a[0]||(a[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",Ra,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",_a)):e.createCommentVNode("",!0),a[1]||(a[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",Ba)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",Ua)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",qa)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Ha,[...a[2]||(a[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)])]))}),ja=["title","aria-label","onMouseenter","onClick"],Za=["title","onMouseenter","onClick"],Ya={style:{"font-size":"11px","font-weight":"600"}},Ja=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:s}){const a=t,r=s,n=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],o=e.computed(()=>new Set(a.hiddenBuiltinActions??[])),i=e.computed(()=>!o.value.has("copy")),l=e.computed(()=>n.filter(e=>!o.value.has(e.id))),d=e.computed(()=>!o.value.has("note")),h=e.computed(()=>[...a.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),c=e.computed(()=>l.value.length>0||h.value.length>0),u=e.ref(null),p=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:a.placementAbove?void 0:`${a.anchorHeight+10}px`,bottom:a.placementAbove?`${a.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,a)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[i.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:a[0]||(a[0]=e=>u.value="copy"),onMouseleave:a[1]||(a[1]=e=>u.value=null),onClick:a[2]||(a[2]=e=>r("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(Wa,{key:1,kind:"copy"}))],36),c.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:a[3]||(a[3]=e=>u.value=null),onClick:e=>r("action",t.id)},[e.createVNode(Wa,{kind:t.id},null,8,["kind"])],44,ja))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.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:a[4]||(a[4]=e=>u.value=null),onClick:e=>r("action",t.id)},[e.createElementVNode("span",Ya,e.toDisplayString(t.label.slice(0,2)),1)],44,Za))),128)),d.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||i.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:a[5]||(a[5]=e=>u.value="note"),onMouseleave:a[6]||(a[6]=e=>u.value=null),onClick:a[7]||(a[7]=e=>r("action","note"))},[e.createVNode(Wa,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Ka={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},Xa=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(a){const r=a,o=e.computed(()=>r.features),{hostRef:i}=fs(o),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=r.features)?void 0:e.scrollViewport)?void 0:t.background)??$}}),h=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e,t,a;const r=null==(a=null==(t=null==(e=s.value)?void 0:e.getPlugin(nt.id))?void 0:t.provides)?void 0:a.call(t);return r?e=>r.createNoteFromSelection(e):null})}(),c=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(nt.id))})}(),u=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(Zt.id))})}(),p=e.computed(()=>{var e,t;return r.showNoteMarkers&&c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return r.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(a,r){const n=e.computed(()=>{var e;return null==(e=a())?void 0:e.selectionToolbar}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=a())?void 0:e.markup)?void 0:t.enabled)}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=a())?void 0:e.notes)?void 0:t.enabled)}),l=e.computed(()=>{var e,t;return!(null==(t=null==(e=n.value)?void 0:e.hiddenBuiltinActions)?void 0:t.includes("copy"))}),{provides:h}=t.useCapability(d.SelectionPlugin.id),{provides:c}=t.useCapability(s.AnnotationPlugin.id),{provides:u}=t.useCapability(nt.id);return e.computed(()=>{var t,s,d;if(!1!==(null==(t=n.value)?void 0:t.enabled)&&(o.value||i.value||l.value||(null==(d=null==(s=n.value)?void 0:s.extraActions)?void 0:d.length)))return t=>{const s=Ea(t.item),d=Oa(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(Ja,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(m=n.value)?void 0:m.hiddenBuiltinActions,extraActions:null==(f=n.value)?void 0:f.extraActions,renderCopyIcon:null==(v=n.value)?void 0:v.renderCopyIcon,onAction:e=>{var n,p,g;if("copy"!==e)if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!h.value||!u.value||!i.value)return;const e=h.value.getHighlightRectsForPage(d,s);return void Na(h.value.getSelectedText(s),s=>{var a;null==(a=u.value)||a.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:s.join("\n")})})}null==(n=null==r?void 0:r.onExtraAction)||n.call(r,e,t)}else{if(!h.value||!c.value||!o.value)return;O(s,Ka[e],c.value,h.value,null==(g=null==(p=a())?void 0:p.markup)?void 0:g.styles)}else{if(!h.value||!l.value)return;Na(h.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"))})}}}))}}})}(()=>r.features,{onExtraAction:r.onExtraSelectionAction}),v=e.computed(()=>{if(r.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return r.buildSelectionMenu?r.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(n.DocumentManagerPlugin.id);function I(t){var s;const a=[];if(m.value){const s=function(t){var s,a,n,o;const i=Ea(t),l=Oa(t),d=null==(a=null==(s=P.value)?void 0:s.getDocument(i))?void 0:a.pages[l];return t.isPlaceholder||!d?null:e.h(Ga,{item:t,pdfPageWidth:d.size.width,pdfPageHeight:d.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(n=r.features)?void 0:n.bookmarks)?void 0:o.hover})}(t);s&&a.push(s)}const n=null==(s=r.renderPageOverlay)?void 0:s.call(r,t);if(n&&a.push(n),a.length)return e.h("div",a)}return(t,s)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:i,class:e.normalizeClass(a.className),style:e.normalizeStyle(a.className?void 0:e.unref(M))},[e.createVNode(e.unref(Fs),{class:e.normalizeClass(a.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var s,r,n,o;return[e.createVNode(Fa,{item:t,features:a.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":a.showRedactionLayer,"note-marker-ui":null==(r=null==(s=a.features)?void 0:s.notes)?void 0:r.marker,"bookmark-marker-ui":null==(o=null==(n=a.features)?void 0:n.bookmarks)?void 0:o.marker,"build-selection-menu":v.value,"create-note":e.unref(h),"annotation-selection-menu":a.annotationSelectionMenu,"redaction-selection-menu":a.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))}}),Qa={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},er=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(s){const a=s,r=e.computed(()=>function(e){if(e.options)return is(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=z(e.features),{plugins:s}=as({...e.editorOptions,features:t});return{plugins:s,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:a.engine,options:a.options,editorOptions:a.editorOptions,features:a.features}));return(a,n)=>(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:r.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",Qa,[e.renderSlot(a.$slots,"prepend"),e.createVNode(Xa,{class:e.normalizeClass(s.viewportClassName),style:{flex:1,minHeight:0},features:r.value.features,"on-extra-selection-action":s.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(a.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),tr={class:"chapter-tree-row"},sr=["aria-expanded"],ar={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},rr={class:"chapter-tree-label"},nr={class:"chapter-tree-meta"},or={key:0},ir=(e,t)=>{const s=e.__vccOpts||e;for(const[a,r]of t)s[a]=r;return s},lr=ir(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const s={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},a=t,r=e.computed(()=>a.node.children??[]),n=e.computed(()=>r.value.length>0),o=e.ref(a.depth<1),i=e.computed(()=>a.activeChapterId===a.node.id),l=e.computed(()=>a.chapterStatus[a.node.id]??"idle"),d=e.computed(()=>!n.value);return(a,h)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",tr,[n.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":o.value,onClick:h[0]||(h[0]=e=>o.value=!o.value)},e.toDisplayString(o.value?"▼":"▶"),9,sr)):(e.openBlock(),e.createElementBlock("span",ar)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":i.value}]),onClick:h[1]||(h[1]=e=>a.$emit("select",t.node.id))},[e.createElementVNode("div",rr,e.toDisplayString(t.node.title),1),e.createElementVNode("div",nr,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),d.value?(e.openBlock(),e.createElementBlock("span",or,e.toDisplayString(s[l.value]),1)):e.createCommentVNode("",!0)])],2)]),n.value&&o.value?(e.openBlock(),e.createBlock(dr,{key:0,nodes:r.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:h[2]||(h[2]=e=>a.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),dr=ir(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(s,a)=>(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,r=>(e.openBlock(),e.createBlock(lr,{key:r.id,node:r,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:a[0]||(a[0]=e=>s.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),hr={class:"chapter-tree"},cr={class:"chapter-tree-nav","aria-label":"章节目录"},ur=ir(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(s,{emit:a}){const r=s,n=a,{provides:o}=t.useCapability(Se.id),{provides:i}=t.useCapability(ee.id),l=e.ref({});function d(){if(!i.value)return;const e={},t=s=>{var a;for(const r of s)e[r.id]=i.value.getChapterStatus(r.id),(null==(a=r.children)?void 0:a.length)&&t(r.children)};t(r.tree),l.value=e}e.watch([i,()=>r.tree],d,{immediate:!0});let h=null;function c(e){var t;n("active-chapter-change",e),null==(t=o.value)||t.scrollToChapter(e)}return e.watch(i,e=>{null==h||h(),h=e?e.onChapterStatusChange(d):null},{immediate:!0}),e.onBeforeUnmount(()=>null==h?void 0:h()),(t,a)=>(e.openBlock(),e.createElementBlock("aside",hr,[a[0]||(a[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",cr,[e.createVNode(dr,{nodes:s.tree,depth:0,"active-chapter-id":s.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),pr=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,s)=>(e.openBlock(),e.createBlock(e.unref(er),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 gr(e){const[t,s]=e.localPageRange;return s-t+1}function mr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function fr(e,t){return`${e}#s${t}`}function vr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Pr(e){const t=e.source;if(!mr(t))return null;const s=t.segmentPageThreshold,a=gr(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:fr(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Ir(e,t){const s=Pr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function br(e,t){const s=Pr(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Cr(e){var t;const s=e.source;if(!mr(s))return[];const a=[],{chapterId:r}=e,n=gr(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Sr={kind:"first-wins"};function wr(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 yr=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 Mr=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Sr,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Sr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=vr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=vr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=vr(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=>this.handleVisibleChange(e),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?Ir(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Pr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Cr(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Sr){const s=function(e,t=Sr){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,wr(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new yr(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Pr(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=br(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Ir(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=Pr(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(mr(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=vr(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?Pr(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Mr.id="chapter-manager";let xr=Mr;function Lr(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),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Dr(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:Lr(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function kr(e){const[t,s]=e.localPageRange;return s-t+1}function Tr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Er(e,t){return`${e}#s${t}`}function Or(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Nr(e){const t=e.source;if(!Tr(t))return null;const s=t.segmentPageThreshold,a=kr(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:Er(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Ar(e,t){const s=Nr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function zr(e,t){const s=Nr(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Fr(e){var t;const s=e.source;if(!Tr(s))return[];const a=[],{chapterId:r}=e,n=kr(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Gr={kind:"first-wins"};function Vr(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 Rr{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 _r=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Gr,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Gr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Or(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Or(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Or(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=>this.handleVisibleChange(e),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?Ar(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Nr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Fr(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Gr){const s=function(e,t=Gr){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Vr(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new Rr(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Nr(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=zr(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Ar(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=Nr(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Tr(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=Or(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?Nr(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};_r.id="chapter-manager";let Br=_r;function Ur(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}function qr(e){const[t,s]=e.localPageRange;return s-t+1}function Hr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Wr(e,t){return`${e}#s${t}`}function jr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Zr(e){const t=e.source;if(!Hr(t))return null;const s=t.segmentPageThreshold,a=qr(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:Wr(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Yr(e,t){const s=Zr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Jr(e,t){const s=Zr(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Kr(e){var t;const s=e.source;if(!Hr(s))return[];const a=[],{chapterId:r}=e,n=qr(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}(class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Ur),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Br.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=Dr(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=$r(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=$r(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=Dr(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=$r(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),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 Xr={kind:"first-wins"};function Qr(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 en=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 tn=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Xr,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.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}=jr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=jr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=jr(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=>this.handleVisibleChange(e),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?Yr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Zr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Kr(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Xr){const s=function(e,t=Xr){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Qr(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new en(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Zr(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Jr(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Yr(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=Zr(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Hr(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=jr(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?Zr(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};tn.id="chapter-manager";let sn=tn;function an(e,t){return`${e}#s${t}`}function rn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function nn(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:an(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function on(e){const[t,s]=e.localPageRange;return s-t+1}function ln(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function dn(e,t){return`${e}#s${t}`}function hn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function cn(e){const t=e.source;if(!ln(t))return null;const s=t.segmentPageThreshold,a=on(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:dn(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function un(e,t){const s=cn(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function pn(e,t){const s=cn(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function gn(e){var t;const s=e.source;if(!ln(s))return[];const a=[],{chapterId:r}=e,n=on(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const mn={kind:"first-wins"};function fn(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 vn=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 Pn=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=mn,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??mn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=hn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=hn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=hn(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=>this.handleVisibleChange(e),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?un(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?cn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...gn(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=mn){const s=function(e,t=mn){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,fn(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new vn(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?cn(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=pn(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=un(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=cn(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(ln(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=hn(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?cn(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Pn.id="chapter-manager";let In=Pn;function bn(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const Cn=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,bn),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(In.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=nn(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=rn(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=rn(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=nn(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=rn(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(s,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Cn.id="chapter-scroll";let Sn=Cn;const wn=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Sn.id),this.chapterManager=this.registry.getPlugin(sn.id),this.documentManager=this.registry.getPlugin(n.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 a=this.notes.get(e);a&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,a),this.noteActivated$.emit({noteId:e,anchor:a}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,a]of this.notes.entries())a.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:Mn(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:a}=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),a=this.config.callbacks.onCreateNote;if(!a)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await a(s)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const n={...s,noteId:r.noteId};return this.registerNote(n),n}async deleteNote(t){var s,a;if(this.notes.has(t)){try{await(null==(a=(s=this.config.callbacks).onDeleteNote)?void 0:a.call(s,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var a,r;const n=this.notes.get(t);if(!n)return;const o={...n,content:s};try{await(null==(r=(a=this.config.callbacks).onUpdateNote)?void 0:r.call(a,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const a=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(s.chapterId);const n=r.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(n.documentId))?void 0:t.pages[n.pageIndex])?(a.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),a.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):a.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 a=setTimeout(()=>{r(),s(null)},2500),r=t.onLayoutChange(t=>{const n=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);n&&(clearTimeout(a),r(),s(n))})})}};wn.id="note";let yn=wn;function Mn(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function xn(e){const[t,s]=e.localPageRange;return s-t+1}function Ln(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $n(e,t){return`${e}#s${t}`}function Dn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function kn(e){const t=e.source;if(!Ln(t))return null;const s=t.segmentPageThreshold,a=xn(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:$n(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function Tn(e,t){const s=kn(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function En(e,t){const s=kn(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function On(e){var t;const s=e.source;if(!Ln(s))return[];const a=[],{chapterId:r}=e,n=xn(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Nn={kind:"first-wins"};function An(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 zn=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 Fn=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Nn,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Nn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Dn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Dn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Dn(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=>this.handleVisibleChange(e),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?Tn(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?kn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...On(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Nn){const s=function(e,t=Nn){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,An(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new zn(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?kn(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=En(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=Tn(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=kn(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Ln(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=Dn(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?kn(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Fn.id="chapter-manager";let Gn=Fn;function Vn(e,t){return`${e}#s${t}`}function Rn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function _n(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:Vn(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}function Bn(e){const[t,s]=e.localPageRange;return s-t+1}function Un(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function qn(e,t){return`${e}#s${t}`}function Hn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Wn(e){const t=e.source;if(!Un(t))return null;const s=t.segmentPageThreshold,a=Bn(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:qn(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function jn(e,t){const s=Wn(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Zn(e,t){const s=Wn(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function Yn(e){var t;const s=e.source;if(!Un(s))return[];const a=[],{chapterId:r}=e,n=Bn(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=(l=o,(i=n)<=0||l<=0?0:Math.ceil(i/l));s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}var i,l;for(let d=0;d<s.urls.length;d++)(null==(t=s.urls[d])?void 0:t.trim())||a.push(`${r}: source.urls[${d}] is empty`);return a}const Jn={kind:"first-wins"};function Kn(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 Xn{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 Qn=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Jn,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Jn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Hn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Hn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Hn(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=>this.handleVisibleChange(e),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?jn(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Wn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Yn(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Jn){const s=function(e,t=Jn){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Kn(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new Xn(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Wn(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Zn(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=jn(this.findChapter(s.chapterId),s.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus)"loaded"===a&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=Wn(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(Un(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=Hn(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?Wn(t):null,r=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Qn.id="chapter-manager";let eo=Qn;function to(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 a=e.items[s],r=t.items[s];if(a.globalPageIndex!==r.globalPageIndex||a.isPlaceholder!==r.isPlaceholder||a.chapterId!==r.chapterId||a.localPageIndex!==r.localPageIndex||a.pdfDocumentId!==r.pdfDocumentId||a.pdfPageIndex!==r.pdfPageIndex||a.offsetTop!==r.offsetTop||a.width!==r.width||a.height!==r.height)return!1}return!0}const so=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,to),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(eo.id),this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),a=s.getChapterStatus(e);if("error"===a||"password-required"===a)return!0;const r=s.getChapter(e);if(!r)return!0;const n=function(e,t){const s=_n(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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}=Rn(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:s}=Rn(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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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 a=0;a<e;a++){const{width:e,height:r}=this.getPageSize(a);this.offsets[a]=t,t+=r+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const a of t){const t=this.virtualPageMap.toGlobal(e,a.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===a.width&&r.height===a.height||(this.pageSizes.set(t.globalPageIndex,{width:a.width,height:a.height}),s=!0)}if(s){const e=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()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),a=s.getChapter(e),r=this.virtualPageMap.pagesOfChapter(e);if(!a||0===r.length)return;const n=_n(a),o=this.documentManager.provides(),i=[],l=(e,t,s,a)=>{var r;const n=o.getDocument(e);if(!(null==(r=null==n?void 0:n.pages)?void 0:r.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<a;o++){const e=n.pages[s+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(n)for(const d of n.segments){if(!s.isSegmentLoaded(e,d.index))continue;const t=d.localPageEnd-d.localPageStart+1;l(d.documentId,d.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,r.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Rn(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}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.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),a=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),a.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),a.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,a=this.findFirstVisibleIndex(t);let r=a;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=s)break;r++}const n=[];let o=a,i=-1;for(let l=a;l<r;l++){n.push(l);const e=this.offsets[l],a=e+this.getPageSize(l).height,r=Math.max(0,Math.min(a,s)-Math.max(e,t));r>i&&(i=r,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,a=0;for(;t<=s;){const r=t+s>>1;this.offsets[r]<=e?(a=r,t=r+1):s=r-1}return a}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,a=Math.min(this.offsets.length-1,(s>=0?s:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=a;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),a=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);r.push({globalPageIndex:n,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[n]??0,isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var a;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==s?void 0:s.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,s);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.localPageIndex),l=i?null==(a=this.documentManager.provides().getDocument(i.documentId))?void 0:a.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,s);const d=o.height/l.size.height,h=(this.offsets[e]??0)+t*d-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);s<0||(this.chapterManager.provides().ensureChapterLoaded(e),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 ao=so;function ro(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function no(e,t){const s=e.origin.y,a=e.origin.y+e.size.height,r=t.origin.y,n=t.origin.y+t.size.height,o=Math.max(a,n)-Math.min(s,r);return o<=0?0:Math.max(0,Math.min(a,n)-Math.max(s,r))/o}function oo(e,t){var s,a;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],n=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??ro(r),i=t.markerAnchor??ro(n);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of r)for(const e of n){if(no(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 io=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ao.id),this.chapterManager=this.registry.getPlugin(Gn.id),this.documentManager=this.registry.getPlugin(n.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(a){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",a)}}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 a of this.entries.values())if(oo(a.anchor,e.anchor))return a;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,a;this.entries.delete(e)&&(this.notifyAndPersist(),null==(a=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||a.call(s,e))}async requestRemoveBookmark(t){var s,a;const r=this.entries.get(t);if(!r)return!1;const n=null==(a=null==(s=this.config)?void 0:s.callbacks)?void 0:a.onRequestRemove;if(n)try{if(!(await n(r)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!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,a]of this.entries.entries())a.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 a=this.list();this.change$.emit(a),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(a)).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(),a=this.chapterManager.provides();await a.ensureAllSegmentsLoaded(t.anchor.chapterId);let r=t.anchor.globalPageIndex;if(void 0===r){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;r=e.globalPageIndex}const n=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 a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const r=setTimeout(()=>{n(),a(null)},s),n=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(r),n(),a(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,r,n)}};io.id="paragraph-bookmark";let lo=io;function ho(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 co(e,t){return`${e}#s${t}`}function uo(e,t){const s=function(e){const t=e.source;if(!((s=t)&&"urls"in s&&Array.isArray(s.urls)))return null;var s;const a=t.segmentPageThreshold,r=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),n=[];for(let o=0;o<t.urls.length;o++){const s=o*a,i=Math.min(s+a-1,r-1);if(s>=r)break;n.push({index:o,url:t.urls[o],localPageStart:s,localPageEnd:i,documentId:co(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:a,pageCount:r,segments:n}}(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}a.PdfAnnotationSubtype.HIGHLIGHT,a.PdfAnnotationSubtype.UNDERLINE,a.PdfAnnotationSubtype.SQUIGGLY,a.PdfAnnotationSubtype.STRIKEOUT,a.PdfAnnotationSubtype.HIGHLIGHT,a.PdfAnnotationSubtype.UNDERLINE,a.PdfAnnotationSubtype.SQUIGGLY,a.PdfAnnotationSubtype.STRIKEOUT,function(){const e=ho(void 0,{enabled:!0}),t=ho(void 0,{enabled:!0}),s=ho(void 0,{enabled:!0}),a=ho(void 0,{enabled:!0,min:.5,max:3,initial:1}),r=ho(!1!==e.enabled||!1!==s.enabled,{enabled:!0});null==void 0||(void 0).background}();function po(e){const t=new Uint8Array(e);let s="";for(let a=0;a<t.length;a++)s+=String.fromCharCode(t[a]);return btoa(s)}function go(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 mo(e){return new Promise((t,s)=>{e.wait(e=>t(e),e=>s(e))})}function fo(e){var t,a,r,n;return{annotation:null==(t=e.getPlugin(s.AnnotationPlugin.id))?void 0:t.provides(),note:null==(a=e.getPlugin(yn.id))?void 0:a.provides(),bookmark:null==(r=e.getPlugin(lo.id))?void 0:r.provides(),chapterManager:null==(n=e.getPlugin(xr.id))?void 0:n.provides()}}async function vo(e,t,s){if(!s||!e)return;const a=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==a)throw new Error(`章节 ${t} 未加载成功(${a}),无法导入/导出划线`)}async function Po(e,t,s){const a=go(s),{annotation:r,note:n,bookmark:o,chapterManager:i}=fo(e),l={chapterId:t};if(a.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=o.listBookmarksForChapter(t)}if(a.notes){if(!n)throw new Error("note 插件未注册");l.notes=n.listNotesForChapter(t)}if(a.markup){if(!r)throw new Error("annotation 插件未注册");await vo(i,t,!1!==(null==s?void 0:s.ensureChapterLoaded));const e=await async function(e,t,s){const a=t.getSegmentPlan(s);if(!a)return mo(e.forDocument(s).exportAnnotations());const r=[];for(const n of a.segments){if(!t.isSegmentLoaded(s,n.index))continue;const a=await mo(e.forDocument(n.documentId).exportAnnotations());for(const e of a){const t=e.annotation.pageIndex;r.push({...e,annotation:{...e.annotation,pageIndex:t+n.localPageStart}})}}return r}(r,i,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:po(t.data),mimeType:t.mimeType}}})}(e)}return l}async function Io(e,t,s){const a=go(s),r=(null==s?void 0:s.mode)??"replace",{annotation:n,note:o,bookmark:i,chapterManager:l}=fo(e),d=t.chapterId;if(a.bookmarks&&t.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");if("replace"===r)i.replaceBookmarksForChapter(d,t.bookmarks);else for(const e of t.bookmarks)i.addBookmark(e)}if(a.notes&&t.notes){if(!o)throw new Error("note 插件未注册");if("replace"===r)o.replaceNotesForChapter(d,t.notes);else for(const e of t.notes)o.registerNote(e)}if(a.markup&&t.markup){if(!n)throw new Error("annotation 插件未注册");await vo(l,d,!1!==(null==s?void 0:s.ensureChapterLoaded)),function(e,t,s,a,r){const n=t.getSegmentPlan(s);if(!n){const t=e.forDocument(s);return"replace"===r&&t.deleteAllAnnotations(),void t.importAnnotations(a)}const o=t.getChapter(s);if(!o)return;const i=new Map;for(const l of a){const e=l.annotation.pageIndex,t=uo(o,e),s=n.segments[t];if(!s)continue;const a=i.get(t)??[];a.push({...l,annotation:{...l.annotation,pageIndex:e-s.localPageStart}}),i.set(t,a)}for(const l of n.segments){const t=e.forDocument(l.documentId),s=i.get(l.index)??[];"replace"===r&&t.deleteAllAnnotations(),s.length>0&&t.importAnnotations(s)}}(n,l,d,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 a=0;a<t.length;a++)s[a]=t.charCodeAt(a);return s.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:s,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),r)}(null==s?void 0:s.persistNotes)&&o&&await s.persistNotes(o.listAllNotes()),(null==s?void 0:s.persistBookmarks)&&i&&await s.persistBookmarks(i.listBookmarks())}function bo(e){return JSON.stringify(e,null,2)}function Co(e){return JSON.stringify(e,null,2)}function So(e,t){const s=new Blob([t],{type:"application/json;charset=utf-8"}),a=URL.createObjectURL(s),r=document.createElement("a");r.href=a,r.download=e,r.click(),URL.revokeObjectURL(a)}function wo(e){const[t,s]=e.localPageRange;return s-t+1}function yo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Mo(e,t){return`${e}#s${t}`}function xo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),a=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(a)||a<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:a}}function Lo(e){const t=e.source;if(!yo(t))return null;const s=t.segmentPageThreshold,a=wo(e),r=[];for(let n=0;n<t.urls.length;n++){const o=n*s,i=Math.min(o+s-1,a-1);if(o>=a)break;r.push({index:n,url:t.urls[n],localPageStart:o,localPageEnd:i,documentId:Mo(e.chapterId,n)})}return{chapterId:e.chapterId,threshold:s,pageCount:a,segments:r}}function $o(e,t){const s=Lo(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!a){const a=s.segments[s.segments.length-1];return a?{documentId:a.documentId,pageIndex:t-a.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:a.documentId,pageIndex:t-a.localPageStart}}function Do(e,t){const s=Lo(e);if(!s)return 0;const a=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==a?void 0:a.index)??Math.floor(t/s.threshold)}function ko(e){var t;const s=e.source;if(!yo(s))return[];const a=[],{chapterId:r}=e,n=wo(e),o=s.segmentPageThreshold;if(o<=0&&a.push(`${r}: segmentPageThreshold must be > 0`),0===s.urls.length&&a.push(`${r}: source.urls must not be empty`),o>0){const e=function(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}(n,o);s.urls.length!==e&&a.push(`${r}: source.urls.length (${s.urls.length}) must equal ceil(pageCount/threshold) (${e})`)}for(let i=0;i<s.urls.length;i++)(null==(t=s.urls[i])?void 0:t.trim())||a.push(`${r}: source.urls[${i}] is empty`);return a}const To={kind:"first-wins"};function Eo(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 Oo{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 No(e,t=To){const s=function(e,t=To){const s=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let a=e;a<=t;a++){const e=s.get(a);e?e.push(r):s.set(a,[r])}}const a=new Map;for(const[r,n]of s)a.set(r,Eo(r,n,t));return a}(e,t),a=new Map;for(const i of e.chapters)a.set(i.chapterId,i);const r=Array.from(s.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of r){const e=s.get(i),t=a.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,d=l+(i-r);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:d})}return new Oo(n)}const Ao=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=To,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??To,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=xo(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=xo(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=xo(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=>this.handleVisibleChange(e),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?$o(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Lo(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=[],s=new Set;for(const a of e.chapters){s.has(a.chapterId)&&t.push(`Duplicate chapterId: ${a.chapterId}`),s.add(a.chapterId);const[e,r]=a.globalPageRange,[n,o]=a.localPageRange;if(e>r&&t.push(`${a.chapterId}: invalid globalPageRange [${e},${r}]`),n>o&&t.push(`${a.chapterId}: invalid localPageRange [${n},${o}]`),r-e!==o-n&&t.push(`${a.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-n+1})`),a.ownedGlobalPages)for(const s of a.ownedGlobalPages)(s<e||s>r)&&t.push(`${a.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ko(a))}return t}(t);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const a=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of a)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=No(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=0;a<s;a++){const e=this.manifest.chapters[a].chapterId;this.chapterLastUsed.set(e,t);const s=this.chapterStatus.get(e)??"idle";"idle"!==s&&"closed"!==s&&"error"!==s||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Lo(t):null}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),a=this.documentManager.provides();if(!s)return 0===t&&a.isDocumentOpen(e);const r=s.segments[t];return!!r&&a.isDocumentOpen(r.documentId)}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"));const a=t.segments[0];if(a&&s.isDocumentOpen(a.documentId))return 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)}))return void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r&&"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),s=this.config.prefetchChapters??1,a=new Set,r=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Do(t,e.localPageIndex);r.add(`${e.chapterId}:${s}`),r.add(`${e.chapterId}:${s+1}`)}if(0===a.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of a){const e=n.indexOf(i);if(-1!==e)for(let t=e-s;t<=e+s;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of r){const[e,s]=i.split(":"),a=Number.parseInt(s,10);e&&Number.isFinite(a)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,a))}if(this.config.autoActivateOnLoad??1){const t=e[0],s=null!=t?this.virtualPageMap.atIndex(t):null;if(s){const e=$o(this.findChapter(s.chapterId),s.localPageIndex);if(this.documentManager.provides().isDocumentOpen(e.documentId)){this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,a]of this.chapterStatus){if("loaded"!==a)continue;t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.ensureSegmentLoaded(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const s=this.findChapter(e);if(!s)return Promise.resolve("error");const a=Lo(s);if(!a)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(s);if(t<0||t>=a.segments.length)return Promise.resolve("error");const r=a.segments[t],n=r.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(s,r).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const a=this.chapterStatus.get(t)??"idle";if("loaded"===a)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===a)return this.waitForTerminalStatus(t);const r=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,r),r}async resolvePdfPayload(e,t){const s=e.source;if(s){if(yo(s)){const a=s.urls[t];if(!a)throw new Error(`Chapter "${e.chapterId}" missing source.urls[${t}]`);return{url:a}}if(0!==t)throw new Error(`Chapter "${e.chapterId}" is not segmented`);if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e,t);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoadSegment(t,s){var a;const r=t.chapterId,n=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??r;0===n&&this.updateStatus(r,"loading"),this.chapterLastUsed.set(r,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(r):null,i=await this.resolvePdfPayload(t,n),l=this.documentManager.provides(),d="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}),h=await new Promise((e,t)=>{d.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{h.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(r),this.waitForTerminalStatus(r)}catch(i){const t=this.chapterStatus.get(r);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${r}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(r,"error",t)}return this.chapterStatus.get(r)??"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 a=null;a=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==a||a(),a=null)})})}async handleDocumentError(t,s,r,n){if(r!==a.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:a}=xo(t);return void(e&&0!==a&&null!==a||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const o=this.findChapter(s);if(!o)return;const i=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(d){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,d)}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(),a=t?Lo(t):null,r=e=>{if(s.isDocumentOpen(e)){s.closeDocument(e).wait(()=>{},()=>{})}};if(a)for(const n of a.segments)r(n.documentId);else r(e);this.updateStatus(e,"closed")}updateStatus(e,t,s){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ao.id="chapter-manager";let zo=Ao;function Fo(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}:{},...e.encrypted?{encrypted:e.encrypted}:{}}}function Go(e){const t=[],s=e=>{var a;for(const r of e)t.push(Fo(r)),(null==(a=r.children)?void 0:a.length)&&s(r.children)};return s(e),t}function Vo(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)?Vo(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:()=>y.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=V,exports.ChapterManagerPlugin=zo,exports.ChapterPdfViewer=pr,exports.ChapterTreePanel=ur,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=ss,exports.PdfChapterViewport=Xa,exports.applySelectionMarkup=O,exports.buildChapterViewerCatalog=function(e){return{tree:Vo(e),manifest:{chapters:Go(e)}}},exports.buildParagraphBookmarkAnchor=Wt,exports.chapterAnnotationsArchiveToJson=bo,exports.chapterAnnotationsSnapshotToJson=Co,exports.chapterDescriptorFromTreeNode=Fo,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=is,exports.createChapterViewerEditor=as,exports.createChapterViewerEditorOptions=function(e){const{features:t,...s}=os(ns(e));return s},exports.createPdfChapterEditor=es,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){So(t,bo(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){So(t??`chapter-annotations-${e.chapterId}.json`,Co(e))},exports.downloadJsonFile=So,exports.exportAllChapterAnnotations=async function(e,t,s){const a={};for(const r of t.chapters){const t=await Po(e,r.chapterId,s),{chapterId:n,...o}=t;a[r.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:a}},exports.exportChapterAnnotations=Po,exports.flattenChapterTree=Go,exports.importChapterAnnotations=Io,exports.importChapterAnnotationsArchive=async function(e,t,s){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[a,r]of Object.entries(t.chapters))await Io(e,{chapterId:a,...r},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=Vo;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),r=require("@embedpdf/plugin-annotation"),s=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),o=require("@embedpdf/plugin-interaction-manager"),i=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),d=require("@embedpdf/plugin-history"),c=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),f=require("@embedpdf/plugin-commands"),m=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),P=require("@embedpdf/plugin-interaction-manager/vue"),I=require("@embedpdf/plugin-rotate/vue"),C=require("@embedpdf/plugin-selection/vue"),b=require("@embedpdf/plugin-annotation/vue"),w=require("@embedpdf/plugin-redaction/vue"),S=require("@embedpdf/plugin-render/vue"),y=require("@embedpdf/engines/vue"),M={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function $(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const L="#f1f5f9",D={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},k={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.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 T(e){let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),r=Math.min(r,a.origin.y),s=Math.max(s,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:n-r}}}function E(e,t,n,a,o){const i=n.forDocument(e),l=a.forDocument(e);if(!i||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=n.getTool(h);if(!d)return!1;const c=d.defaults,u={...D[g=t],...null==(f=o)?void 0:f[g]},p=l.getFormattedSelection();var g,f;if(0===p.length)return!1;i.setLocked({type:r.LockModeType.Exclude,categories:["markup","shape"]});for(const r of p){const e=s.uuidV4(),n=u.color??c.color??c.strokeColor,a=u.opacity??c.opacity,o=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(r.segmentRects,l):r.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?T(h):r.rect;i.createAnnotation(r.pageIndex,{id:e,created:new Date,flags:["print"],type:k[t],..."highlight"===t?{blendMode:s.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=o?{strokeWidth:o}:{},pageIndex:r.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}const A=new Set([s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT]);function F(e,t){const r=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...r,enabled:!1!==(null==r?void 0:r.enabled)}}function N(e){var t;const r=F(null==e?void 0:e.markup,{enabled:!0}),s=F(null==e?void 0:e.bookmarks,{enabled:!0}),n=F(null==e?void 0:e.notes,{enabled:!0}),a=F(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),o=F(void 0===(null==e?void 0:e.selectionToolbar)?!1!==r.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:r,bookmarks:s,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??L},selectionToolbar:o}}function O(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function z(e,t){return`${e}#s${t}`}function G(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return O(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=O(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:z(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}let R=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const V="chapter-manager",_={id:V,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function B(e){const[t,r]=e.localPageRange;return r-t+1}function q(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function H(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return q(t)?t.segmentPageThreshold:null}function W(e,t){return`${e}#s${t}`}function j(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Y(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Z(e){const t=H(e);if(!t)return null;const r=B(e),s=Y(r,t),n=q(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:W(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function K(e,t){const r=Z(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function J(e,t){const r=Z(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function X(e){var t;const r=H(e);if(!r)return[];const s=[],{chapterId:n}=e,a=B(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!q(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Y(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Q={kind:"first-wins"};function ee(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const re=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.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],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}=j(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=j(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=j(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?K(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Z(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...X(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Q){const r=function(e,t=Q){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,ee(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new te(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Z(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=J(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=K(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Z(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(q(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=H(t);if(a){const s=Y(B(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(q(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=j(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Z(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};re.id="chapter-manager";let se=re;const ne={manifest:_,create:e=>new se(V,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",oe={id:ae,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}};function ie(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 r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function de(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ie(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=ie(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ce(e){const[t,r]=e.localPageRange;return r-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 fe(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function me(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ve(e){const t=pe(e);if(!t)return null;const r=ce(e),s=me(r,t),n=ue(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ge(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Pe(e,t){const r=ve(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Ie(e,t){const r=ve(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ce(e){var t;const r=pe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ce(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ue(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=me(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const be={kind:"first-wins"};function we(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Se=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const ye=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.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],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}=fe(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=fe(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=fe(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Pe(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ve(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ce(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=be){const r=function(e,t=be){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,we(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Se(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ve(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Ie(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Pe(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ve(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ue(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=pe(t);if(a){const s=me(ce(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ue(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=fe(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ve(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};ye.id="chapter-manager";let Me=ye;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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const $e=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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Me.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=de(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=de(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=he(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};$e.id="chapter-scroll";let Le=$e;const De={manifest:oe,create:e=>new Le(ae,e),reducer:e=>e,initialState:{}},ke="note",Ue={id:ke,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 Te(e){const[t,r]=e.localPageRange;return r-t+1}function Ee(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ae(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ee(t)?t.segmentPageThreshold:null}function Fe(e,t){return`${e}#s${t}`}function Ne(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Oe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ze(e){const t=Ae(e);if(!t)return null;const r=Te(e),s=Oe(r,t),n=Ee(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Fe(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ge(e,t){const r=ze(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Re(e,t){const r=ze(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ve(e){var t;const r=Ae(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Te(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Ee(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Oe(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const _e={kind:"first-wins"};function Be(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let qe=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const He=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=_e,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??_e,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ne(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ne(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ne(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Ge(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ze(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ve(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=_e){const r=function(e,t=_e){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Be(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new qe(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ze(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Re(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Ge(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ze(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Ee(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Ae(t);if(a){const s=Oe(Te(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Ee(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Ne(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ze(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};He.id="chapter-manager";let We=He;function je(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ye(e,t){return`${e}#s${t}`}function Ze(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ke(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return je(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=je(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ye(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Je(e){const[t,r]=e.localPageRange;return r-t+1}function Xe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Qe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xe(t)?t.segmentPageThreshold:null}function et(e,t){return`${e}#s${t}`}function tt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function rt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function st(e){const t=Qe(e);if(!t)return null;const r=Je(e),s=rt(r,t),n=Xe(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:et(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function nt(e,t){const r=st(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function at(e,t){const r=st(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function ot(e){var t;const r=Qe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Je(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Xe(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=rt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const it={kind:"first-wins"};function lt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let ht=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const dt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=it,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??it,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=tt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=tt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=tt(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?nt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?st(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ot(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=it){const r=function(e,t=it){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,lt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ht(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?st(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=at(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=nt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=st(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Xe(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Qe(t);if(a){const s=rt(Je(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Xe(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=tt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?st(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};dt.id="chapter-manager";let ct=dt;function ut(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const pt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ut),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ct.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Ke(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=Ze(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Ze(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Ke(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=Ze(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};pt.id="chapter-scroll";let gt=pt;const ft=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(gt.id),this.chapterManager=this.registry.getPlugin(We.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:vt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};ft.id="note";let mt=ft;function vt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const Pt={manifest:Ue,create:e=>new mt(ke,e),reducer:e=>e,initialState:{}},It="paragraph-bookmark",Ct={id:It,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function bt(e){const[t,r]=e.localPageRange;return r-t+1}function wt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function St(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wt(t)?t.segmentPageThreshold:null}function yt(e,t){return`${e}#s${t}`}function Mt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function xt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function $t(e){const t=St(e);if(!t)return null;const r=bt(e),s=xt(r,t),n=wt(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:yt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Lt(e,t){const r=$t(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Dt(e,t){const r=$t(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function kt(e){var t;const r=St(e);if(!r)return[];const s=[],{chapterId:n}=e,a=bt(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!wt(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=xt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ut={kind:"first-wins"};function Tt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Et=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const At=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ut,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ut,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Mt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Mt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Mt(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Lt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?$t(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...kt(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Ut){const r=function(e,t=Ut){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Tt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Et(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?$t(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Dt(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Lt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=$t(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(wt(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=St(t);if(a){const s=xt(bt(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(wt(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Mt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?$t(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};At.id="chapter-manager";let Ft=At;function Nt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ot(e,t){return`${e}#s${t}`}function zt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Gt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Nt(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Nt(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ot(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Rt(e){const[t,r]=e.localPageRange;return r-t+1}function Vt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function _t(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Vt(t)?t.segmentPageThreshold:null}function Bt(e,t){return`${e}#s${t}`}function qt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ht(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Wt(e){const t=_t(e);if(!t)return null;const r=Rt(e),s=Ht(r,t),n=Vt(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Bt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function jt(e,t){const r=Wt(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Yt(e,t){const r=Wt(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Zt(e){var t;const r=_t(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Rt(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Vt(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ht(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Kt={kind:"first-wins"};function Jt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Xt=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Qt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Kt,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Kt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=qt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=qt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=qt(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?jt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Wt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Zt(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Kt){const r=function(e,t=Kt){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Jt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Xt(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Wt(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Yt(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=jt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Wt(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Vt(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=_t(t);if(a){const s=Ht(Rt(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Vt(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=qt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Wt(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Qt.id="chapter-manager";let er=Qt;function tr(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const rr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,tr),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(er.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Gt(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=zt(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=zt(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Gt(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=zt(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};rr.id="chapter-scroll";let sr=rr;function nr(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),r=Math.min(r,a.origin.y),s=Math.max(s,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:n-r}}}function ar(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function or(e,t){const r=e.origin.y,s=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,o=Math.max(s,a)-Math.min(r,n);return o<=0?0:Math.max(0,Math.min(s,a)-Math.max(r,n))/o}function ir(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??ar(n),i=t.markerAnchor??ar(a);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of n)for(const e of a){if(or(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 lr(e,t,r,s){const n=r.length>0?r:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:nr(n),rectsPdfCoord:n,markerAnchor:ar(n)}}const hr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(sr.id),this.chapterManager=this.registry.getPlugin(Ft.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var r;if(this.config=t,null==(r=t.callbacks)?void 0:r.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(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}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 s of this.entries.values())if(ir(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,r),this.notifyAndPersist(),r}removeBookmark(e){var t,r,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.onRemoveSuccess)||s.call(r,e))}async requestRemoveBookmark(t){var r,s;const n=this.entries.get(t);if(!n)return!1;const a=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const r=this.entries.get(e);r&&(this.entries.set(e,{...r,...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[r,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(r);for(const r of t)r.anchor.chapterId===e&&this.entries.set(r.id,r);this.notifyAndPersist()}notifyAndPersist(){var t,r;const s=this.list();this.change$.emit(s),(null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.persist)&&Promise.resolve(this.config.callbacks.persist(s)).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 r=this.chapterScroll.provides(),s=this.chapterManager.provides();await s.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,r){e.scrollToGlobalPageIndex(t),await function(e,t,r=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const n=setTimeout(()=>{a(),s(null)},r),a=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(n),a(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,n,a)}};hr.id="paragraph-bookmark";let dr=hr;const cr={manifest:Ct,create:e=>new dr(It,e),reducer:e=>e,initialState:{}},ur={"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 pr{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(ur);for(const t of this.specs){const r=e[t.toolbarSlot];if(!r)continue;const s={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??[]};r.items=gr(r.items,s,t.position)}return e}}function gr(e,t,r){return(null==r?void 0:r.after)||(null==r?void 0:r.before)?function(e,t,r){const s=e=>{const n=[];for(const a of e)"group"!==a.type?r.before&&a.id===r.before?n.push(t,a):(n.push(a),r.after&&a.id===r.after&&n.push(t)):n.push({...a,items:s(a.items)});return n};return s(e)}(e,t,r):(s=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,s]}:e));var s}const fr={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function mr(e){var t,s,P,I,C,b;const w=e.toolbar??{},S=w.enabledModes??["view","annotate","shapes","insert","form","redact"],y=S.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,r,s,n,a,o;const i=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new pr;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of i){if("view"===u)continue;const e=fr[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,r)=>({type:"command-button",id:`${e}-mode`,commandId:r,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}]}}(i);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(r=e.extend)?void 0:r.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=e.extend)?void 0:s.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(o=e.extend)?void 0:o.selectionMenus)??{}},operationRegistry:l}}({...w,enabledModes:S}),$={...y?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var s,n,a,o;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();i&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),i.forDocument(t).closeToolbarSlot("top","secondary"),null==(o=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||o.provides().forDocument(t).setLocked(e.getPluginConfig(r.ANNOTATION_PLUGIN_ID).locked??{type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...y?vr(x.list()):{},...e.commands??{}},L=[n.createPluginRegistration(a.DocumentManagerPluginPackage,{initialDocuments:[]}),n.createPluginRegistration(ne,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),n.createPluginRegistration(De,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(o.InteractionManagerPluginPackage),n.createPluginRegistration(i.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(d.HistoryPluginPackage),n.createPluginRegistration(r.AnnotationPluginPackage),n.createPluginRegistration(c.RedactionPluginPackage),n.createPluginRegistration(u.FormPluginPackage),n.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),n.createPluginRegistration(g.SignaturePluginPackage),...Object.keys($).length>0?[n.createPluginRegistration(f.CommandsPluginPackage,{commands:$})]:[],...y?[n.createPluginRegistration(m.I18nPluginPackage),n.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&L.push(n.createPluginRegistration(Pt,{callbacks:e.notes.callbacks,ui:null==(s=null==(t=e.features)?void 0:t.notes)?void 0:s.marker})),e.bookmarks&&L.push(n.createPluginRegistration(cr,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(b=null==(C=e.features)?void 0:C.bookmarks)?void 0:b.hover})),{plugins:L,uiSchema:M,operationRegistry:x}}function vr(e){const t={};for(const r of e)r.handler&&(t[r.commandId]={id:r.commandId,labelKey:r.i18nKey,label:r.label,icon:r.icon,categories:r.categories,action:({documentId:e})=>{var t;null==(t=r.handler)||t.call(r,{documentId:e,chapterId:e})}});return t}const Pr=N();function Ir(e){return mr({...e,toolbar:e.toolbar??{enabledModes:[]},features:N(e.features)})}const Cr={overlapStrategy:{kind:"first-wins"},passwordProvider:new R(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function br(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function wr(e){return{...Cr,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Cr.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:N(e.features)}}function Sr(e){const t=wr(br(e)),{plugins:r}=Ir(t);return{plugins:r,features:t.features,editorOptions:t}}function yr(e,t=.5,r=3){return Math.min(r,Math.max(t,e))}function Mr(e,t){var r;if(t<=0)return 1;let s=0;for(const n of e.pages){const e=(null==(r=null==n?void 0:n.size)?void 0:r.width)??0;e>s&&(s=e)}return s<=0?1:t/s}function xr(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function $r(e,t,r,s){const n=xr(t,r);if(n<=0)return s;const a=Mr(e,n);return Math.min(s,a)}function Lr(e,t,r){const s=G(t);if(s){for(const t of s.segments){const s=e.getDocument(t.documentId);s&&r(s,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&r(n,t.chapterId)}function Dr(e){return e instanceof HTMLElement?e.clientWidth:0}function kr(e,t,r){return Math.min(r,Math.max(t,e))}const Ur={chapters:[]};function Tr(r){const s=e.ref(null),{provides:o}=t.useCapability(se.id),i=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??Ur}),l=e.computed(()=>{var e;return null==(e=r.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(r,s,o){const i=e.isRef(r)?r:e.computed(()=>r),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:d}=t.useCapability(se.id),c=e.ref(m()),u=e.ref(c.value),p=e.ref(0),g=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth},f=()=>{return null!=(e=g())&&e>0;var e},m=()=>{var e;return(null==(e=s.value)?void 0:e.initial)??1},v=e.computed(()=>{var e;return function(e,t,r,s,n){if(!e||r<=0)return n;let a=n;for(const o of t.chapters)Lr(e,o,e=>{a=Math.min(a,$r(e,r,s,n))});return a}(h.value,i.value,p.value,g(),(null==(e=s.value)?void 0:e.max)??3)}),P=e.computed(()=>{var e;return Math.min((null==(e=s.value)?void 0:e.min)??.5,v.value)});let I;function C(e){const t=v.value,r=P.value,s=yr(e,r,t);u.value=s,c.value=s,function(e,t,r,s=.5,a=3){const o=null==e?void 0:e.getStore();if(!o)return;const i=yr(r,s,a);o.dispatchToCore(n.setDefaultScale(i));for(const l of t.chapters){const e=G(l);if(e)for(const t of e.segments)o.getState().core.documents[t.documentId]&&o.dispatchToCore(n.setScale(i,t.documentId));else o.getState().core.documents[l.chapterId]&&o.dispatchToCore(n.setScale(i,l.chapterId))}}(l.value,i.value,s,r,t)}function b(e){if(!h.value||!d.value)return;const t=d.value.resolvePageDocument(e,0),r=h.value.getDocument(t.documentId);if(!r)return;const s=xr(p.value,g());s<=0||C(Mr(r,s))}function w(e){f()?b(e):C(m())}return e.watch(()=>null==o?void 0:o.value,e=>{null==I||I(),I=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let r=null;const s=new ResizeObserver(()=>{t(Dr(r))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==r?(r&&s.unobserve(r),r=n,r?(s.observe(r),t(Dr(r))):t(0)):t(Dr(r))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const o=requestAnimationFrame(n);return()=>{cancelAnimationFrame(o),a.disconnect(),r&&s.unobserve(r),s.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==I?void 0:I()),e.watch([l,()=>m(),()=>f()],()=>{l.value&&(f()||C(m()))},{immediate:!0}),e.watch(v,e=>{u.value>e&&C(e)}),e.watch([d,i,()=>f(),()=>m()],()=>{const e=d.value;if(e){for(const t of i.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&w(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&w(e.chapterId)})}},{immediate:!0}),e.watch([p,()=>f(),d,i],()=>{if(f()&&!(p.value<=0)&&d.value)for(const e of i.value.chapters)if("loaded"===d.value.getChapterStatus(e.chapterId)){b(e.chapterId);break}}),{scale:c,setScale:C,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:P,maxZoom:v}}(i,l,s);return function(t,r){let s=null;e.watch([t,r],()=>{null==s||s();const e=r.value;s=function(e,t){if(!e||!1===t.enabled)return()=>{};let r=null,s=null,n=0;const a=()=>{const s=e.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==r||r(),r=function({container:e,getScale:t,setScale:r,minZoom:s=.5,maxZoom:n=3}){let a=0,o=1,i=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===i?(h=t(),l=1):clearTimeout(i),l*=1-.01*e.deltaY,l=kr(l,.1,10),r(kr(h*l,s,n)),i=setTimeout(()=>{i=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,r]=[...c.values()];a=Math.hypot(r.x-e.x,r.y-e.y),o=t()}},p=e=>{if(c.has(e.pointerId)&&(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size&&a>0)){e.preventDefault();const[t,i]=[...c.values()],l=Math.hypot(i.x-t.x,i.y-t.y);r(kr(o*(l/a),s,n))}},g=e=>{c.delete(e.pointerId),c.size<2&&(a=0)};return e.addEventListener("wheel",d,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",d),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),i&&clearTimeout(i)}}({container:s,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(s=new MutationObserver(()=>{a()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==s||s.disconnect(),null==r||r()}}(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==s?void 0:s())}(s,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u.value,maxZoom:p.value}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}function Er(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ar(e,t){return`${e}#s${t}`}function Fr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Nr(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Er(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Er(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ar(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Or(e){const[t,r]=e.localPageRange;return r-t+1}function zr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Gr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zr(t)?t.segmentPageThreshold:null}function Rr(e,t){return`${e}#s${t}`}function Vr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function _r(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Br(e){const t=Gr(e);if(!t)return null;const r=Or(e),s=_r(r,t),n=zr(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Rr(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function qr(e,t){const r=Br(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Hr(e,t){const r=Br(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Wr(e){var t;const r=Gr(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Or(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!zr(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=_r(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const jr={kind:"first-wins"};function Yr(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Kr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=jr,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??jr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Vr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Vr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Vr(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?qr(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Br(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Wr(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=jr){const r=function(e,t=jr){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Yr(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Zr(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Br(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Hr(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=qr(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Br(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(zr(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Gr(t);if(a){const s=_r(Or(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(zr(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Vr(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Br(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Kr.id="chapter-manager";let Jr=Kr;function Xr(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const Qr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Xr),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Jr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Nr(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=Fr(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Fr(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Nr(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=Fr(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Qr.id="chapter-scroll";let es=Qr;const ts=["data-global-page-index","data-chapter-id","data-local-page-index"],rs=(e=>{const t=e.__vccOpts||e;for(const[r,s]of[["__scopeId","data-v-e9ab4da3"]])t[r]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(r){const{provides:s}=t.useCapability(es.id),n=e.ref(null),a=e.ref(null);let o=null;const i=()=>{null==o||o(),o=null,s.value&&(s.value.registerViewport(n.value),o=s.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(i),e.onBeforeUnmount(()=>{var e;null==o||o(),null==(e=s.value)||e.registerViewport(null)}),e.watch(s,i),(t,r)=>{var s,o,i;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==(s=a.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(o=a.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(i=a.value)?void 0:i.items)??[],s=>(e.openBlock(),e.createElementBlock("div",{key:s.globalPageIndex,"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:s.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[s.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:s},()=>[r[0]||(r[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:s},void 0,!0)],12,ts))),128))],4)],6)}}})),ss=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const r=t;return(s,n)=>(e.openBlock(),e.createBlock(e.unref(S.RenderLayer),{"document-id":r.pdfDocumentId??r.chapterId,"page-index":r.pdfPageIndex??r.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 ns(e){const[t,r]=e.localPageRange;return r-t+1}function as(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function os(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return as(t)?t.segmentPageThreshold:null}function is(e,t){return`${e}#s${t}`}function ls(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function hs(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ds(e){const t=os(e);if(!t)return null;const r=ns(e),s=hs(r,t),n=as(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:is(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function cs(e,t){const r=ds(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function us(e,t){const r=ds(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function ps(e){var t;const r=os(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ns(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!as(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=hs(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const gs={kind:"first-wins"};function fs(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let ms=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const vs=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=gs,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??gs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ls(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ls(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ls(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?cs(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ds(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ps(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=gs){const r=function(e,t=gs){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,fs(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ms(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ds(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=us(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=cs(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ds(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(as(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=os(t);if(a){const s=hs(ns(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(as(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ls(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ds(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};vs.id="chapter-manager";let Ps=vs;function Is(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Cs(e,t){return`${e}#s${t}`}function bs(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function ws(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Is(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Is(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Cs(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ss(e){const[t,r]=e.localPageRange;return r-t+1}function ys(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ms(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ys(t)?t.segmentPageThreshold:null}function xs(e,t){return`${e}#s${t}`}function $s(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ls(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ds(e){const t=Ms(e);if(!t)return null;const r=Ss(e),s=Ls(r,t),n=ys(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:xs(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ks(e,t){const r=Ds(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Us(e,t){const r=Ds(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ts(e){var t;const r=Ms(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ss(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ys(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ls(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Es={kind:"first-wins"};function As(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class Fs{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Ns=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Es,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Es,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=$s(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=$s(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=$s(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?ks(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ds(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ts(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Es){const r=function(e,t=Es){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,As(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Fs(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ds(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Us(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=ks(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Ds(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ys(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Ms(t);if(a){const s=Ls(Ss(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ys(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=$s(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Ds(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ns.id="chapter-manager";let Os=Ns;function zs(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const Gs=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,zs),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Os.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=ws(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=bs(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=bs(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=ws(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=bs(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Gs.id="chapter-scroll";let Rs=Gs;const Vs=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(Rs.id),this.chapterManager=this.registry.getPlugin(Ps.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Bs(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};Vs.id="note";let _s=Vs;function Bs(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function qs(e){const{markerPdf:t,lineRects:r,sx:s,sy:n,cssPageWidth:a,iconSize:o,gapPx:i=6}=e,l=(null==r?void 0:r.length)?r[r.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*s+i,d=l.origin.y*n+(l.size.height*n-o)/2):(h=t.x*s-o/2,d=t.y*n-o-i);const c=Math.max(0,a-o-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const Hs={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Ws=["onMouseenter"],js=["data-note-marker-zone","onMouseenter","onMouseleave"],Ys=["onClick"],Zs=["onClick"],Ks=["onClick"],Js=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:n}=t.useCapability(_s.id),a=e.ref([]),o=e.ref(null),i=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===s.chapterId&&e.localPageIndex===s.localPageIndex)})},{immediate:!0});let l=null;e.watch(i,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var r;const s=t.target;(null==(r=s.closest)?void 0:r.call(s,`[data-note-marker-zone="${e}"]`))||(i.value=null,o.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,n=h.value,{left:a,top:o}=qs({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:r,cssPageWidth:s.cssPageWidth,iconSize:n}),l=function(e,t,r){let s=1/0,n=1/0,a=-1/0,o=-1/0;for(const i of e)s=Math.min(s,i.origin.x*t),n=Math.min(n,i.origin.y*r),a=Math.max(a,(i.origin.x+i.size.width)*t),o=Math.max(o,(i.origin.y+i.size.height)*r);return{left:s,top:n,width:a-s,height:o-n}}(e.rectsPdfCoord,t,r),d=i.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,o)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(s.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-c,zoneH:Math.max(l.top+l.height,o+n+6+d)+8-u,iconLeft:a,iconTop:o,sx:t,sy:r}}return(t,s)=>e.unref(n)&&a.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Hs,[(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,(r,s)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${s}`,style:e.normalizeStyle({position:"absolute",left:r.origin.x*c(t).sx+"px",top:r.origin.y*c(t).sy+"px",width:r.size.width*c(t).sx+"px",height:r.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>o.value=t.noteId},null,44,Ws))),128)),o.value===t.noteId||i.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${c(t).zoneLeft}px`,top:`${c(t).zoneTop}px`,width:`${c(t).zoneW}px`,height:`${c(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>o.value=t.noteId,onMouseleave:e=>i.value!==t.noteId&&(o.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:c(t).iconTop-c(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:s[0]||(s[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>i.value=i.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Ys),i.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:`${c(t).iconTop-c(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:s[1]||(s[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 r=t,void(null==(s=n.value)||s.requestEditNote(r.noteId,r));var r,s}}," 编辑 ",8,Zs),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 r,s;return s=t.noteId,null==(r=n.value)||r.requestDeleteNote(s),void(i.value=null)}}," 删除 ",8,Ks)],36)):e.createCommentVNode("",!0)],44,js)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Xs={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Qs=["title","onClick"],en=["onClick"],tn=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:n}=t.useCapability(dr.id),a=e.ref([]),o=e.ref(null),i=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(o,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=i.value)?void 0:t.contains(e.target))||(o.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:r}=function(e){var t;const r=s.cssPageWidth/s.pdfPageWidth,n=s.cssPageHeight/s.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return qs({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:r,sy:n,cssPageWidth:s.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,r-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,s)=>e.unref(n)&&a.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Xs,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(c(t)),onMousedown:s[1]||(s[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${d.value}px`,height:`${d.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=>o.value=o.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Qs),o.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:i,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:s[0]||(s[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)&&(o.value=null)}(t.id)}," 删除书签 ",8,en)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function rn(e){return e.pdfDocumentId??e.chapterId}function sn(e){return e.pdfPageIndex??e.localPageIndex}function nn(e,t){e.wait(t,()=>{})}const an={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)"},on={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const ln=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(r){const s=r,n=e.computed(()=>rn(s.item)),o=e.computed(()=>sn(s.item));!function(r){const{provides:s}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([s,r],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:i}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),d=e.computed(()=>{var e,t;return null==(t=null==(e=i.value)?void 0:e.getDocument(n.value))?void 0:t.pages[o.value]});function c(t,r){var n,a,o,i;const h=s.createNote.value;if(h&&!1!==(null==(a=null==(n=s.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(i=null==(o=s.features)?void 0:o.selectionToolbar)?void 0:i.enabled))return s=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=s.placement)?void 0:n.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.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(sn(t),r);nn(l.value.getSelectedText(r),r=>{var s,n,a;h((s=t,n=e,a=r.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:c(s.item,n.value),createNote:s.createNote.value};if(e){const r=e(t);if(r)return r}return t.defaultMenu}),p=function(t,r){var s,n;const{provides:a}=b.useAnnotationCapability(),o=null==(s=null==r?void 0:r.markup)?void 0:s.annotationMenu,i=!1!==(null==(n=null==r?void 0:r.markup)?void 0:n.enabled),l=!1!==(null==o?void 0:o.enabled);return e.computed(()=>{const r="string"==typeof t?t:t.value;if(i&&l&&a.value)return t=>{const{context:s,rect:n,placement:i,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==s.type)return e.h("span",l);if(s.structurallyLocked)return e.h("span",l);if(d=s.annotation.object.type,!A.has(d))return e.h("span",l);var d;const c=a.value.forDocument(r),{pageIndex:u,id:p}=s.annotation.object,g=()=>{null==c||c.deleteAnnotation(u,p)},f={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==i?void 0:i.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==i?void 0:i.suggestTop)?`${n.size.height+8}px`:void 0},m=(null==o?void 0:o.renderMenu)?o.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:on,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:f},[e.h("div",{style:an,role:"toolbar","aria-label":"划线标注"},[m])])])}})}(n,s.features),g=e.computed(()=>function(e,t){if(e||t)return r=>{if(e){const t=e(r);if(null!=t)return t}return(null==t?void 0:t(r))??null}}(s.annotationSelectionMenu,p.value)),f=e.computed(()=>{var e;return null==(e=s.renderPageOverlay)?void 0:e.call(s,s.item)}),m=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=s.features)?void 0:e.selectionToolbar)});return(t,s)=>r.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":o.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":o.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref($)},{default:e.withCtx(()=>[e.createVNode(e.unref(ss),{"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":o.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(C.SelectionLayer),{"document-id":n.value,"page-index":o.value,"text-style":m.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),r.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(w.RedactionLayer),{key:0,"document-id":n.value,"page-index":o.value,"selection-menu":r.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(b.AnnotationLayer),{"document-id":n.value,"page-index":o.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),r.showBookmarkMarkers&&d.value?(e.openBlock(),e.createBlock(tn,{key:1,"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":r.item.width,"css-page-height":r.item.height,ui:r.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),f.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(f.value),{key:2})):e.createCommentVNode("",!0),r.showNoteMarkers&&d.value?(e.openBlock(),e.createBlock(Js,{key:3,"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":r.item.width,"css-page-height":r.item.height,ui:r.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"]))}}),hn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(r){const s=r,n=e.computed(()=>rn(s.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(dr.id),i=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=s.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??d.value);let g=null,f=0;function m(){const e=a.value;if(!e)return;const t=e.forDocument(n.value).getState().geometry[s.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>s.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(f),l.value=null,!e)return;const t=e.forDocument(n.value);g=t.onSelectionChange(m);let r=!1;const a=()=>{if(!r){try{if(m(),t.getState().geometry[s.item.localPageIndex])return}catch{}f=requestAnimationFrame(a)}};return a(),()=>{r=!0,cancelAnimationFrame(f),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.pdfPageWidth&&(v=e=>{if(c.value)return;const t=a.value;if(t)try{if(t.forDocument(n.value).getState().selecting)return void(d.value=null)}catch{}const r=i.value;if(!r)return;const o=r.getBoundingClientRect();if(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)return void(d.value=null);const u=function(e,t){const r=h.glyphAt(e,t);if(r<0)return null;const s=h.expandToLineBoundary(e,r);if(!s)return null;const n=h.rectsWithinSlice(e,s.from,s.to);return 0===n.length?null:{lineRects:n,charFrom:s.from,charTo:s.to}}(l.value,{x:(e.clientX-o.left)/(s.cssPageWidth/s.pdfPageWidth),y:(e.clientY-o.top)/(s.cssPageHeight/s.pdfPageHeight)});d.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(f),null==g||g()});const P=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?lr(s.item.chapterId,s.item.localPageIndex,e,{globalPageIndex:s.item.globalPageIndex,globalPageNumber:s.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=o.value;return!(!e||!t)&&t.listBookmarks().some(t=>ir(t.anchor,e))});function C(){const e=o.value,t=P.value;e&&t&&!I.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),d.value=null,c.value=null)}const b=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!s.pdfPageWidth)return null;const r=s.cssPageWidth/s.pdfPageWidth,n=s.cssPageHeight/s.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*r+6,Math.max(0,s.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*r-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,s)=>{var n;return e.unref(o)&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:i,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)*(r.cssPageHeight/r.pdfPageHeight)+b.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:s[0]||(s[0]=e=>c.value=p.value),onMouseleave:s[1]||(s[1]=e=>c.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(C,["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":""},cn={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},un={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},pn={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},gn={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"},fn={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},mn={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},vn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(r,s)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",dn,[...s[0]||(s[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",cn,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",un)):e.createCommentVNode("",!0),s[1]||(s[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",pn)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",gn)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",fn)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",mn,[...s[2]||(s[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)])]))}),Pn=["title","aria-label","onMouseenter","onClick"],In=["title","onMouseenter","onClick"],Cn={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:r}){const s=t,n=r,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),i=e.computed(()=>!o.value.has("copy")),l=e.computed(()=>a.filter(e=>!o.value.has(e.id))),h=e.computed(()=>!o.value.has("note")),d=e.computed(()=>[...s.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),c=e.computed(()=>l.value.length>0||d.value.length>0),u=e.ref(null),p=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:s.placementAbove?void 0:`${s.anchorHeight+10}px`,bottom:s.placementAbove?`${s.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 f={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(r,s)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[i.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:s[0]||(s[0]=e=>u.value="copy"),onMouseleave:s[1]||(s[1]=e=>u.value=null),onClick:s[2]||(s[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(vn,{key:1,kind:"copy"}))],36),c.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:f,"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:s[3]||(s[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(vn,{kind:t.id},null,8,["kind"])],44,Pn))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.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:s[4]||(s[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",Cn,e.toDisplayString(t.label.slice(0,2)),1)],44,In))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||i.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:f,"aria-hidden":""})):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(g("note",!0)),onMouseenter:s[5]||(s[5]=e=>u.value="note"),onMouseleave:s[6]||(s[6]=e=>u.value=null),onClick:s[7]||(s[7]=e=>n("action","note"))},[e.createVNode(vn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),wn={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},Sn=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(s){const n=s,o=e.computed(()=>n.features),{hostRef:i}=Tr(o),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=n.features)?void 0:e.scrollViewport)?void 0:t.background)??L}}),d=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e,t,s;const n=null==(s=null==(t=null==(e=r.value)?void 0:e.getPlugin(mt.id))?void 0:t.provides)?void 0:s.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),c=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=r.value)?void 0:e.getPlugin(mt.id))})}(),u=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=r.value)?void 0:e.getPlugin(dr.id))})}(),p=e.computed(()=>{var e,t;return n.showNoteMarkers&&c.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)}),f=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=function(s,n){const a=e.computed(()=>{var e;return null==(e=s())?void 0:e.selectionToolbar}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.markup)?void 0:t.enabled)}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?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:d}=t.useCapability(h.SelectionPlugin.id),{provides:c}=t.useCapability(r.AnnotationPlugin.id),{provides:u}=t.useCapability(mt.id);return e.computed(()=>{var t,r,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(o.value||i.value||l.value||(null==(h=null==(r=a.value)?void 0:r.extraActions)?void 0:h.length)))return t=>{const r=rn(t.item),h=sn(t.item);return p=>{var g,f,m,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==(f=a.value)?void 0:f.hiddenBuiltinActions,extraActions:null==(m=a.value)?void 0:m.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(!d.value||!u.value||!i.value)return;const e=d.value.getHighlightRectsForPage(h,r);return void nn(d.value.getSelectedText(r),r=>{var s;null==(s=u.value)||s.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:r.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!d.value||!c.value||!o.value)return;E(r,wn[e],c.value,d.value,null==(g=null==(p=s())?void 0:p.markup)?void 0:g.styles)}else{if(!d.value||!l.value)return;nn(d.value.getSelectedText(r),e=>{!async function(e){var t;const r=e.trim();if(!r)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(r),!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}catch{return!1}}(e.join("\n"))})}}}))}}})}(()=>n.features,{onExtraAction:n.onExtraSelectionAction}),v=e.computed(()=>{if(n.buildSelectionMenu||m.value)return e=>{const t=m.value?m.value(e):e.defaultMenu;return n.buildSelectionMenu?n.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(a.DocumentManagerPlugin.id);function I(t){var r;const s=[];if(f.value){const r=function(t){var r,s,a,o;const i=rn(t),l=sn(t),h=null==(s=null==(r=P.value)?void 0:r.getDocument(i))?void 0:s.pages[l];return t.isPlaceholder||!h?null:e.h(hn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(a=n.features)?void 0:a.bookmarks)?void 0:o.hover})}(t);r&&s.push(r)}const a=null==(r=n.renderPageOverlay)?void 0:r.call(n,t);if(a&&s.push(a),s.length)return e.h("div",s)}return(t,r)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:i,class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(rs),{class:e.normalizeClass(s.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var r,n,a,o;return[e.createVNode(ln,{item:t,features:s.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(n=null==(r=s.features)?void 0:r.notes)?void 0:n.marker,"bookmark-marker-ui":null==(o=null==(a=s.features)?void 0:a.bookmarks)?void 0:o.marker,"build-selection-menu":v.value,"create-note":e.unref(d),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.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))}}),yn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},Mn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(r){const s=r,n=e.computed(()=>function(e){if(e.options)return Sr(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=N(e.features),{plugins:r}=Ir({...e.editorOptions,features:t});return{plugins:r,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:s.engine,options:s.options,editorOptions:s.editorOptions,features:s.features}));return(s,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:r.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",yn,[e.renderSlot(s.$slots,"prepend"),e.createVNode(Sn,{class:e.normalizeClass(r.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":r.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(s.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),xn={class:"chapter-tree-row"},$n=["aria-expanded"],Ln={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Dn={class:"chapter-tree-label"},kn={class:"chapter-tree-meta"},Un={key:0},Tn=(e,t)=>{const r=e.__vccOpts||e;for(const[s,n]of t)r[s]=n;return r},En=Tn(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const r={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,n=e.computed(()=>s.node.children??[]),a=e.computed(()=>n.value.length>0),o=e.ref(s.depth<1),i=e.computed(()=>s.activeChapterId===s.node.id),l=e.computed(()=>s.chapterStatus[s.node.id]??"idle"),h=e.computed(()=>!a.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",xn,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":o.value,onClick:d[0]||(d[0]=e=>o.value=!o.value)},e.toDisplayString(o.value?"▼":"▶"),9,$n)):(e.openBlock(),e.createElementBlock("span",Ln)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":i.value}]),onClick:d[1]||(d[1]=e=>s.$emit("select",t.node.id))},[e.createElementVNode("div",Dn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",kn,[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",Un,e.toDisplayString(r[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&o.value?(e.openBlock(),e.createBlock(An,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>s.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),An=Tn(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(r,s)=>(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(En,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:s[0]||(s[0]=e=>r.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),Fn={class:"chapter-tree"},Nn={class:"chapter-tree-nav","aria-label":"章节目录"},On=Tn(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(r,{emit:s}){const n=r,a=s,{provides:o}=t.useCapability(Le.id),{provides:i}=t.useCapability(se.id),l=e.ref({});function h(){if(!i.value)return;const e={},t=r=>{var s;for(const n of r)e[n.id]=i.value.getChapterStatus(n.id),(null==(s=n.children)?void 0:s.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([i,()=>n.tree],h,{immediate:!0});let d=null;function c(e){var t;a("active-chapter-change",e),null==(t=o.value)||t.scrollToChapter(e)}return e.watch(i,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,s)=>(e.openBlock(),e.createElementBlock("aside",Fn,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Nn,[e.createVNode(An,{nodes:r.tree,depth:0,"active-chapter-id":r.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),zn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,r)=>(e.openBlock(),e.createBlock(e.unref(Mn),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 Gn(e){const[t,r]=e.localPageRange;return r-t+1}function Rn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Vn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Rn(t)?t.segmentPageThreshold:null}function _n(e,t){return`${e}#s${t}`}function Bn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function qn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Hn(e){const t=Vn(e);if(!t)return null;const r=Gn(e),s=qn(r,t),n=Rn(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:_n(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Wn(e,t){const r=Hn(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function jn(e,t){const r=Hn(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Yn(e){var t;const r=Vn(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Gn(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Rn(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=qn(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Zn={kind:"first-wins"};function Kn(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Jn=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Xn=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Zn,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Zn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Bn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Bn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Bn(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Wn(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Hn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Yn(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Zn){const r=function(e,t=Zn){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Kn(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Jn(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Hn(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=jn(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Wn(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Hn(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Rn(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Vn(t);if(a){const s=qn(Gn(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Rn(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Bn(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Hn(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Xn.id="chapter-manager";let Qn=Xn;function ea(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ta(e,t){return`${e}#s${t}`}function ra(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function sa(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ea(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=ea(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:ta(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function na(e){const[t,r]=e.localPageRange;return r-t+1}function aa(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 aa(t)?t.segmentPageThreshold:null}function ia(e,t){return`${e}#s${t}`}function la(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function ha(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function da(e){const t=oa(e);if(!t)return null;const r=na(e),s=ha(r,t),n=aa(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ia(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ca(e,t){const r=da(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function ua(e,t){const r=da(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function pa(e){var t;const r=oa(e);if(!r)return[];const s=[],{chapterId:n}=e,a=na(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!aa(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=ha(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const ga={kind:"first-wins"};function fa(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class ma{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const va=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ga,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ga,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=la(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=la(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=la(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?ca(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?da(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...pa(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=ga){const r=function(e,t=ga){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,fa(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ma(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?da(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=ua(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=ca(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=da(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(aa(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=oa(t);if(a){const s=ha(na(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(aa(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=la(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?da(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};va.id="chapter-manager";let Pa=va;function Ia(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}function Ca(e){const[t,r]=e.localPageRange;return r-t+1}function ba(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function wa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ba(t)?t.segmentPageThreshold:null}function Sa(e,t){return`${e}#s${t}`}function ya(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ma(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function xa(e){const t=wa(e);if(!t)return null;const r=Ca(e),s=Ma(r,t),n=ba(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Sa(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function $a(e,t){const r=xa(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function La(e,t){const r=xa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Da(e){var t;const r=wa(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ca(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ba(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ma(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ia),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Pa.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=sa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=ra(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=ra(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=sa(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=ra(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}}).id="chapter-scroll";const ka={kind:"first-wins"};function Ua(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Ta=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Ea=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ka,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ka,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ya(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ya(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ya(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?$a(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?xa(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Da(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=ka){const r=function(e,t=ka){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ua(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ta(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?xa(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=La(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=$a(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=xa(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ba(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=wa(t);if(a){const s=Ma(Ca(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ba(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ya(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?xa(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ea.id="chapter-manager";let Aa=Ea;function Fa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Na(e,t){return`${e}#s${t}`}function Oa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function za(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fa(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Fa(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Na(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ga(e){const[t,r]=e.localPageRange;return r-t+1}function Ra(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Va(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ra(t)?t.segmentPageThreshold:null}function _a(e,t){return`${e}#s${t}`}function Ba(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function qa(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ha(e){const t=Va(e);if(!t)return null;const r=Ga(e),s=qa(r,t),n=Ra(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:_a(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Wa(e,t){const r=Ha(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function ja(e,t){const r=Ha(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ya(e){var t;const r=Va(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ga(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Ra(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=qa(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Za={kind:"first-wins"};function Ka(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Ja=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Xa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Za,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Za,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ba(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ba(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ba(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Wa(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ha(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ya(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Za){const r=function(e,t=Za){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ka(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ja(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ha(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=ja(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Wa(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Ha(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Ra(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Va(t);if(a){const s=qa(Ga(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Ra(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Ba(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Ha(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Xa.id="chapter-manager";let Qa=Xa;function eo(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const to=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,eo),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Qa.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=za(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=Oa(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Oa(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=za(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=Oa(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};to.id="chapter-scroll";let ro=to;const so=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(ro.id),this.chapterManager=this.registry.getPlugin(Aa.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:ao(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};so.id="note";let no=so;function ao(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function oo(e){const[t,r]=e.localPageRange;return r-t+1}function io(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function lo(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return io(t)?t.segmentPageThreshold:null}function ho(e,t){return`${e}#s${t}`}function co(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function uo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function po(e){const t=lo(e);if(!t)return null;const r=oo(e),s=uo(r,t),n=io(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ho(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function go(e,t){const r=po(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function fo(e,t){const r=po(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function mo(e){var t;const r=lo(e);if(!r)return[];const s=[],{chapterId:n}=e,a=oo(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!io(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=uo(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const vo={kind:"first-wins"};function Po(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Io=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Co=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=vo,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??vo,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=co(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=co(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=co(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?go(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?po(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...mo(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=vo){const r=function(e,t=vo){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Po(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Io(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?po(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=fo(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=go(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=po(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(io(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=lo(t);if(a){const s=uo(oo(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(io(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=co(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?po(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Co.id="chapter-manager";let bo=Co;function wo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function So(e,t){return`${e}#s${t}`}function yo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Mo(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wo(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=wo(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:So(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function xo(e){const[t,r]=e.localPageRange;return r-t+1}function $o(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Lo(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return $o(t)?t.segmentPageThreshold:null}function Do(e,t){return`${e}#s${t}`}function ko(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Uo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function To(e){const t=Lo(e);if(!t)return null;const r=xo(e),s=Uo(r,t),n=$o(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Do(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Eo(e,t){const r=To(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Ao(e,t){const r=To(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Fo(e){var t;const r=Lo(e);if(!r)return[];const s=[],{chapterId:n}=e,a=xo(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!$o(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Uo(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const No={kind:"first-wins"};function Oo(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class zo{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Go=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=No,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??No,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ko(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ko(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ko(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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Eo(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?To(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Fo(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=No){const r=function(e,t=No){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Oo(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new zo(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?To(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Ao(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Eo(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=To(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if($o(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Lo(t);if(a){const s=Uo(xo(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if($o(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ko(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?To(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Go.id="chapter-manager";let Ro=Go;function Vo(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const _o=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Vo),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ro.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Mo(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=yo(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=yo(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Mo(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:r}=yo(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};_o.id="chapter-scroll";let Bo=_o;function qo(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ho(e,t){const r=e.origin.y,s=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,o=Math.max(s,a)-Math.min(r,n);return o<=0?0:Math.max(0,Math.min(s,a)-Math.max(r,n))/o}function Wo(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??qo(n),i=t.markerAnchor??qo(a);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of n)for(const e of a){if(Ho(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 jo=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(bo.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var r;if(this.config=t,null==(r=t.callbacks)?void 0:r.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(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}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 s of this.entries.values())if(Wo(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,r),this.notifyAndPersist(),r}removeBookmark(e){var t,r,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.onRemoveSuccess)||s.call(r,e))}async requestRemoveBookmark(t){var r,s;const n=this.entries.get(t);if(!n)return!1;const a=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const r=this.entries.get(e);r&&(this.entries.set(e,{...r,...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[r,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(r);for(const r of t)r.anchor.chapterId===e&&this.entries.set(r.id,r);this.notifyAndPersist()}notifyAndPersist(){var t,r;const s=this.list();this.change$.emit(s),(null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.persist)&&Promise.resolve(this.config.callbacks.persist(s)).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 r=this.chapterScroll.provides(),s=this.chapterManager.provides();await s.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,r){e.scrollToGlobalPageIndex(t),await function(e,t,r=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const n=setTimeout(()=>{a(),s(null)},r),a=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(n),a(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,n,a)}};jo.id="paragraph-bookmark";let Yo=jo;function Zo(e,t){const r=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...r,enabled:!1!==(null==r?void 0:r.enabled)}}function Ko(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Jo(e,t){return`${e}#s${t}`}function Xo(e,t){const r=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ko(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Ko(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Jo(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,function(){const e=Zo(void 0,{enabled:!0}),t=Zo(void 0,{enabled:!0}),r=Zo(void 0,{enabled:!0}),s=Zo(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=Zo(!1!==e.enabled||!1!==r.enabled,{enabled:!0});null==void 0||(void 0).background}();function Qo(e){const t=new Uint8Array(e);let r="";for(let s=0;s<t.length;s++)r+=String.fromCharCode(t[s]);return btoa(r)}function ei(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 ti(e){return new Promise((t,r)=>{e.wait(e=>t(e),e=>r(e))})}function ri(e){var t,s,n,a;return{annotation:null==(t=e.getPlugin(r.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(no.id))?void 0:s.provides(),bookmark:null==(n=e.getPlugin(Yo.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(Qn.id))?void 0:a.provides()}}async function si(e,t,r){if(!r||!e)return;const s=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function ni(e,t,r){const s=ei(r),{annotation:n,note:a,bookmark:o,chapterManager:i}=ri(e),l={chapterId:t};if(s.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=o.listBookmarksForChapter(t)}if(s.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(s.markup){if(!n)throw new Error("annotation 插件未注册");await si(i,t,!1!==(null==r?void 0:r.ensureChapterLoaded));const e=await async function(e,t,r){const s=t.getSegmentPlan(r);if(!s)return ti(e.forDocument(r).exportAnnotations());const n=[];for(const a of s.segments){if(!t.isSegmentLoaded(r,a.index))continue;const s=await ti(e.forDocument(a.documentId).exportAnnotations());for(const e of s){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,i,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:Qo(t.data),mimeType:t.mimeType}}})}(e)}return l}async function ai(e,t,r){const s=ei(r),n=(null==r?void 0:r.mode)??"replace",{annotation:a,note:o,bookmark:i,chapterManager:l}=ri(e),h=t.chapterId;if(s.bookmarks&&t.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)i.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)i.addBookmark(e)}if(s.notes&&t.notes){if(!o)throw new Error("note 插件未注册");if("replace"===n)o.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)o.registerNote(e)}if(s.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await si(l,h,!1!==(null==r?void 0:r.ensureChapterLoaded)),function(e,t,r,s,n){const a=t.getSegmentPlan(r);if(!a){const t=e.forDocument(r);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(s)}const o=t.getChapter(r);if(!o)return;const i=new Map;for(const l of s){const e=l.annotation.pageIndex,t=Xo(o,e),r=a.segments[t];if(!r)continue;const s=i.get(t)??[];s.push({...l,annotation:{...l.annotation,pageIndex:e-r.localPageStart}}),i.set(t,s)}for(const l of a.segments){const t=e.forDocument(l.documentId),r=i.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),r.length>0&&t.importAnnotations(r)}}(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 r=function(e){const t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:r,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==r?void 0:r.persistNotes)&&o&&await r.persistNotes(o.listAllNotes()),(null==r?void 0:r.persistBookmarks)&&i&&await r.persistBookmarks(i.listBookmarks())}function oi(e){return JSON.stringify(e,null,2)}function ii(e){return JSON.stringify(e,null,2)}function li(e,t){const r=new Blob([t],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(r),n=document.createElement("a");n.href=s,n.download=e,n.click(),URL.revokeObjectURL(s)}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT;function hi(e){const[t,r]=e.localPageRange;return r-t+1}function di(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ci(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return di(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 r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function gi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function fi(e){const t=ci(e);if(!t)return null;const r=hi(e),s=gi(r,t),n=di(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ui(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function mi(e,t){const r=fi(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function vi(e,t){const r=fi(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Pi(e){var t;const r=ci(e);if(!r)return[];const s=[],{chapterId:n}=e,a=hi(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!di(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=gi(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ii={kind:"first-wins"};function Ci(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class bi{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}function wi(e,t=Ii){const r=function(e,t=Ii){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ci(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new bi(a)}const Si=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.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],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=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?mi(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?fi(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Pi(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=wi(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?fi(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=vi(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=mi(this.findChapter(r.chapterId),r.localPageIndex);if(this.documentManager.provides().isDocumentOpen(e.documentId)){this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus){if("loaded"!==s)continue;t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=fi(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(di(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=ci(t);if(a){const s=gi(hi(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(di(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=pi(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}if(!l)return void this.updateStatus(r,"password-required");this.updateStatus(r,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?fi(t):null,n=e=>{if(r.isDocumentOpen(e)){r.closeDocument(e).wait(()=>{},()=>{})}};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Si.id="chapter-manager";let yi=Si;function Mi(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 xi(e){const t=[],r=e=>{var s;for(const n of e)t.push(Mi(n)),(null==(s=n.children)?void 0:s.length)&&r(n.children)};return r(e),t}function $i(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)?$i(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:()=>y.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=R,exports.ChapterManagerPlugin=yi,exports.ChapterPdfViewer=zn,exports.ChapterTreePanel=On,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Pr,exports.PdfChapterViewport=Sn,exports.applySelectionMarkup=E,exports.buildChapterViewerCatalog=function(e){return{tree:$i(e),manifest:{chapters:xi(e)}}},exports.buildParagraphBookmarkAnchor=lr,exports.chapterAnnotationsArchiveToJson=oi,exports.chapterAnnotationsSnapshotToJson=ii,exports.chapterDescriptorFromTreeNode=Mi,exports.copyTextToClipboard=async function(e){var t;const r=e.trim();if(!r)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(r),!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}catch{return!1}},exports.createChapterViewerBundle=Sr,exports.createChapterViewerEditor=Ir,exports.createChapterViewerEditorOptions=function(e){const{features:t,...r}=wr(br(e));return r},exports.createPdfChapterEditor=mr,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){li(t,oi(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){li(t??`chapter-annotations-${e.chapterId}.json`,ii(e))},exports.downloadJsonFile=li,exports.exportAllChapterAnnotations=async function(e,t,r){const s={};for(const n of t.chapters){const t=await ni(e,n.chapterId,r),{chapterId:a,...o}=t;s[n.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=ni,exports.flattenChapterTree=xi,exports.importChapterAnnotations=ai,exports.importChapterAnnotationsArchive=async function(e,t,r){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[s,n]of Object.entries(t.chapters))await ai(e,{chapterId:s,...n},r)},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=$i;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|