From 52bfce900e8bf6af3db60423033ffd38e92fc199 Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Sun, 29 Dec 2024 09:07:18 +0800 Subject: [PATCH] fix bug --- package.json | 2 +- public/lib/kookit/kookit.min.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 08623244..5d587992 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "koodo-reader", "main": "main.js", - "version": "1.7.2", + "version": "1.7.3", "description": "A cross-platform ebook reader", "author": { "name": "App by Troye", diff --git a/public/lib/kookit/kookit.min.js b/public/lib/kookit/kookit.min.js index 48fa0fb9..15450ad3 100644 --- a/public/lib/kookit/kookit.min.js +++ b/public/lib/kookit/kookit.min.js @@ -1,4 +1,4 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Kookit={})}(this,function(e){"use strict";function v(e,a,o,l){return new(o=o||Promise)(function(r,t){function i(e){try{s(l.next(e))}catch(e){t(e)}}function n(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?r(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(i,n)}s((l=l.apply(e,a||[])).next())})}const w=e=>e?parseFloat(e+""):0,p=e=>parseFloat(e.substring(0,e.length-2)),m=r=>v(void 0,void 0,void 0,function*(){let t="";if(r.load){let e=yield fetch(yield r.load()).then(e=>e.blob());t=yield e.text()}return r.loadAsset&&(t=yield i(t,r.loadAsset)),n(t)}),u=e=>Array.from(e.querySelectorAll("img, image")),i=(n,s)=>v(void 0,void 0,void 0,function*(){let e=(new DOMParser).parseFromString(n,"text/html"),t=u(e);for(let e=0;e{var t=(new DOMParser).parseFromString(e,"text/html");let r=u(t);if(0===r.length)return e;for(let e=0;e{var r=document.createElement("iframe");r.style.width="100%",r.style.border="0",r.style.margin="0",r.style.padding="0",r.style.minHeight="calc(100% - 2px)",r.style.fontSize="100%",r.style.font="inherit",r.scrolling="no",r.tabIndex=0,r.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(r)},c=r=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return 1===parseInt(t.body.scrollWidth/t.body.clientWidth+"")&&(yield new Promise(e=>setTimeout(e,1e3))),{totalPage:"scroll"===r?1:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(w(t.body.scrollLeft)/t.body.clientWidth+"")+1}}}}),g=()=>{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var r=e.querySelectorAll("a, article, cite, div, li, p, span, pre, table, bold, body");for(let e=0;ev(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let n=t.contentDocument;if(n){var s,t=Math.floor(c.clientWidth/12),a=t%2==0?t:t-1;for(s of n.querySelectorAll("img, image")){var o,l=s.parentElement;let e=0,t=0,r=s.naturalWidth,i=s.naturalHeight;"image"===s.tagName&&(o=yield(t=>v(void 0,void 0,void 0,function*(){const e=new Image;return e.src=t,yield e.decode(),e}))(s.getAttribute("xlink:href")),r=o.naturalWidth,i=o.naturalHeight),d.startsWith("CB")&&"scroll"===h?t=l.offsetWidth:d.startsWith("CB")&&"single"===h?(e=c.clientHeight,t=c.clientWidth):r&&i?(i/r>l.clientHeight/l.clientWidth?(e=l.clientHeight,t=parseInt(e*r/i+"")):(t=l.clientWidth,e=parseInt(t*i/r+"")),e>n.body.clientHeight&&(t=parseInt(t*(n.body.clientHeight/e)+""),e=n.body.clientHeight)):e=l&&l.clientWidth&&0i||e/t>i/r?e=t*(i/r):t=e*(r/i)),(t||e)&&s.setAttribute("style",s.getAttribute("style")+";"+`max-width: ${0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){let t=n.contentDocument;if(t){let e=t.createElement("style");e.id="default-style",e.textContent="p,empty-line{display: inherit;margin-block-start: inherit;margin-block-end: inherit;margin-inline-start: inherit;margin-inline-end: inherit;}body{margin: 0px}",t.head.appendChild(e),"scroll"!==i&&(n="double"===i?2:1,i=(i=Math.floor(r.clientWidth/12))%2==0?i:i-1,t.body.setAttribute("style",`width: auto;height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;max-width: inherit;column-fill: auto;column-gap: ${i}px; column-width: ${(r.clientWidth-i)/n}px;`))}}}};class f{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return v(this,void 0,void 0,function*(){return this.chapterList=e?yield Promise.all(e.map(t=>v(this,void 0,void 0,function*(){let e=-1;try{e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1}catch(e){console.log(e)}return{label:t.label||e,href:t.href||"title"+e,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))):yield Promise.all(this.book.sections.map((e,t)=>v(this,void 0,void 0,function*(){return{label:e.label||t,href:e.href||"title"+t,index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return v(this,void 0,void 0,function*(){const r=this.flattenChapters.map(e=>e.index);return this.book.sections.map((e,t)=>-1v(this,void 0,void 0,function*(){const t=this.book.metadata;try{var e=yield this.book.getCover(),r=new FileReader;r.readAsDataURL(e),r.onloadend=()=>{n({name:t.title,author:t.author?t.author[0].name:"",description:t.description,publisher:t.publisher,cover:r.result})}}catch(e){try{var i=t.author&&t.author[0]&&t.author[0].name?t.author[0].name:t.author&&t.author[0]?t.author[0]:t.author||"";n({name:t.title,author:i,description:t.description,publisher:t.publisher,cover:""})}catch(e){console.log(e),s(e)}}}))}}const r=(e,i)=>e.map((e,t,r)=>i(e,t,r)?t:null).filter(e=>null!=e),o=(i,e)=>[-1,...e,i.length].reduce(({xs:e,a:t},r)=>({xs:e?.concat([i.slice(t+1,r)])??[],a:r}),{}).xs,l=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),h=/\d/,d=/^epubcfi\((.*)\)$/,b=e=>e.replace(/[\^[\](),;=]/g,"^$&"),t=e=>d.test(e)?e:`epubcfi(${e})`,x=(e,t)=>r(e,([e])=>e===t),C=e=>{const t=[];let r;for(var[i,n]of e){if("/"===i)t.push({index:n});else{const s=t[t.length-1];if(":"===i)s.offset=n;else if("~"===i)s.temporal=n;else if("@"===i)s.spatial=(s.spatial??[]).concat(n);else if(";s"===i)s.side=n;else if("["===i){if("/"!==r||!n){s.text=(s.text??[]).concat(n);continue}s.id=n}}r=i}return t},L=e=>o(e,x(e,"!")).map(C),T=e=>{var t=(e=>{const t=[];let r,i,n="";var s=e=>(t.push(e),r=null,n=""),a=e=>(n+=e,i=!1);for(const o of Array.from(e.trim()).concat(""))if("^"!==o||i){if("!"===r)s(["!"]);else if(","===r)s([","]);else if("/"===r||":"===r){if(h.test(o)){a(o);continue}s([r,parseInt(n)])}else if("~"===r){if(h.test(o)||"."===o){a(o);continue}s(["~",parseFloat(n)])}else if("@"===r){if(":"===o){s(["@",parseFloat(n)]),r="@";continue}if(h.test(o)||"."===o){a(o);continue}s(["@",parseFloat(n)])}else{if("["===r){";"!==o||i?","!==o||i?"]"!==o||i?a(o):s(["[",n]):(s(["[",n]),r="["):(s(["[",n]),r=";");continue}if(r?.startsWith(";")){"="!==o||i?";"!==o||i?"]"!==o||i?a(o):s([r,n]):(s([r,n]),r=";"):(r=`;${n}`,n="");continue}}"/"!==o&&":"!==o&&"~"!==o&&"@"!==o&&"["!==o&&"!"!==o&&","!==o||(r=o)}else i=!0;return t})((r=e).match(d)?.[1]??r),e=x(t,",");if(!e.length)return L(t);var[r,t,e]=o(t,e).map(L);return{parent:r,start:t,end:e}},S=({index:e,id:t,offset:r,temporal:i,spatial:n,text:s,side:a})=>{var o=a?`;s=${a}`:"";return`/${e}`+(t?`[${b(t)}${o}]`:"")+(null!=r&&e%2?`:${r}`:"")+(i?`~${i}`:"")+(n?`@${n.join(":")}`:"")+(s||!t&&a?"["+(s?.map(b)?.join(",")??"")+o+"]":"")},I=e=>e.parent?[e.parent,e.start,e.end].map(I).join(","):e.map(e=>e.map(S).join("")).join("!"),k=e=>t(I(e)),E=(e,t)=>"string"==typeof e?k(E(T(e),t)):e.parent?l(e.parent,e[t?"end":"start"]):e,B=({nodeType:e})=>3===e||4===e,A=({nodeType:e})=>1===e,M=e=>{const t=Array.from(e.childNodes).filter(e=>B(e)||A(e)).reduce((e,t)=>{let r=e[e.length-1];return r?B(t)?Array.isArray(r)?r.push(t):B(r)?e[e.length-1]=[r,t]:e.push(t):A(r)?e.push(null,t):e.push(t):e.push(t),e},[]);return A(t[0])&&t.unshift("first"),A(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},O=(e,t)=>e?M(e)[t]:null,R=(e,t)=>{var r,i=t[t.length-1]["id"];if(i){i=e.ownerDocument.getElementById(i);if(i)return{node:i,offset:0}}for({index:r}of t){var n=O(e,r);if("first"===n)return{node:e.firstChild??e};if("last"===n)return{node:e.lastChild??e};if("before"===n)return{node:e,before:!0};if("after"===n)return{node:e,after:!0};e=n}var s=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:s};let a=0;for(const l of e){var o=l.nodeValue["length"];if(a+o>=s)return{node:l,offset:s-a};a+=o}},N=(t,r)=>{var{parentNode:e,id:i}=t;const n=M(e);var s=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),a=n[s];if(Array.isArray(a)){let e=0;for(const o of a){if(o===t){e+=r;break}e+=o.nodeValue.length}r=e}s={id:i,index:s,offset:r};return e!==t.ownerDocument.documentElement?N(e).concat(s):[s]},D=(e,t)=>R(e.documentElement,E(t)).node,_={CONTAINER:"urn:oasis:names:tc:opendocument:xmlns:container",XHTML:"http://www.w3.org/1999/xhtml",OPF:"http://www.idpf.org/2007/opf",EPUB:"http://www.idpf.org/2007/ops",DC:"http://purl.org/dc/elements/1.1/",DCTERMS:"http://purl.org/dc/terms/",ENC:"http://www.w3.org/2001/04/xmlenc#",NCX:"http://www.daisy.org/z3986/2005/ncx/",XLINK:"http://www.w3.org/1999/xlink",SMIL:"http://www.w3.org/ns/SMIL"},F={XML:"application/xml",NCX:"application/x-dtbncx+xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml",JS:/\/(x-)?(javascript|ecmascript)/},H=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),P=e=>e?e.trim().replace(/\s{2,}/g," "):"",U=(t,r,e)=>e?e=>e.getAttribute(t)?.split(/\s/)?.includes(r):"function"==typeof r?e=>r(e.getAttribute(t)):e=>e.getAttribute(t)===r,j=(...e)=>t=>t?Object.fromEntries(e.map(e=>[H(e),t.getAttribute(e)])):null,$=e=>P(e?.textContent),z=(e,r)=>{e=e.lookupNamespaceURI(null)===r||e.lookupPrefix(r);const i=e?(e,t)=>e=>e.namespaceURI===r&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(i(e,t)),$$:(e,t)=>[...e.children].filter(i(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(r,t)]:(e,t)=>[...e.getElementsByTagName(r,t)]}},W=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var r="whatever://whatever/";return decodeURI(new URL(t,r+e).href.replace(r,""))}catch(e){return console.warn(e),t}},q=e=>/^(?!blob)\w+:/i.test(e),X=async(e,t,r)=>{const i=[];e.replace(t,(...e)=>(i.push(e),null));const n=[];for(const s of i)n.push(await r(...s));return e.replace(t,()=>n.shift())},V=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");var G={attrs:["dir","xml:lang"]},J={name:"alternate-script",many:!0,...G,props:["file-as"]},K={many:!0,...G,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",J]};const Z=[{name:"title",many:!0,...G,props:["title-type","display-seq","file-as",J]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...K},{name:"contributor",...K},{name:"publisher",...G,props:["file-as",J]},{name:"description",...G,props:[J]},{name:"rights",...G,props:[J]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...G,props:["term","authority",J]},{name:"belongs-to-collection",type:"meta",many:!0,...G,props:["collection-type","group-position","dcterms:identifier","file-as",J,{name:"belongs-to-collection",recursive:!0}]}],Y=(e,s=e=>e)=>{const{$:a,$$:r,$$$:t}=z(e,_.XHTML),i=n=>e=>{const t=a(e,"a")??a(e,"span");var r=a(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(s(e)):null;const i={label:$(t)||t?.getAttribute("title"),href:e,subitems:o(r)};return n&&(i.type=t?.getAttributeNS(_.EPUB,"type")?.split(/\s/)),i},o=(e,t)=>e?r(e,"li").map(i(t)):null;var n=(e,t)=>o(a(e,"ol"),t);let l=null,c=null,h=null,d=[];for(const u of t(e,"nav")){const f=u.getAttributeNS(_.EPUB,"type")?.split(/\s/)??[];f.includes("toc")?l??=n(u):f.includes("page-list")?c??=n(u):f.includes("landmarks")?h??=n(u,!0):d.push({label:$(u.firstElementChild),type:f,list:n(u)})}return{toc:l,pageList:c,landmarks:h,others:d}},Q=(r,s=e=>e)=>{const{$:a,$$:o}=z(r,_.NCX),l=e=>{var t=a(e,"navLabel");const r=a(e,"content");var i=$(t),t=(t=r.getAttribute("src"))?decodeURI(s(t)):null;if("navPoint"!==e.localName)return{label:i,href:t};{const n=o(e,"navPoint");return{label:i,href:t,subitems:n.length?n.map(l):null}}},i=(e,t)=>o(e,t).map(l);var e=(e,t)=>{e=a(r.documentElement,e);return e?i(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:o(r.documentElement,"navList").map(e=>({label:$(a(e,"navLabel")),list:i(e,"navTarget")}))}},ee=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[r,i,n]=t;return 60*r*60+60*i+n}if(2===t.length){var[t,s]=t;return 60*t+s}var[s,e]=e.split(/(?=[^\d.])/);return parseFloat(s)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},te=(e,i=e=>e)=>{const{$:n,$$$:t}=z(e,_.SMIL);return t(e,"par").map(e=>{var t=n(e,"text")?.getAttribute("src")?.split("#")?.[1];const r=n(e,"audio");return r?{id:t,audio:{src:(e=r.getAttribute("src"))?decodeURI(i(e)):null,clipBegin:ee(r.getAttribute("clipBegin")),clipEnd:ee(r.getAttribute("clipEnd"))}}:{id:t}})},re=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ie=e=>$(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(_.DC,"identifier")[0]),ne=async(e,t,r)=>{const i=new Uint8Array(await r.slice(0,t).arrayBuffer());t=Math.min(t,i.length);for(var n=0;n{e=(new TextEncoder).encode(e),e=await globalThis.crypto.subtle.digest("SHA-1",e);return new Uint8Array(e)})=>({"http://www.idpf.org/2008/embedding":{key:e=>t(ie(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>ne(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const r=(e=>{for(const r of e.getElementsByTagNameNS(_.DC,"identifier")){var[t]=$(r).split(":").slice(-1);if(re.test(t))return t}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},(e,t)=>parseInt(r.slice(2*t,2*t+2),16))},decode:(e,t)=>ne(e,1024,t)}});class ae{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var r,i;if(e)for({algorithm:r,uri:i}of Array.from(e.getElementsByTagNameNS(_.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(_.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(_.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(r)){const n=this.#algorithms[r];if(!n){console.warn("Unknown encryption algorithm");continue}const s=await n.key(t);this.#decoders.set(r,e=>n.decode(s,e))}this.#uris.set(i,r)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class oe{constructor({opf:e,resolveHref:i}){this.opf=e;const{$:t,$$:r,$$$:n}=z(e,_.OPF);var s=t(e.documentElement,"manifest");const a=t(e.documentElement,"spine"),o=r(a,"itemref");this.manifest=r(s,"item").map(j("href","id","media-type","properties","media-overlay")).map(e=>(e.href=i(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=o.map(j("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=a.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(a.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===F.NCX))?.href;s=t(e.documentElement,"guide");s&&(this.guide=r(s,"reference").map(j("type","title","href")).map(({type:e,title:t,href:r})=>({label:t,type:e.split(/\s/),href:i(r)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(n(e,"meta").find(U("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var r,i,n=e[0]["parentNode"];const s=N(n);for([r,i]of M(n).entries()){var a=e[t.length];i===a&&t.push(k([s.concat({id:a.id,index:r})]))}return t})(o)}getItemByID(t){return this.manifest.find(e=>e.id===t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>e.properties?.includes(t))}resolveCFI(e){const t=T(e),r=(t.parent??t).shift();let i=D(this.opf,r);i&&"idref"!==i.nodeName&&(r.at(-1).id=null,i=D(this.opf,r));const n=i?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var r=E(t),i=E(t,!0),t=e.documentElement,r=R(t,r[0]),i=R(t,i[0]);const n=e.createRange();return r.before?n.setStartBefore(r.node):r.after?n.setStartAfter(r.node):n.setStart(r.node,r.offset),i.before?n.setEndBefore(i.node):i.after?n.setEndAfter(i.node):n.setEnd(i.node,i.offset),n})(e,t)}}}class le{#cache=new Map;#children=new Map;#refCount=new Map;allowScript=!1;constructor({loadText:e,loadBlob:t,resources:r}){this.loadText=e,this.loadBlob=t,this.manifest=r.manifest,this.assets=r.manifest}createURL(e,t,r,i){if(!t)return"";r=URL.createObjectURL(new Blob([t],{type:r}));if(this.#cache.set(e,r),this.#refCount.set(e,1),i){const n=this.#children.get(i);n?n.push(e):this.#children.set(i,[e])}return r}ref(e,t){const r=this.#children.get(t);return r?.includes(e)||(this.#refCount.set(e,this.#refCount.get(e)+1),r?r.push(e):this.#children.set(t,[e])),this.#cache.get(e)}unref(e){if(this.#refCount.has(e)){var t=this.#refCount.get(e)-1;if(t<1){URL.revokeObjectURL(this.#cache.get(e)),this.#cache.delete(e),this.#refCount.delete(e);const r=this.#children.get(e);if(r)for(;r.length;)this.unref(r.pop());this.#children.delete(e)}else this.#refCount.set(e,t)}}async loadItem(e,t=[]){if(!e)return null;const{href:r,mediaType:i}=e;var n=F.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var s=t.at(-1);return this.#cache.has(r)?this.ref(r,s):(n||[F.XHTML,F.HTML,F.CSS,F.SVG].includes(i))&&t.every(e=>e!==r)?this.loadReplaced(e,t):this.createURL(r,await this.loadBlob(r),i,s)}async loadHref(e,t,r=[]){if(q(e))return e;const i=W(e,t);let n=this.manifest.find(e=>e.href===i);return n=n||{href:i,mediaType:""},this.loadItem(n,r.concat(t))}async loadReplaced(e,n=[]){const{href:s,mediaType:r}=e;var i,a=n.at(-1),o=await this.loadText(s);if(!o)return null;if([F.XHTML,F.HTML,F.SVG].includes(r)){let t=(new DOMParser).parseFromString(o,r);if(r===F.XHTML&&t.querySelector("parsererror")&&(console.warn(t.querySelector("parsererror").innerText),e.mediaType=F.HTML,t=(new DOMParser).parseFromString(o,e.mediaType)),[F.XHTML,F.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(i=await X(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,r,i)=>this.loadHref(r,s,n).then(e=>`${t}${e}${i}`)),e.replaceWith(t.createProcessingInstruction(e.target,i))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),s,n));for(const h of t.querySelectorAll("link[href]"))await l(h,"href");for(const d of t.querySelectorAll("[src]"))await l(d,"src");for(const u of t.querySelectorAll("[poster]"))await l(u,"poster");for(const f of t.querySelectorAll("object[data]"))await l(f,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(_.XLINK,"href",await this.loadHref(p.getAttributeNS(_.XLINK,"href"),s,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,s,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),s,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(s,c,e.mediaType,a)}const c=r===F.CSS?await this.replaceCSS(o,s,n):await this.replaceString(o,s,n);return this.createURL(s,c,r,a)}async replaceCSS(e,r,i=[]){e=await X(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,r,i).then(e=>`url("${e}")`));const t=await X(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,r,i).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,s=window?.innerHeight??600;return t.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/gi,(e,t)=>parseFloat(t)*s/100+"px").replace(/page-break-(after|before|inside)/gi,(e,t)=>`-webkit-column-break-${t}`)}replaceString(e,a,t=[]){const o=new Map,r=this.assets.map(e=>{if(e.href!==a){var t=((e,t)=>{if(!e)return t;const r=e.replace(/\/$/,"").split("/"),i=t.replace(/\/$/,"").split("/");t=(r.length>i.length?r:i).findIndex((e,t)=>r[t]!==i[t]);return t<0?"":Array(r.length-t).fill("..").concat(i.slice(t)).join("/")})(a.slice(0,a.lastIndexOf("/")+1),e.href),r=encodeURI(t),i="/"+e.href,n=encodeURI(i),n=new Set([t,r,i,n]);for(const s of n)o.set(s,e);return Array.from(n)}}).flat().filter(e=>e);if(!r.length)return e;var i=new RegExp(r.map(V).join("|"),"g");return X(e,i,async e=>this.loadItem(o.get(e.replace(/^\//,"")),t.concat(a)))}unloadItem(e){this.unref(e?.href)}}class ce{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:r,sha1:i}){this.loadText=e,this.loadBlob=t,this.getSize=r,this.#encryption=new ae(se(i))}#parseXML(e){return e?this.parser.parseFromString(e,F.XML):null}async#loadXML(e){return this.#parseXML(await this.loadText(e))}async init(){const e=await this.#loadXML("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");var t=Array.from(e.getElementsByTagNameNS(_.CONTAINER,"rootfile"),j("full-path","media-type")).filter(e=>"application/oebps-package+xml"===e.mediaType);if(!t.length)throw new Error("No package document defined in container");const r=t[0].fullPath;var i=await this.#loadXML(r);if(!i)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,i),this.resources=new oe({opf:i,resolveHref:e=>W(e,r)});const s=new le({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#encryption.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map((e,t)=>{var{idref:r,linear:i,properties:e=[]}=e;const n=this.resources.getItemByID(r);return n?{id:this.resources.getItemByID(r)?.href,load:()=>s.loadItem(n),unload:()=>s.unloadItem(n),createDocument:()=>this.loadDocument(n),size:this.getSize(n.href),cfi:this.resources.cfis[t],linear:i,pageSpread:(e=>{for(const t of e){if("page-spread-left"===t||"rendition:page-spread-left"===t)return"left";if("page-spread-right"===t||"rendition:page-spread-right"===t)return"right";if("rendition:page-spread-center"===t)return"center"}})(e),resolveHref:e=>W(e,n.href),loadMediaOverlay:()=>this.loadMediaOverlay(n)}:(console.warn(`Could not find item with ID "${r}" in manifest`),null)}).filter(e=>e);const{navPath:n,ncxPath:a}=this.resources;if(n)try{var o=Y(await this.#loadXML(n),e=>W(e,n));this.toc=o.toc,this.pageList=o.pageList,this.landmarks=o.landmarks}catch(e){console.warn(e)}if(!this.toc&&a)try{var l=Q(await this.#loadXML(a),e=>W(e,a));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:h,media:d}=(e=>{const{$:t,$$:r}=z(e,_.OPF),i=t(e.documentElement,"metadata"),s=Array.from(i.children),l=(a,t)=>{if(!t)return null;const{props:e=[],attrs:r=[]}=a,i=$(t);if(!e.length&&!r.length)return i;var n=t.getAttribute("id");const o=n?s.filter(U("refines","#"+n)):[];return Object.fromEntries([["value",i]].concat(e.map(e=>{var{many:t,recursive:r}=e,i="string"==typeof e?e:e.name,n=U("property",i);const s=r?a:e;return[H(i),t?o.filter(n).map(e=>l(s,e)):l(s,o.find(n))]})).concat(r.map(e=>[H(e),t.getAttribute(e)])))},a=s.filter(U("refines",null));e=t=>Object.fromEntries(r(i,"meta").filter(U("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),$(e)]));return{metadata:Object.fromEntries(Z.map(t=>{const{type:e,name:r,many:i}=t;var n="meta"===e?e=>e.namespaceURI===_.OPF&&e.getAttribute("property")===r:e=>e.namespaceURI===_.DC&&e.localName===r;return[H(r),i?a.filter(n).map(e=>l(t,e)):l(t,a.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(i);this.rendition=h,this.media=d,d.duration=ee(d.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=c;l=c?.title?.[0];this.metadata={title:l?.value,sortAs:l?.fileAs,language:c?.language,identifier:ie(i),description:c?.description?.value,publisher:c?.publisher?.value,published:c?.date,modified:c?.dctermsModified,subject:c?.subject?.filter(({value:e,code:t})=>e||t)?.map(({value:e,code:t,scheme:r})=>({name:e,code:t,scheme:r})),rights:c?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};i=r=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:u[e])??r))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[r],e]};return c?.creator?.map(i("author"))?.concat(c?.contributor?.map?.(i("contributor")))?.forEach(([e,t])=>e.forEach(e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})),this}async loadDocument(e){var t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){e=e.mediaOverlay;if(!e)return null;const t=this.resources.getItemByID(e);e=await this.#loadXML(t.href);return te(e,e=>W(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,r]=e.split("#"),i=this.resources.getItemByHref(decodeURI(t));return i?{index:this.resources.spine.findIndex(({idref:e})=>e===i.id),anchor:r?e=>((e,t)=>e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`))(e,r):()=>0}:null}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return q(e)}async getCover(){var e=this.resources?.cover;return e?.href?new Blob([await this.loadBlob(e.href)],{type:e.mediaType}):null}async getCalibreBookmarks(){const e=await this.loadText("META-INF/calibre_bookmarks.txt");var t="encoding=json+base64:";if(e?.startsWith(t)){t=atob(e.slice(t.length));return JSON.parse(t)}}}let he=!1;const de=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),ue=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),fe=(h,d,u,f,p,m,g,y,b)=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t,r,i,n,s,a,o,l,c=e.getElementsByTagName("iframe")[0];if(c){let e=c.contentDocument;e&&(c=(t=Math.floor(h.clientWidth/12))%2==0?t:t-1,t=h.clientWidth,0{let n=window._.findLastIndex(r,{href:t});return n=t&&-1v(void 0,void 0,void 0,function*(){var e=parseInt(a.chapterDocIndex||"0"),t=a.chapterHref||"";0===e||(t=pe(e,t,i,"prev"))&&(a.text="prevChapter",a.page="",yield ge(t.index,t.label,t.href,i,r,n,s,a))}),ge=(r,l,c,h,d,u,f,p)=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){let t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;var s,i,n,a,o;e&&(e.body.innerHTML="",t.height="0px",e.body.scrollTo(0,0),(-1===(r=l&&!r||h[r]&&h[r].label&&l&&l!==h[r].label&&-1===c.indexOf("#")?window._.findLastIndex(h,{label:l}):r)||r>h.length-1)&&(r=0),e.body.innerHTML=yield m(h[r].text),s=e,yield v(void 0,void 0,void 0,function*(){var t=Array.from(s.getElementsByTagName("link"));for(let e=0;e{console.log("finished")}}let r=[];for(let e=0;e{n.addEventListener("load",e)}))}try{yield Promise.race([Promise.all(r),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Timeout"))},1e3)})])}catch(e){console.log(e)}}),p.chapterTitle=l,p.chapterHref=c,p.chapterDocIndex=r+"",p.percentage=r/h.length+"",p.text="",i=d,n=u,a=t,o=f,yield v(void 0,void 0,void 0,function*(){let t=a.contentDocument;if(t)if(yield Promise.all(Array.from([...t.images,...t.querySelectorAll("image")]).map(t=>t.complete?Promise.resolve(0!==t.naturalHeight):new Promise(e=>{t.addEventListener("load",()=>e(!0)),t.addEventListener("error",()=>e(!1))}))).then(e=>{e.every(e=>e)?console.log("all images loaded successfully!!"):console.log("some images failed to load, all finished loading")}),yield y(i,n,o),g(),"scroll"!==n){if(a.height=i.clientHeight+"px","double"===n){var r=Math.floor(i.clientWidth/12),r=(i.clientWidth+(r%2==0?r:r-1))/2;if((t.body.scrollWidth-t.body.clientWidth)/r%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+t.body.clientHeight+"px; display: inline-block; width: "+r+"px"),t.body.appendChild(e)}}}else a.height=t.body.scrollHeight+"px",a.height=t.body.scrollHeight+"px"}),ye(d,u,"","","",""))}}}),ye=(l,c,h,d,u,f)=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let n=s.contentDocument;if(n){let t=0,r=0,i=n.body;if(f&&"scroll"!==c){var a=Math.floor(l.clientWidth/12),s=a%2==0?a:a-1,a=p(getComputedStyle(l).width);r=(a+s)*(parseInt(f)-1)}else if(h){let e=de(n.body);var o=e.filter((e,t)=>ue(e.textContent).slim()&&(ue(e.textContent).slim()===ue(h).slim()||ue(e.textContent).slim()===window.ChineseS2T.t2s(ue(h).slim())||ue(e.textContent).slim()===window.ChineseS2T.s2t(ue(h)).slim())&&(Math.abs(t-parseInt(d))<2||"search"===d||"ignore"===d||"next"===d));if(0===o.length)return void console.log("failed");i=be(o[0],l,c),r=i?w(i.offsetLeft)-w(i.marginLeft||parseFloat(getComputedStyle(i).marginLeft)):"prevChapter"===h?n.body.scrollWidth:0,t=i?w(i.offsetTop)-w(i.marginTop||parseFloat(getComputedStyle(i).marginTop)):0}else if(u&&-1{var i=Math.floor(t.clientWidth/12),i=i%2==0?i:i-1;return"scroll"!==r&&parseInt(w(e.offsetLeft)-w(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft))+"")%((t.clientWidth+i)/2)!=0&&e.parentElement?be(e.parentElement,t,r):e},ve=(s,a,o,l)=>v(void 0,void 0,void 0,function*(){if(!he){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){var i=i.contentDocument;if(i){let t=de(i.body);var i=t.filter(e=>Le(s,e,a)&&(e.textContent||"").trim()),n=i[0];let r=0;for(let e=0;e{let e=i.chapterHref||"",n=e.lastIndexOf("#"),s=e.substring(0,n),a=e.substring(n+1);for(let e=0;e-1)i.chapterHref=e}}})(i,o,l),n&&!((e,t,r)=>{let i=Math.floor(t.clientWidth/12),n=i%2===0?i:i-1;if(Math.abs(e.offsetLeft-be(e,t,r).offsetLeft)>(t.clientWidth+n)/2)return true;else return false})(n,s,a)?(l.text=n&&n.textContent||"",l.count=r+"",l.page=""):l.page=(null===(i=yield c(a))||void 0===i?void 0:i.currentPage)+"",he=!0,setTimeout(()=>{he=!1},100)}}}}}),we=(r,e,i,n,s,a)=>v(void 0,void 0,void 0,function*(){var e=parseInt(a.chapterDocIndex||"0"),t=a.chapterHref||"";e>=i.length-1?a.percentage="1":(t=pe(e,t,i,"next"))&&(a.page="",yield ge(t.index,t.label,t.href,i,r,n,s,a))}),xe=(r,i)=>{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body).filter(e=>!Ce(e)),t=e.filter(e=>Le(r,e,i)&&(e.textContent||"").trim());return t.filter(e=>"img"!==e.textContent).map(e=>e.textContent)}}}},Ce=e=>{var t=e.children;let r=!1;var i=/^(address|section|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i;if(Array.from(t).filter(e=>i.test(e.nodeName)).length<3)return!1;for(var n=0;n{var i,n=!1,s=t.getBoundingClientRect();return"scroll"!==r&&t.textContent&&t.textContent.trim()?n=-10<(i=s.left)&&i<=e.clientWidth:"scroll"===r&&t.textContent&&t.textContent.trim()?n=(t=s.top)>=e.scrollTop&&t<=e.scrollTop+e.clientHeight:"scroll"!==r&&(n=0<=(s=s.left)&&s<=e.clientWidth),n};const Te={svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",html:"text/html",htm:"text/html",xml:"text/xml",xhtml:"application/xhtml+xml",css:"text/css"},Se={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","application/zip":"zip","application/x-rar-compressed":"rar","application/x-7z-compressed":"7z","application/x-tar":"tar","text/html":"html","text/xml":"xml","application/xhtml+xml":"xhtml","text/css":"css"},Ie=Node.ELEMENT_NODE,ke=Node.TEXT_NODE,Ee=Node.CDATA_SECTION_NODE;class Be{constructor(r,i){this.isRange=!1,this.opts=Object.assign({flattenRange:!1,stricter:!0},i||{}),this.cfi=r,this.parts=[];var n,s,a,i=(r=r.trim()).match(/^epubcfi\((.*)\)$/);if(!i)throw new Error("Not a valid CFI");if(!(i.length<2)){r=i[1]||"";let e=[],t=0;for(;r.length;){if({parsed:n,offset:s,newDoc:a}=this.parse(r),!n||null===s)throw new Error("Parsing failed");if(t&&a)throw new Error("CFI is a range that spans multiple documents. This is not allowed");e.push(n),(a||r.length-s<=0)&&(2===t?this.to=e:this.parts.push(e),e=[]),","===(r=r.slice(s))[0]&&(0===t?(e.length&&this.parts.push(e),e=[]):1===t&&(e.length&&(this.from=e),e=[]),r=r.slice(1),t++)}this.from&&this.from.length&&(!this.opts.flattenRange&&this.to&&this.to.length?this.isRange=!0:(this.parts=this.parts.concat(this.from),delete this.from,delete this.to)),this.opts.stricter&&this.removeIllegalOpts()}}removeIllegalOpts(e){if(!e)if(this.from){if(this.removeIllegalOpts(this.from),!this.to)return;e=this.to}else e=this.parts;let t,r,i,n;for(t=0;tthis.compare(e,t))}static compare(e,t){let r=e.get(),i=t.get();if(e.isRange||t.isRange){if(e.isRange&&t.isRange){var n=this.comparePath(r.from,i.from);return n?n:this.comparePath(r.to,i.to)}return e.isRange&&(r=r.from),t.isRange&&(i=i.from),this.comparePath(r,i)}return this.comparePath(r,i)}static compareParts(e,t){var r,i,n,s,a=Math.max(e.length,t.length);let o,l,c,h;for(o=0;o=r)return"img"===l.tagName.toLowerCase()&&i?{node:l,offset:i}:{node:l,offset:0}}else{if(s+=1,s===r)return"img"===l.tagName.toLowerCase()&&i?{node:l,offset:i}:{node:l,offset:0};if(s>r)return a?{node:a,offset:this.trueLength(e,a.textContent)}:{node:t,offset:0}}a=l;break;case ke:case Ee:if(0!==s&&s%2!=0||(s+=1),s===r){var c=this.trueLength(e,l.textContent);if(!(c<=i))return{node:l,offset:i};i-=c}a=l;break;default:continue}if(r>s){const h={relativeToNode:"after",offset:0};return a?h.node=a:h.node=t,this.isTextNode(h.node)&&(h.offset=this.trueLength(e,h.node.textContent.length)),h}}isTextNode(e){return!!e&&(e.nodeType===ke||e.nodeType===Ee)}correctOffset(e,t,r,i){let n=t,s;if(s="string"==typeof i?this.decodeEntities(e,i):(i.pre=this.decodeEntities(e,i.pre),i.post=this.decodeEntities(e,i.post),i.pre+"."+i.post),!this.isTextNode(t))return{node:t,offset:0};for(;this.isTextNode(n.previousSibling);)n=n.previousSibling;var a,o=n;const l=[];let c="",h=0;for(;this.isTextNode(n)&&(a=this.decodeEntities(e,n.textContent),l[h]=a.length,c+=a,n.nextSibling);)n=n.nextSibling,h++;i=i.pre?i.pre.length:0,i=function(e,t,r){r=r||0;const i=[];let n=0;for(var s;(s=e.match(t))&&(i.push(s.index+r),n+=s.index+s.length,e=e.slice(s.index+s.length),n=l[h];){if(d-=l[h],d<0)return{node:t,offset:r};if(!n.nextSibling||h+1>=[].length)return{node:t,offset:r};h++,n=n.nextSibling}return{node:n,offset:d}}resolveNode(e,t,r,i){if(i=Object.assign({},i||{}),!r)throw new Error("Missing DOM argument");let n;if(0===e&&(n=r.querySelector("package")),!n)for(const h of r.childNodes)if(h.nodeType===Ie){n=h;break}if(n=r,!n)throw new Error("Document incompatible with CFIs");let s=n,a=0,o,l;for(o=t.length-1;0<=o;o--)if(l=t[o],!i.ignoreIDs&&l.nodeID&&(s=r.getElementById(l.nodeID))){a=o+1;break}s=s||n;let c={node:s,offset:0};for(o=a;othis.parts.length-2)throw new Error("index is out of bounds");var i=this.parts[e];if(!i)throw new Error("Missing CFI part for index: "+e);let n=this.resolveNode(e,i,t,r).node;r=n.tagName.toLowerCase();if("itemref"===r&&"spine"===n.parentNode.tagName.toLowerCase()){var s=n.getAttribute("idref");if(!s)throw new Error("Referenced node had not 'idref' attribute");if(n=t.getElementById(s),!n)throw new Error("Specified node is missing from manifest");s=n.getAttribute("href");if(!s)throw new Error("Manifest item is missing href attribute");return s}if("iframe"===r||"embed"===r){s=n.getAttribute("src");if(!s)throw new Error(r+" element is missing 'src' attribute");return s}if("object"===r){var a=n.getAttribute("data");if(!a)throw new Error(r+" element is missing 'data' attribute");return a}if("image"!==r&&"use"!==r)throw new Error("No URI found");a=n.getAttribute("xlink:href");if(!a)throw new Error(r+" element is missing 'xlink:href' attribute");return a}deepClone(e){return JSON.parse(JSON.stringify(e))}resolveLocation(e,t){var r=t.length-1,t=t[r];if(!t)throw new Error("Missing CFI part for index: "+r);const i=this.resolveNode(r,t,e),n=this.deepClone(t[t.length-1]);return delete n.nodeIndex,n.offset||delete i.offset,Object.assign(Object.assign({},n),i)}resolveLast(e,t){if(t=Object.assign({range:!1},t||{}),!this.isRange)return this.resolveLocation(e,this.parts);if(t.range){const r=e.createRange();t=this.getFrom();"before"===t.relativeToNode?r.setStartBefore(t.node,t.offset):"after"===t.relativeToNode?r.setStartAfter(t.node,t.offset):r.setStart(t.node,t.offset);t=this.getTo();return"before"===t.relativeToNode?r.setEndBefore(t.node,t.offset):"after"===t.relativeToNode?r.setEndAfter(t.node,t.offset):r.setEnd(t.node,t.offset),r}return{from:this.resolveLocation(e,this.getFrom()),to:this.resolveLocation(e,this.getTo()),isRange:!0}}resolve(e,t){return this.resolveLast(e,t)}}class Ae extends class{constructor(){this.callbacks={},this.callbacks.base={}}on(e,t){const r=this;if(void 0===e||""===e)return console.warn("wrong names"),!1;if(void 0===t)return console.warn("wrong callback"),!1;const i=this.resolveNames(e);return i.forEach(function(e){e=r.resolveName(e);r.callbacks[e.namespace]instanceof Object||(r.callbacks[e.namespace]={}),r.callbacks[e.namespace][e.value]instanceof Array||(r.callbacks[e.namespace][e.value]=[]),r.callbacks[e.namespace][e.value].push(t)}),this}off(e){const i=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=i.resolveName(e);if("base"!==t.namespace&&""===t.value)delete i.callbacks[t.namespace];else if("base"===t.namespace)for(const r in i.callbacks)i.callbacks[r]instanceof Object&&i.callbacks[r][t.value]instanceof Array&&(delete i.callbacks[r][t.value],0===Object.keys(i.callbacks[r]).length&&delete i.callbacks[r]);else i.callbacks[t.namespace]instanceof Object&&i.callbacks[t.namespace][t.value]instanceof Array&&(delete i.callbacks[t.namespace][t.value],0===Object.keys(i.callbacks[t.namespace]).length&&delete i.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const r=this;const i=t instanceof Array?t:[];let n=this.resolveNames(e);n=this.resolveName(n[0]),setTimeout(()=>{if("base"===n.namespace)for(const e in r.callbacks){if(r.callbacks[e]instanceof Object&&r.callbacks[e][n.value]instanceof Array&&r.callbacks[e][n.value])r.callbacks[e][n.value].forEach(function(e){e.apply(r,i)});else if(this.callbacks[n.namespace]instanceof Object&&r.callbacks[n.namespace][n.value]){if(""===n.value)return console.warn("wrong name"),this;r.callbacks[n.namespace][n.value].forEach(function(e){e.apply(r,i)})}return null}},100)}resolveNames(e){let t=e;return t=t.replace(/[^a-zA-Z0-9 ,/.]/g,""),t=t.replace(/[,/]+/g," "),t=t.split(" "),t}resolveName(e){const t={};var r=e.split(".");return t.original=e,t.value=r[0],t.namespace="base",1v(this,void 0,void 0,function*(){let e=new f(d);this.chapterList=yield e.getChapter(d.toc),this.chapterDocList=yield e.getChapterDoc();var t=this.chapterList,r=this.chapterDocList.map(e=>({href:e.href,label:e.label})),n=yield Promise.all(this.chapterDocList.map(r=>v(this,void 0,void 0,function*(){let t="";if(r.text.load){let e=yield fetch(yield r.text.load()).then(e=>e.blob());t=yield e.text()}return t})));let s=new window.JSZip;s.file("toc.json",JSON.stringify(t)),s.file("sections.json",JSON.stringify(r));let a=[];for(let i=0;ie.blob());e.file(t+"."+Se[o.type],o),r[t].src="imgs/"+i+"/"+t+"."+Se[o.type]}catch(e){console.log(e)}}var l=Array.from(e.getElementsByTagName("link"));for(let r=0;re.blob());t.file(r+"."+Se[c.type],c),e.href="css/"+i+"/"+r+"."+Se[c.type]}catch(e){console.log(e)}}a.push(e.documentElement.innerHTML)}let i=s.folder("chapters");for(let e=0;ev(this,void 0,void 0,function*(){h(yield new Response(e).arrayBuffer())})).catch(e=>{h("err")})}))}resolveChapter(e){var r=e;let i=-1;for(let e=0;e{let e=document.getElementById("page-area");if(e){var a=e.getElementsByTagName("iframe")[0];if(a){a=a.contentDocument;if(a){let e=de(a.body).filter(e=>!Ce(e)),t=e.filter(e=>(e.textContent||"").trim()),r=t.filter(e=>"img"!==e.textContent).map(e=>e.textContent),i=0;return xe(n,s)&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body),t=e.filter(e=>(e.getAttribute("style")===i&&e.setAttribute("style",""),(e.textContent||"").trim()&&e.textContent===r));0!Ce(e));for(let e=0;esetTimeout(e,1e3))),yield ve(this.element,this.mode,this.flatChapter(this.chapterList),this.tempLocation)})}getPosition(){return this.tempLocation}setStyle(t){let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){let e=r.contentDocument;e&&e.body.setAttribute("style",t+e.body.getAttribute("style"))}}}}const Me=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Oe={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Re={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ne={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},De={magic:[16,4,"string"],length:[20,4,"uint"],type:[24,4,"uint"],encoding:[28,4,"uint"],uid:[32,4,"uint"],version:[36,4,"uint"],titleOffset:[84,4,"uint"],titleLength:[88,4,"uint"],localeRegion:[94,1,"uint"],localeLanguage:[95,1,"uint"],resourceStart:[108,4,"uint"],huffcdic:[112,4,"uint"],numHuffcdic:[116,4,"uint"],exthFlag:[128,4,"uint"],trailingFlags:[240,4,"uint"],indx:[244,4,"uint"]},_e={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},Fe={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},He={magic:[0,4,"string"],length:[4,4,"uint"],type:[8,4,"uint"],idxt:[20,4,"uint"],numRecords:[24,4,"uint"],encoding:[28,4,"uint"],language:[32,4,"uint"],total:[36,4,"uint"],ordt:[40,4,"uint"],ligt:[44,4,"uint"],numLigt:[48,4,"uint"],numCncx:[52,4,"uint"]},Pe={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},Ue={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},je={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},$e={magic:[0,4,"string"],numEntries:[8,4,"uint"]},ze={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},We={1252:"windows-1252",65001:"utf-8"},qe={100:["creator","string",!0],101:["publisher"],103:["description"],104:["isbn"],105:["subject","string",!0],106:["date"],108:["contributor","string",!0],109:["rights"],110:["subjectCode","string",!0],112:["source","string",!0],113:["asin"],121:["boundary","uint"],122:["fixedLayout"],125:["numResources","uint"],126:["originalResolution"],127:["zeroGutter"],128:["zeroMargin"],129:["coverURI"],132:["regionMagnification"],201:["coverOffset","uint"],202:["thumbnailOffset","uint"],503:["title"],524:["language","string",!0],527:["pageProgressionDirection"]},Xe={1:["ar","ar-SA","ar-IQ","ar-EG","ar-LY","ar-DZ","ar-MA","ar-TN","ar-OM","ar-YE","ar-SY","ar-JO","ar-LB","ar-KW","ar-AE","ar-BH","ar-QA"],2:["bg"],3:["ca"],4:["zh","zh-TW","zh-CN","zh-HK","zh-SG"],5:["cs"],6:["da"],7:["de","de-DE","de-CH","de-AT","de-LU","de-LI"],8:["el"],9:["en","en-US","en-GB","en-AU","en-CA","en-NZ","en-IE","en-ZA","en-JM",null,"en-BZ","en-TT","en-ZW","en-PH"],10:["es","es-ES","es-MX",null,"es-GT","es-CR","es-PA","es-DO","es-VE","es-CO","es-PE","es-AR","es-EC","es-CL","es-UY","es-PY","es-BO","es-SV","es-HN","es-NI","es-PR"],11:["fi"],12:["fr","fr-FR","fr-BE","fr-CA","fr-CH","fr-LU","fr-MC"],13:["he"],14:["hu"],15:["is"],16:["it","it-IT","it-CH"],17:["ja"],18:["ko"],19:["nl","nl-NL","nl-BE"],20:["no","nb","nn"],21:["pl"],22:["pt","pt-BR","pt-PT"],23:["rm"],24:["ro"],25:["ru"],26:["hr",null,"sr"],27:["sk"],28:["sq"],29:["sv","sv-SE","sv-FI"],30:["th"],31:["tr"],32:["ur"],33:["id"],34:["uk"],35:["be"],36:["sl"],37:["et"],38:["lv"],39:["lt"],41:["fa"],42:["vi"],43:["hy"],44:["az"],45:["eu"],46:["hsb"],47:["mk"],48:["st"],49:["ts"],50:["tn"],52:["xh"],53:["zu"],54:["af"],55:["ka"],56:["fo"],57:["hi"],58:["mt"],59:["se"],62:["ms"],63:["kk"],65:["sw"],67:["uz",null,"uz-UZ"],68:["tt"],69:["bn"],70:["pa"],71:["gu"],72:["or"],73:["ta"],74:["te"],75:["kn"],76:["ml"],77:["as"],78:["mr"],79:["sa"],82:["cy","cy-GB"],83:["gl","gl-ES"],87:["kok"],97:["ne"],98:["fy"]},Ve=(e,t)=>{const r=new e.constructor(e.length+t.length);return r.set(e),r.set(t,e.length),r},Ge=(e,t,r)=>{const i=new e.constructor(e.length+t.length+r.length);return i.set(e),i.set(t,e.length),i.set(r,e.length+t.length),i},Je=new TextDecoder,Ke=e=>Je.decode(e),Ze=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Ye=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,r,i]])=>[e,("string"===i?Ke:Ze)(n.slice(t,t+r))])),Qe=e=>new TextDecoder(We[e]),et=(e,t=0)=>{let r=0,i=0;for(const n of e.subarray(t,t+4))if(r=r<<7|(127&n)>>>0,i++,128&n)break;return{value:r,length:i}},tt=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},rt=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},it=t=>{let r=[];for(let e=0;e>>3,a=3+(7&n);for(let e=0;e{const i=await r(t.huffcdic),{magic:e,offset1:n,offset2:s}=Ye(Ue,i);if("HUFF"!==e)throw new Error("Invalid HUFF record");const d=Array.from({length:256},(e,t)=>n+4*t).map(e=>Ze(i.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),u=[null].concat(Array.from({length:32},(e,t)=>s+8*t).map(e=>[Ze(i.slice(e,e+4)),Ze(i.slice(e+4,e+8))])),f=[];for(let e=1;e{let o=new Uint8Array;var l=8*a.byteLength;for(let s=0;s{var e=r+32,i=e>>3;let n=0n;for(let e=r>>3;e<=i;e++)n=n<<8n|BigInt(t[e]??0);return n>>8n-BigInt(7&e)&0xffffffffn})(a,s));let[e,t,r]=d[c>>>24];if(!e){for(;c>>>32-tl)break;var h=r-(c>>>32-t);let[i,n]=f[h];n||(i=p(i),f[h]=[i,!0]),o=Ve(o,i)}return o};return p},st=async(t,r)=>{const e=await r(t),i=Ye(He,e);if("INDX"!==i.magic)throw new Error("Invalid INDX record");const n=Qe(i.encoding),s=e.slice(i.length);var a=Ye(Pe,s);if("TAGX"!==a.magic)throw new Error("Invalid TAGX section");var o=(a.length-12)/4,l=Array.from({length:o},(e,t)=>new Uint8Array(s.slice(12+4*t,12+4*t+4)));const c={};let h=0;for(let e=0;e>rt(C),null,x]));const P={};for([k,E,B,A]of H){const U=[];if(null!=E)for(let e=0;eZe(r.slice(8*t,8*t+4))).map((e,t,r)=>[e,r[t+1]])}loadRecord(e){e=this.#offsets[e];if(!e)throw new RangeError("Record index out of bounds");return this.#file.slice(...e).arrayBuffer()}async loadMagic(e){e=this.#offsets[e][0];return Ke(await this.#file.slice(e,e+4).arrayBuffer())}}{#start=0;#resourceStart;#decoder;#encoder;#decompress;#removeTrailingEntries;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#getHeaders(await super.loadRecord(0)),this.#resourceStart=this.headers.mobi.resourceStart;let t=8<=this.headers.mobi.version;if(!t){e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#getHeaders(await super.loadRecord(e)),this.#start=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#setup(),new(t?mt:ct)(this).init()}#getHeaders(e){var t=Ye(Ne,e);const r=Ye(De,e);if("MOBI"!==r.magic)throw new Error("Missing MOBI header");var{titleOffset:i,titleLength:n,localeLanguage:s,localeRegion:a}=r;r.title=e.slice(i,i+n);s=Xe[s];r.language=s?.[a>>2]??s?.[0];s=64&r.exthFlag?((t,e)=>{var{magic:r,count:i}=Ye(Fe,t);if("EXTH"!==r)throw new Error("Invalid EXTH header");const n=Qe(e),s={};let a=12;for(let e=0;ee:2===e?it:17480===e?await nt(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const i=1&t,n=tt(t>>>1);this.#removeTrailingEntries=t=>{for(let e=0;e{let t=0;for(const r of e.subarray(-4))128&r&&(t=0),t=t<<7|127&r;return t})(t);t=t.subarray(0,-r)}var e;return i&&(e=1+(3&t[t.length-1]),t=t.subarray(0,-e)),t}}decode(...e){return this.#decoder.decode(...e)}encode(...e){return this.#encoder.encode(...e)}loadRecord(e){return super.loadRecord(this.#start+e)}loadMagic(e){return super.loadMagic(this.#start+e)}loadText(e){return this.loadRecord(e+1).then(e=>new Uint8Array(e)).then(this.#removeTrailingEntries).then(this.#decompress)}async loadResource(e){const t=await super.loadRecord(this.#resourceStart+e);e=Ke(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:r,dataStart:i,keyLength:n,keyStart:s}=Ye(ze,e);const a=new Uint8Array(e.slice(i));if(2&r)for(var i=16===n?1024:1040,o=new Uint8Array(e.slice(s,s+n)),l=Math.min(i,a.length),c=0;c{const{table:r,cncx:i}=await st(e,t),n=r.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:i[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),s=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(s)),t);return n.filter(e=>0===e.headingLevel).map(s)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Me(t?.title||this.decode(e.title)),author:t?.creator?.map(Me),publisher:Me(t?.publisher),language:t?.language??e.language,published:t?.date,description:Me(t?.description),subject:t?.subject?.map(Me),rights:Me(t?.rights)}}async getCover(){var e=this.headers["exth"],e=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=e){e=await this.loadResource(e);return new Blob([e])}}}const ot=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,lt=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class ct{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=Oe.HTML;constructor(e){this.mobi=e}async init(){let t=new Uint8Array;for(let e=0;eString.fromCharCode(e)).join("");this.#sections=[0].concat(Array.from(i.matchAll(ot),e=>e.index)).map((e,t,r)=>i.slice(e,r[t+1])).map(e=>Uint8Array.from(e,e=>e.charCodeAt(0))).map(e=>({book:this,raw:e})).reduce((e,t)=>{var r=e[e.length-1];return t.start=r?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)},[]),this.sections=this.#sections.map((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start}));try{this.landmarks=await this.getGuide();var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var r=this.resolveHref(e)["index"];const n=await this.sections[r].createDocument();let s,a=0,o=0;const l=new Map,c=new Map;this.toc=Array.from(n.querySelectorAll("a[filepos]")).reduce((e,t)=>{var r=(e=>{let t=0;for(;e;){const i=e.parentElement;var r;i&&("p"===(r=i.tagName.toLowerCase())?t+=1.5:"blockquote"===r&&(t+=2)),e=i}return t})(t),i={label:t.innerText?.trim(),href:`filepos:${t.getAttribute("filepos")}`},t=r>o?a+1:r===o?a:l.get(r)??Math.max(0,a-1);if(t>a)s?(s.subitems??=[],s.subitems.push(i),c.set(t,s)):e.push(i);else{const n=c.get(t);(n?n.subitems:e).push(i)}return s=i,a=t,o=r,l.set(r,t),e},[])}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(Array.from(i.matchAll(lt),e=>e[1]))].map(e=>({filepos:e,number:Number(e)})).sort((e,t)=>e.number-t.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#sections[0]);return Array.from(e.getElementsByTagName("reference"),e=>({label:e.getAttribute("title"),type:e.getAttribute("type")?.split(/\s/),href:`filepos:${e.getAttribute("filepos")}`}))}async loadResource(e){if(this.#resourceCache.has(e))return this.#resourceCache.get(e);var t=await this.mobi.loadResource(e),t=URL.createObjectURL(new Blob([t]));return this.#resourceCache.set(e,t),t}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const s of e.querySelectorAll("img[recindex]")){var t=s.getAttribute("recindex");try{s.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const a of e.querySelectorAll("[mediarecindex]")){var r=a.getAttribute("mediarecindex"),i=a.getAttribute("recindex");try{a.src=await this.loadRecindex(r),i&&(a.poster=await this.loadRecindex(i))}catch(e){console.warn(`Failed to load media ${r}`)}}for(const o of e.querySelectorAll("[filepos]")){var n=o.getAttribute("filepos");o.href=`filepos:${n}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const i=t["raw"],n=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let s=i;n.length&&(s=i.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},r)=>{r=n[r+1],e=this.mobi.encode(``);s=Ge(s,e,i.subarray(t,r?.offset))}));var e=this.mobi.decode(s).replaceAll(ot,"");return this.#textCache.set(t,e),e}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);const t=await this.createDocument(e),r=t.createElement("style");t.head.append(r),r.append(t.createTextNode(`blockquote { +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Kookit={})}(this,function(e){"use strict";function v(e,a,o,l){return new(o=o||Promise)(function(r,t){function i(e){try{s(l.next(e))}catch(e){t(e)}}function n(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?r(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(i,n)}s((l=l.apply(e,a||[])).next())})}const w=e=>e?parseFloat(e+""):0,p=e=>parseFloat(e.substring(0,e.length-2)),m=r=>v(void 0,void 0,void 0,function*(){let t="";if(r.load){let e=yield fetch(yield r.load()).then(e=>e.blob());t=yield e.text()}return r.loadAsset&&(t=yield i(t,r.loadAsset)),n(t)}),u=e=>Array.from(e.querySelectorAll("img, image")),i=(n,s)=>v(void 0,void 0,void 0,function*(){let e=(new DOMParser).parseFromString(n,"text/html"),t=u(e);for(let e=0;e{var t=(new DOMParser).parseFromString(e,"text/html");let r=u(t);if(0===r.length)return e;for(let e=0;e{var r=document.createElement("iframe");r.style.width="100%",r.style.border="0",r.style.margin="0",r.style.padding="0",r.style.minHeight="calc(100% - 2px)",r.style.fontSize="100%",r.style.font="inherit",r.scrolling="no",r.tabIndex=0,r.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(r)},c=r=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return 1===parseInt(t.body.scrollWidth/t.body.clientWidth+"")&&(yield new Promise(e=>setTimeout(e,1e3))),{totalPage:"scroll"===r?1:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(w(t.body.scrollLeft)/t.body.clientWidth+"")+1}}}}),g=()=>{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var r=e.querySelectorAll("a, article, cite, div, li, p, span, pre, table, bold, body");for(let e=0;ev(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let n=t.contentDocument;if(n){var s,t=Math.floor(c.clientWidth/12),a=t%2==0?t:t-1;for(s of n.querySelectorAll("img, image")){var o,l=s.parentElement;let e=0,t=0,r=s.naturalWidth,i=s.naturalHeight;"image"===s.tagName&&(o=yield(t=>v(void 0,void 0,void 0,function*(){const e=new Image;return e.src=t,yield e.decode(),e}))(s.getAttribute("xlink:href")),r=o.naturalWidth,i=o.naturalHeight),d.startsWith("CB")&&"scroll"===h?t=l.offsetWidth:d.startsWith("CB")&&"single"===h?(e=c.clientHeight,t=c.clientWidth):r&&i?(i/r>l.clientHeight/l.clientWidth?(e=l.clientHeight,t=parseInt(e*r/i+"")):(t=l.clientWidth,e=parseInt(t*i/r+"")),e>n.body.clientHeight&&(t=parseInt(t*(n.body.clientHeight/e)+""),e=n.body.clientHeight)):e=l&&l.clientWidth&&0i||e/t>i/r?e=t*(i/r):t=e*(r/i)),(t||e)&&s.setAttribute("style",s.getAttribute("style")+";"+`max-width: ${0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){let t=n.contentDocument;if(t){let e=t.createElement("style");e.id="default-style",e.textContent="p,empty-line{display: inherit;margin-block-start: inherit;margin-block-end: inherit;margin-inline-start: inherit;margin-inline-end: inherit;}body{margin: 0px}",t.head.appendChild(e),"scroll"!==i&&(n="double"===i?2:1,i=(i=Math.floor(r.clientWidth/12))%2==0?i:i-1,t.body.setAttribute("style",`width: auto;height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;max-width: inherit;column-fill: auto;column-gap: ${i}px; column-width: ${(r.clientWidth-i)/n}px;`))}}}};class f{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return v(this,void 0,void 0,function*(){return this.chapterList=e?yield Promise.all(e.map(t=>v(this,void 0,void 0,function*(){let e=-1;try{e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1}catch(e){console.log(e)}return{label:t.label||e,href:t.href||"title"+e,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))):yield Promise.all(this.book.sections.map((e,t)=>v(this,void 0,void 0,function*(){return{label:e.label||t,href:e.href||"title"+t,index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return v(this,void 0,void 0,function*(){const r=this.flattenChapters.map(e=>e.index);return this.book.sections.map((e,t)=>-1v(this,void 0,void 0,function*(){const t=this.book.metadata;try{var e=yield this.book.getCover(),r=new FileReader;r.readAsDataURL(e),r.onloadend=()=>{n({name:t.title,author:t.author?t.author[0].name:"",description:t.description,publisher:t.publisher,cover:r.result})}}catch(e){try{var i=t.author&&t.author[0]&&t.author[0].name?t.author[0].name:t.author&&t.author[0]?t.author[0]:t.author||"";n({name:t.title,author:i,description:t.description,publisher:t.publisher,cover:""})}catch(e){console.log(e),s(e)}}}))}}const r=(e,i)=>e.map((e,t,r)=>i(e,t,r)?t:null).filter(e=>null!=e),o=(i,e)=>[-1,...e,i.length].reduce(({xs:e,a:t},r)=>({xs:e?.concat([i.slice(t+1,r)])??[],a:r}),{}).xs,l=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),h=/\d/,d=/^epubcfi\((.*)\)$/,b=e=>e.replace(/[\^[\](),;=]/g,"^$&"),t=e=>d.test(e)?e:`epubcfi(${e})`,x=(e,t)=>r(e,([e])=>e===t),C=e=>{const t=[];let r;for(var[i,n]of e){if("/"===i)t.push({index:n});else{const s=t[t.length-1];if(":"===i)s.offset=n;else if("~"===i)s.temporal=n;else if("@"===i)s.spatial=(s.spatial??[]).concat(n);else if(";s"===i)s.side=n;else if("["===i){if("/"!==r||!n){s.text=(s.text??[]).concat(n);continue}s.id=n}}r=i}return t},L=e=>o(e,x(e,"!")).map(C),T=e=>{var t=(e=>{const t=[];let r,i,n="";var s=e=>(t.push(e),r=null,n=""),a=e=>(n+=e,i=!1);for(const o of Array.from(e.trim()).concat(""))if("^"!==o||i){if("!"===r)s(["!"]);else if(","===r)s([","]);else if("/"===r||":"===r){if(h.test(o)){a(o);continue}s([r,parseInt(n)])}else if("~"===r){if(h.test(o)||"."===o){a(o);continue}s(["~",parseFloat(n)])}else if("@"===r){if(":"===o){s(["@",parseFloat(n)]),r="@";continue}if(h.test(o)||"."===o){a(o);continue}s(["@",parseFloat(n)])}else{if("["===r){";"!==o||i?","!==o||i?"]"!==o||i?a(o):s(["[",n]):(s(["[",n]),r="["):(s(["[",n]),r=";");continue}if(r?.startsWith(";")){"="!==o||i?";"!==o||i?"]"!==o||i?a(o):s([r,n]):(s([r,n]),r=";"):(r=`;${n}`,n="");continue}}"/"!==o&&":"!==o&&"~"!==o&&"@"!==o&&"["!==o&&"!"!==o&&","!==o||(r=o)}else i=!0;return t})((r=e).match(d)?.[1]??r),e=x(t,",");if(!e.length)return L(t);var[r,t,e]=o(t,e).map(L);return{parent:r,start:t,end:e}},S=({index:e,id:t,offset:r,temporal:i,spatial:n,text:s,side:a})=>{var o=a?`;s=${a}`:"";return`/${e}`+(t?`[${b(t)}${o}]`:"")+(null!=r&&e%2?`:${r}`:"")+(i?`~${i}`:"")+(n?`@${n.join(":")}`:"")+(s||!t&&a?"["+(s?.map(b)?.join(",")??"")+o+"]":"")},I=e=>e.parent?[e.parent,e.start,e.end].map(I).join(","):e.map(e=>e.map(S).join("")).join("!"),k=e=>t(I(e)),E=(e,t)=>"string"==typeof e?k(E(T(e),t)):e.parent?l(e.parent,e[t?"end":"start"]):e,B=({nodeType:e})=>3===e||4===e,A=({nodeType:e})=>1===e,M=e=>{const t=Array.from(e.childNodes).filter(e=>B(e)||A(e)).reduce((e,t)=>{let r=e[e.length-1];return r?B(t)?Array.isArray(r)?r.push(t):B(r)?e[e.length-1]=[r,t]:e.push(t):A(r)?e.push(null,t):e.push(t):e.push(t),e},[]);return A(t[0])&&t.unshift("first"),A(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},O=(e,t)=>e?M(e)[t]:null,R=(e,t)=>{var r,i=t[t.length-1]["id"];if(i){i=e.ownerDocument.getElementById(i);if(i)return{node:i,offset:0}}for({index:r}of t){var n=O(e,r);if("first"===n)return{node:e.firstChild??e};if("last"===n)return{node:e.lastChild??e};if("before"===n)return{node:e,before:!0};if("after"===n)return{node:e,after:!0};e=n}var s=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:s};let a=0;for(const l of e){var o=l.nodeValue["length"];if(a+o>=s)return{node:l,offset:s-a};a+=o}},N=(t,r)=>{var{parentNode:e,id:i}=t;const n=M(e);var s=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),a=n[s];if(Array.isArray(a)){let e=0;for(const o of a){if(o===t){e+=r;break}e+=o.nodeValue.length}r=e}s={id:i,index:s,offset:r};return e!==t.ownerDocument.documentElement?N(e).concat(s):[s]},D=(e,t)=>R(e.documentElement,E(t)).node,_={CONTAINER:"urn:oasis:names:tc:opendocument:xmlns:container",XHTML:"http://www.w3.org/1999/xhtml",OPF:"http://www.idpf.org/2007/opf",EPUB:"http://www.idpf.org/2007/ops",DC:"http://purl.org/dc/elements/1.1/",DCTERMS:"http://purl.org/dc/terms/",ENC:"http://www.w3.org/2001/04/xmlenc#",NCX:"http://www.daisy.org/z3986/2005/ncx/",XLINK:"http://www.w3.org/1999/xlink",SMIL:"http://www.w3.org/ns/SMIL"},F={XML:"application/xml",NCX:"application/x-dtbncx+xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml",JS:/\/(x-)?(javascript|ecmascript)/},H=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),P=e=>e?e.trim().replace(/\s{2,}/g," "):"",U=(t,r,e)=>e?e=>e.getAttribute(t)?.split(/\s/)?.includes(r):"function"==typeof r?e=>r(e.getAttribute(t)):e=>e.getAttribute(t)===r,j=(...e)=>t=>t?Object.fromEntries(e.map(e=>[H(e),t.getAttribute(e)])):null,$=e=>P(e?.textContent),z=(e,r)=>{e=e.lookupNamespaceURI(null)===r||e.lookupPrefix(r);const i=e?(e,t)=>e=>e.namespaceURI===r&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(i(e,t)),$$:(e,t)=>[...e.children].filter(i(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(r,t)]:(e,t)=>[...e.getElementsByTagName(r,t)]}},W=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var r="whatever://whatever/";return decodeURI(new URL(t,r+e).href.replace(r,""))}catch(e){return console.warn(e),t}},q=e=>/^(?!blob)\w+:/i.test(e),X=async(e,t,r)=>{const i=[];e.replace(t,(...e)=>(i.push(e),null));const n=[];for(const s of i)n.push(await r(...s));return e.replace(t,()=>n.shift())},V=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");var G={attrs:["dir","xml:lang"]},J={name:"alternate-script",many:!0,...G,props:["file-as"]},K={many:!0,...G,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",J]};const Z=[{name:"title",many:!0,...G,props:["title-type","display-seq","file-as",J]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...K},{name:"contributor",...K},{name:"publisher",...G,props:["file-as",J]},{name:"description",...G,props:[J]},{name:"rights",...G,props:[J]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...G,props:["term","authority",J]},{name:"belongs-to-collection",type:"meta",many:!0,...G,props:["collection-type","group-position","dcterms:identifier","file-as",J,{name:"belongs-to-collection",recursive:!0}]}],Y=(e,s=e=>e)=>{const{$:a,$$:r,$$$:t}=z(e,_.XHTML),i=n=>e=>{const t=a(e,"a")??a(e,"span");var r=a(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(s(e)):null;const i={label:$(t)||t?.getAttribute("title"),href:e,subitems:o(r)};return n&&(i.type=t?.getAttributeNS(_.EPUB,"type")?.split(/\s/)),i},o=(e,t)=>e?r(e,"li").map(i(t)):null;var n=(e,t)=>o(a(e,"ol"),t);let l=null,c=null,h=null,d=[];for(const u of t(e,"nav")){const f=u.getAttributeNS(_.EPUB,"type")?.split(/\s/)??[];f.includes("toc")?l??=n(u):f.includes("page-list")?c??=n(u):f.includes("landmarks")?h??=n(u,!0):d.push({label:$(u.firstElementChild),type:f,list:n(u)})}return{toc:l,pageList:c,landmarks:h,others:d}},Q=(r,s=e=>e)=>{const{$:a,$$:o}=z(r,_.NCX),l=e=>{var t=a(e,"navLabel");const r=a(e,"content");var i=$(t),t=(t=r.getAttribute("src"))?decodeURI(s(t)):null;if("navPoint"!==e.localName)return{label:i,href:t};{const n=o(e,"navPoint");return{label:i,href:t,subitems:n.length?n.map(l):null}}},i=(e,t)=>o(e,t).map(l);var e=(e,t)=>{e=a(r.documentElement,e);return e?i(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:o(r.documentElement,"navList").map(e=>({label:$(a(e,"navLabel")),list:i(e,"navTarget")}))}},ee=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[r,i,n]=t;return 60*r*60+60*i+n}if(2===t.length){var[t,s]=t;return 60*t+s}var[s,e]=e.split(/(?=[^\d.])/);return parseFloat(s)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},te=(e,i=e=>e)=>{const{$:n,$$$:t}=z(e,_.SMIL);return t(e,"par").map(e=>{var t=n(e,"text")?.getAttribute("src")?.split("#")?.[1];const r=n(e,"audio");return r?{id:t,audio:{src:(e=r.getAttribute("src"))?decodeURI(i(e)):null,clipBegin:ee(r.getAttribute("clipBegin")),clipEnd:ee(r.getAttribute("clipEnd"))}}:{id:t}})},re=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ie=e=>$(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(_.DC,"identifier")[0]),ne=async(e,t,r)=>{const i=new Uint8Array(await r.slice(0,t).arrayBuffer());t=Math.min(t,i.length);for(var n=0;n{e=(new TextEncoder).encode(e),e=await globalThis.crypto.subtle.digest("SHA-1",e);return new Uint8Array(e)})=>({"http://www.idpf.org/2008/embedding":{key:e=>t(ie(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>ne(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const r=(e=>{for(const r of e.getElementsByTagNameNS(_.DC,"identifier")){var[t]=$(r).split(":").slice(-1);if(re.test(t))return t}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},(e,t)=>parseInt(r.slice(2*t,2*t+2),16))},decode:(e,t)=>ne(e,1024,t)}});class ae{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var r,i;if(e)for({algorithm:r,uri:i}of Array.from(e.getElementsByTagNameNS(_.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(_.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(_.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(r)){const n=this.#algorithms[r];if(!n){console.warn("Unknown encryption algorithm");continue}const s=await n.key(t);this.#decoders.set(r,e=>n.decode(s,e))}this.#uris.set(i,r)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class oe{constructor({opf:e,resolveHref:i}){this.opf=e;const{$:t,$$:r,$$$:n}=z(e,_.OPF);var s=t(e.documentElement,"manifest");const a=t(e.documentElement,"spine"),o=r(a,"itemref");this.manifest=r(s,"item").map(j("href","id","media-type","properties","media-overlay")).map(e=>(e.href=i(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=o.map(j("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=a.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(a.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===F.NCX))?.href;s=t(e.documentElement,"guide");s&&(this.guide=r(s,"reference").map(j("type","title","href")).map(({type:e,title:t,href:r})=>({label:t,type:e.split(/\s/),href:i(r)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(n(e,"meta").find(U("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var r,i,n=e[0]["parentNode"];const s=N(n);for([r,i]of M(n).entries()){var a=e[t.length];i===a&&t.push(k([s.concat({id:a.id,index:r})]))}return t})(o)}getItemByID(t){return this.manifest.find(e=>e.id===t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>e.properties?.includes(t))}resolveCFI(e){const t=T(e),r=(t.parent??t).shift();let i=D(this.opf,r);i&&"idref"!==i.nodeName&&(r.at(-1).id=null,i=D(this.opf,r));const n=i?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var r=E(t),i=E(t,!0),t=e.documentElement,r=R(t,r[0]),i=R(t,i[0]);const n=e.createRange();return r.before?n.setStartBefore(r.node):r.after?n.setStartAfter(r.node):n.setStart(r.node,r.offset),i.before?n.setEndBefore(i.node):i.after?n.setEndAfter(i.node):n.setEnd(i.node,i.offset),n})(e,t)}}}class le{#cache=new Map;#children=new Map;#refCount=new Map;allowScript=!1;constructor({loadText:e,loadBlob:t,resources:r}){this.loadText=e,this.loadBlob=t,this.manifest=r.manifest,this.assets=r.manifest}createURL(e,t,r,i){if(!t)return"";r=URL.createObjectURL(new Blob([t],{type:r}));if(this.#cache.set(e,r),this.#refCount.set(e,1),i){const n=this.#children.get(i);n?n.push(e):this.#children.set(i,[e])}return r}ref(e,t){const r=this.#children.get(t);return r?.includes(e)||(this.#refCount.set(e,this.#refCount.get(e)+1),r?r.push(e):this.#children.set(t,[e])),this.#cache.get(e)}unref(e){if(this.#refCount.has(e)){var t=this.#refCount.get(e)-1;if(t<1){URL.revokeObjectURL(this.#cache.get(e)),this.#cache.delete(e),this.#refCount.delete(e);const r=this.#children.get(e);if(r)for(;r.length;)this.unref(r.pop());this.#children.delete(e)}else this.#refCount.set(e,t)}}async loadItem(e,t=[]){if(!e)return null;const{href:r,mediaType:i}=e;var n=F.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var s=t.at(-1);return this.#cache.has(r)?this.ref(r,s):(n||[F.XHTML,F.HTML,F.CSS,F.SVG].includes(i))&&t.every(e=>e!==r)?this.loadReplaced(e,t):this.createURL(r,await this.loadBlob(r),i,s)}async loadHref(e,t,r=[]){if(q(e))return e;const i=W(e,t);let n=this.manifest.find(e=>e.href===i);return n=n||{href:i,mediaType:""},this.loadItem(n,r.concat(t))}async loadReplaced(e,n=[]){const{href:s,mediaType:r}=e;var i,a=n.at(-1),o=await this.loadText(s);if(!o)return null;if([F.XHTML,F.HTML,F.SVG].includes(r)){let t=(new DOMParser).parseFromString(o,r);if(r===F.XHTML&&t.querySelector("parsererror")&&(console.warn(t.querySelector("parsererror").innerText),e.mediaType=F.HTML,t=(new DOMParser).parseFromString(o,e.mediaType)),[F.XHTML,F.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(i=await X(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,r,i)=>this.loadHref(r,s,n).then(e=>`${t}${e}${i}`)),e.replaceWith(t.createProcessingInstruction(e.target,i))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),s,n));for(const h of t.querySelectorAll("link[href]"))await l(h,"href");for(const d of t.querySelectorAll("[src]"))await l(d,"src");for(const u of t.querySelectorAll("[poster]"))await l(u,"poster");for(const f of t.querySelectorAll("object[data]"))await l(f,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(_.XLINK,"href",await this.loadHref(p.getAttributeNS(_.XLINK,"href"),s,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,s,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),s,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(s,c,e.mediaType,a)}const c=r===F.CSS?await this.replaceCSS(o,s,n):await this.replaceString(o,s,n);return this.createURL(s,c,r,a)}async replaceCSS(e,r,i=[]){e=await X(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,r,i).then(e=>`url("${e}")`));const t=await X(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,r,i).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,s=window?.innerHeight??600;return t.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/gi,(e,t)=>parseFloat(t)*s/100+"px").replace(/page-break-(after|before|inside)/gi,(e,t)=>`-webkit-column-break-${t}`)}replaceString(e,a,t=[]){const o=new Map,r=this.assets.map(e=>{if(e.href!==a){var t=((e,t)=>{if(!e)return t;const r=e.replace(/\/$/,"").split("/"),i=t.replace(/\/$/,"").split("/");t=(r.length>i.length?r:i).findIndex((e,t)=>r[t]!==i[t]);return t<0?"":Array(r.length-t).fill("..").concat(i.slice(t)).join("/")})(a.slice(0,a.lastIndexOf("/")+1),e.href),r=encodeURI(t),i="/"+e.href,n=encodeURI(i),n=new Set([t,r,i,n]);for(const s of n)o.set(s,e);return Array.from(n)}}).flat().filter(e=>e);if(!r.length)return e;var i=new RegExp(r.map(V).join("|"),"g");return X(e,i,async e=>this.loadItem(o.get(e.replace(/^\//,"")),t.concat(a)))}unloadItem(e){this.unref(e?.href)}}class ce{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:r,sha1:i}){this.loadText=e,this.loadBlob=t,this.getSize=r,this.#encryption=new ae(se(i))}#parseXML(e){return e?this.parser.parseFromString(e,F.XML):null}async#loadXML(e){return this.#parseXML(await this.loadText(e))}async init(){const e=await this.#loadXML("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");var t=Array.from(e.getElementsByTagNameNS(_.CONTAINER,"rootfile"),j("full-path","media-type")).filter(e=>"application/oebps-package+xml"===e.mediaType);if(!t.length)throw new Error("No package document defined in container");const r=t[0].fullPath;var i=await this.#loadXML(r);if(!i)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,i),this.resources=new oe({opf:i,resolveHref:e=>W(e,r)});const s=new le({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#encryption.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map((e,t)=>{var{idref:r,linear:i,properties:e=[]}=e;const n=this.resources.getItemByID(r);return n?{id:this.resources.getItemByID(r)?.href,load:()=>s.loadItem(n),unload:()=>s.unloadItem(n),createDocument:()=>this.loadDocument(n),size:this.getSize(n.href),cfi:this.resources.cfis[t],linear:i,pageSpread:(e=>{for(const t of e){if("page-spread-left"===t||"rendition:page-spread-left"===t)return"left";if("page-spread-right"===t||"rendition:page-spread-right"===t)return"right";if("rendition:page-spread-center"===t)return"center"}})(e),resolveHref:e=>W(e,n.href),loadMediaOverlay:()=>this.loadMediaOverlay(n)}:(console.warn(`Could not find item with ID "${r}" in manifest`),null)}).filter(e=>e);const{navPath:n,ncxPath:a}=this.resources;if(n)try{var o=Y(await this.#loadXML(n),e=>W(e,n));this.toc=o.toc,this.pageList=o.pageList,this.landmarks=o.landmarks}catch(e){console.warn(e)}if(!this.toc&&a)try{var l=Q(await this.#loadXML(a),e=>W(e,a));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:h,media:d}=(e=>{const{$:t,$$:r}=z(e,_.OPF),i=t(e.documentElement,"metadata"),s=Array.from(i.children),l=(a,t)=>{if(!t)return null;const{props:e=[],attrs:r=[]}=a,i=$(t);if(!e.length&&!r.length)return i;var n=t.getAttribute("id");const o=n?s.filter(U("refines","#"+n)):[];return Object.fromEntries([["value",i]].concat(e.map(e=>{var{many:t,recursive:r}=e,i="string"==typeof e?e:e.name,n=U("property",i);const s=r?a:e;return[H(i),t?o.filter(n).map(e=>l(s,e)):l(s,o.find(n))]})).concat(r.map(e=>[H(e),t.getAttribute(e)])))},a=s.filter(U("refines",null));e=t=>Object.fromEntries(r(i,"meta").filter(U("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),$(e)]));return{metadata:Object.fromEntries(Z.map(t=>{const{type:e,name:r,many:i}=t;var n="meta"===e?e=>e.namespaceURI===_.OPF&&e.getAttribute("property")===r:e=>e.namespaceURI===_.DC&&e.localName===r;return[H(r),i?a.filter(n).map(e=>l(t,e)):l(t,a.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(i);this.rendition=h,this.media=d,d.duration=ee(d.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=c;l=c?.title?.[0];this.metadata={title:l?.value,sortAs:l?.fileAs,language:c?.language,identifier:ie(i),description:c?.description?.value,publisher:c?.publisher?.value,published:c?.date,modified:c?.dctermsModified,subject:c?.subject?.filter(({value:e,code:t})=>e||t)?.map(({value:e,code:t,scheme:r})=>({name:e,code:t,scheme:r})),rights:c?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};i=r=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:u[e])??r))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[r],e]};return c?.creator?.map(i("author"))?.concat(c?.contributor?.map?.(i("contributor")))?.forEach(([e,t])=>e.forEach(e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})),this}async loadDocument(e){var t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){e=e.mediaOverlay;if(!e)return null;const t=this.resources.getItemByID(e);e=await this.#loadXML(t.href);return te(e,e=>W(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,r]=e.split("#"),i=this.resources.getItemByHref(decodeURI(t));return i?{index:this.resources.spine.findIndex(({idref:e})=>e===i.id),anchor:r?e=>((e,t)=>e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`))(e,r):()=>0}:null}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return q(e)}async getCover(){var e=this.resources?.cover;return e?.href?new Blob([await this.loadBlob(e.href)],{type:e.mediaType}):null}async getCalibreBookmarks(){const e=await this.loadText("META-INF/calibre_bookmarks.txt");var t="encoding=json+base64:";if(e?.startsWith(t)){t=atob(e.slice(t.length));return JSON.parse(t)}}}let he=!1;const de=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),ue=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),fe=(h,d,u,f,p,m,g,y,b)=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t,r,i,n,s,a,o,l,c=e.getElementsByTagName("iframe")[0];if(c){let e=c.contentDocument;e&&(c=(t=Math.floor(h.clientWidth/12))%2==0?t:t-1,t=h.clientWidth,0{let n=window._.findLastIndex(r,{href:t});return n=t&&-1v(void 0,void 0,void 0,function*(){var e=parseInt(a.chapterDocIndex||"0"),t=a.chapterHref||"";0===e||(t=pe(e,t,i,"prev"))&&(a.text="prevChapter",a.page="",yield ge(t.index,t.label,t.href,i,r,n,s,a))}),ge=(r,l,c,h,d,u,f,p)=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){let t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;var s,i,n,a,o;e&&(e.body.innerHTML="",t.height="0px",e.body.scrollTo(0,0),(-1===(r=l&&!r||h[r]&&h[r].label&&l&&l!==h[r].label&&-1===c.indexOf("#")?window._.findLastIndex(h,{label:l}):r)||r>h.length-1)&&(r=0),e.body.innerHTML=yield m(h[r].text),s=e,yield v(void 0,void 0,void 0,function*(){var t=Array.from(s.getElementsByTagName("link"));for(let e=0;e{console.log("finished")}}let r=[];for(let e=0;e{n.addEventListener("load",e)}))}try{yield Promise.race([Promise.all(r),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Timeout"))},1e3)})])}catch(e){console.log(e)}}),p.chapterTitle=l,p.chapterHref=c,p.chapterDocIndex=r+"",p.percentage=r/h.length+"",p.text="",i=d,n=u,a=t,o=f,yield v(void 0,void 0,void 0,function*(){let t=a.contentDocument;if(t)if(yield Promise.all(Array.from([...t.images,...t.querySelectorAll("image")]).map(t=>t.complete?Promise.resolve(0!==t.naturalHeight):new Promise(e=>{t.addEventListener("load",()=>e(!0)),t.addEventListener("error",()=>e(!1))}))).then(e=>{e.every(e=>e)?console.log("all images loaded successfully!!"):console.log("some images failed to load, all finished loading")}),yield y(i,n,o),g(),"scroll"!==n){if(a.height=i.clientHeight+"px","double"===n){var r=Math.floor(i.clientWidth/12),r=(i.clientWidth+(r%2==0?r:r-1))/2;if((t.body.scrollWidth-t.body.clientWidth)/r%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+t.body.clientHeight+"px; display: inline-block; width: "+r+"px"),t.body.appendChild(e)}}}else a.height=t.body.scrollHeight+"px",a.height=t.body.scrollHeight+"px"}),ye(d,u,"","","",""))}}}),ye=(l,c,h,d,u,f)=>v(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let n=s.contentDocument;if(n){let t=0,r=0,i=n.body;if(f&&"scroll"!==c){var a=Math.floor(l.clientWidth/12),s=a%2==0?a:a-1,a=p(getComputedStyle(l).width);r=(a+s)*(parseInt(f)-1)}else if(h){let e=de(n.body);var o=e.filter((e,t)=>ue(e.textContent).slim()&&(ue(e.textContent).slim()===ue(h).slim()||ue(e.textContent).slim()===window.ChineseS2T.t2s(ue(h).slim())||ue(e.textContent).slim()===window.ChineseS2T.s2t(ue(h)).slim())&&(Math.abs(t-parseInt(d))<2||"search"===d||"ignore"===d||"next"===d));if(0===o.length)return void console.log("failed");i=be(o[0],l,c),r=i?w(i.offsetLeft)-w(i.marginLeft||parseFloat(getComputedStyle(i).marginLeft)):"prevChapter"===h?n.body.scrollWidth:0,t=i?w(i.offsetTop)-w(i.marginTop||parseFloat(getComputedStyle(i).marginTop)):0}else if(u&&-1{var i=Math.floor(t.clientWidth/12),i=i%2==0?i:i-1;return"scroll"!==r&&parseInt(w(e.offsetLeft)-w(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft))+"")%((t.clientWidth+i)/2)!=0&&e.parentElement?be(e.parentElement,t,r):e},ve=(s,a,o,l)=>v(void 0,void 0,void 0,function*(){if(!he){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){var i=i.contentDocument;if(i){let t=de(i.body);var i=t.filter(e=>Le(s,e,a)&&(e.textContent||"").trim()),n=i[0];let r=0;for(let e=0;e{let e=i.chapterHref||"",n=e.lastIndexOf("#"),s=e.substring(0,n),a=e.substring(n+1);for(let e=0;e-1)i.chapterHref=e}}})(i,o,l),n&&!((e,t,r)=>{let i=Math.floor(t.clientWidth/12),n=i%2===0?i:i-1;if(Math.abs(e.offsetLeft-be(e,t,r).offsetLeft)>(t.clientWidth+n)/2)return true;else return false})(n,s,a)?(l.text=n&&n.textContent||"",l.count=r+"",l.page=""):l.page=(null===(i=yield c(a))||void 0===i?void 0:i.currentPage)+"",he=!0,setTimeout(()=>{he=!1},100)}}}}}),we=(r,e,i,n,s,a)=>v(void 0,void 0,void 0,function*(){var e=parseInt(a.chapterDocIndex||"0"),t=a.chapterHref||"";e>=i.length-1?a.percentage="1":(t=pe(e,t,i,"next"))&&(a.page="",yield ge(t.index,t.label,t.href,i,r,n,s,a))}),xe=(r,i)=>{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body).filter(e=>!Ce(e)),t=e.filter(e=>Le(r,e,i)&&(e.textContent||"").trim());return t.filter(e=>"img"!==e.textContent).map(e=>e.textContent)}}}},Ce=e=>{var t=e.children;let r=!1;var i=/^(address|section|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i;if(Array.from(t).filter(e=>i.test(e.nodeName)).length<3)return!1;for(var n=0;n{var i,n=!1,s=t.getBoundingClientRect();return"scroll"!==r&&t.textContent&&t.textContent.trim()?n=-10<(i=s.left)&&i<=e.clientWidth:"scroll"===r&&t.textContent&&t.textContent.trim()?n=(t=s.top)>=e.scrollTop&&t<=e.scrollTop+e.clientHeight:"scroll"!==r&&(n=0<=(s=s.left)&&s<=e.clientWidth),n};const Te={svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",html:"text/html",htm:"text/html",xml:"text/xml",xhtml:"application/xhtml+xml",css:"text/css"},Se={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","application/zip":"zip","application/x-rar-compressed":"rar","application/x-7z-compressed":"7z","application/x-tar":"tar","text/html":"html","text/xml":"xml","application/xhtml+xml":"xhtml","text/css":"css"},Ie=Node.ELEMENT_NODE,ke=Node.TEXT_NODE,Ee=Node.CDATA_SECTION_NODE;class Be{constructor(r,i){this.isRange=!1,this.opts=Object.assign({flattenRange:!1,stricter:!0},i||{}),this.cfi=r,this.parts=[];var n,s,a,i=(r=r.trim()).match(/^epubcfi\((.*)\)$/);if(!i)throw new Error("Not a valid CFI");if(!(i.length<2)){r=i[1]||"";let e=[],t=0;for(;r.length;){if({parsed:n,offset:s,newDoc:a}=this.parse(r),!n||null===s)throw new Error("Parsing failed");if(t&&a)throw new Error("CFI is a range that spans multiple documents. This is not allowed");e.push(n),(a||r.length-s<=0)&&(2===t?this.to=e:this.parts.push(e),e=[]),","===(r=r.slice(s))[0]&&(0===t?(e.length&&this.parts.push(e),e=[]):1===t&&(e.length&&(this.from=e),e=[]),r=r.slice(1),t++)}this.from&&this.from.length&&(!this.opts.flattenRange&&this.to&&this.to.length?this.isRange=!0:(this.parts=this.parts.concat(this.from),delete this.from,delete this.to)),this.opts.stricter&&this.removeIllegalOpts()}}removeIllegalOpts(e){if(!e)if(this.from){if(this.removeIllegalOpts(this.from),!this.to)return;e=this.to}else e=this.parts;let t,r,i,n;for(t=0;tthis.compare(e,t))}static compare(e,t){let r=e.get(),i=t.get();if(e.isRange||t.isRange){if(e.isRange&&t.isRange){var n=this.comparePath(r.from,i.from);return n?n:this.comparePath(r.to,i.to)}return e.isRange&&(r=r.from),t.isRange&&(i=i.from),this.comparePath(r,i)}return this.comparePath(r,i)}static compareParts(e,t){var r,i,n,s,a=Math.max(e.length,t.length);let o,l,c,h;for(o=0;o=r)return"img"===l.tagName.toLowerCase()&&i?{node:l,offset:i}:{node:l,offset:0}}else{if(s+=1,s===r)return"img"===l.tagName.toLowerCase()&&i?{node:l,offset:i}:{node:l,offset:0};if(s>r)return a?{node:a,offset:this.trueLength(e,a.textContent)}:{node:t,offset:0}}a=l;break;case ke:case Ee:if(0!==s&&s%2!=0||(s+=1),s===r){var c=this.trueLength(e,l.textContent);if(!(c<=i))return{node:l,offset:i};i-=c}a=l;break;default:continue}if(r>s){const h={relativeToNode:"after",offset:0};return a?h.node=a:h.node=t,this.isTextNode(h.node)&&(h.offset=this.trueLength(e,h.node.textContent.length)),h}}isTextNode(e){return!!e&&(e.nodeType===ke||e.nodeType===Ee)}correctOffset(e,t,r,i){let n=t,s;if(s="string"==typeof i?this.decodeEntities(e,i):(i.pre=this.decodeEntities(e,i.pre),i.post=this.decodeEntities(e,i.post),i.pre+"."+i.post),!this.isTextNode(t))return{node:t,offset:0};for(;this.isTextNode(n.previousSibling);)n=n.previousSibling;var a,o=n;const l=[];let c="",h=0;for(;this.isTextNode(n)&&(a=this.decodeEntities(e,n.textContent),l[h]=a.length,c+=a,n.nextSibling);)n=n.nextSibling,h++;i=i.pre?i.pre.length:0,i=function(e,t,r){r=r||0;const i=[];let n=0;for(var s;(s=e.match(t))&&(i.push(s.index+r),n+=s.index+s.length,e=e.slice(s.index+s.length),n=l[h];){if(d-=l[h],d<0)return{node:t,offset:r};if(!n.nextSibling||h+1>=[].length)return{node:t,offset:r};h++,n=n.nextSibling}return{node:n,offset:d}}resolveNode(e,t,r,i){if(i=Object.assign({},i||{}),!r)throw new Error("Missing DOM argument");let n;if(0===e&&(n=r.querySelector("package")),!n)for(const h of r.childNodes)if(h.nodeType===Ie){n=h;break}if(n=r,!n)throw new Error("Document incompatible with CFIs");let s=n,a=0,o,l;for(o=t.length-1;0<=o;o--)if(l=t[o],!i.ignoreIDs&&l.nodeID&&(s=r.getElementById(l.nodeID))){a=o+1;break}s=s||n;let c={node:s,offset:0};for(o=a;othis.parts.length-2)throw new Error("index is out of bounds");var i=this.parts[e];if(!i)throw new Error("Missing CFI part for index: "+e);let n=this.resolveNode(e,i,t,r).node;r=n.tagName.toLowerCase();if("itemref"===r&&"spine"===n.parentNode.tagName.toLowerCase()){var s=n.getAttribute("idref");if(!s)throw new Error("Referenced node had not 'idref' attribute");if(n=t.getElementById(s),!n)throw new Error("Specified node is missing from manifest");s=n.getAttribute("href");if(!s)throw new Error("Manifest item is missing href attribute");return s}if("iframe"===r||"embed"===r){s=n.getAttribute("src");if(!s)throw new Error(r+" element is missing 'src' attribute");return s}if("object"===r){var a=n.getAttribute("data");if(!a)throw new Error(r+" element is missing 'data' attribute");return a}if("image"!==r&&"use"!==r)throw new Error("No URI found");a=n.getAttribute("xlink:href");if(!a)throw new Error(r+" element is missing 'xlink:href' attribute");return a}deepClone(e){return JSON.parse(JSON.stringify(e))}resolveLocation(e,t){var r=t.length-1,t=t[r];if(!t)throw new Error("Missing CFI part for index: "+r);const i=this.resolveNode(r,t,e),n=this.deepClone(t[t.length-1]);return delete n.nodeIndex,n.offset||delete i.offset,Object.assign(Object.assign({},n),i)}resolveLast(e,t){if(t=Object.assign({range:!1},t||{}),!this.isRange)return this.resolveLocation(e,this.parts);if(t.range){const r=e.createRange();t=this.getFrom();"before"===t.relativeToNode?r.setStartBefore(t.node,t.offset):"after"===t.relativeToNode?r.setStartAfter(t.node,t.offset):r.setStart(t.node,t.offset);t=this.getTo();return"before"===t.relativeToNode?r.setEndBefore(t.node,t.offset):"after"===t.relativeToNode?r.setEndAfter(t.node,t.offset):r.setEnd(t.node,t.offset),r}return{from:this.resolveLocation(e,this.getFrom()),to:this.resolveLocation(e,this.getTo()),isRange:!0}}resolve(e,t){return this.resolveLast(e,t)}}class Ae extends class{constructor(){this.callbacks={},this.callbacks.base={}}on(e,t){const r=this;if(void 0===e||""===e)return console.warn("wrong names"),!1;if(void 0===t)return console.warn("wrong callback"),!1;const i=this.resolveNames(e);return i.forEach(function(e){e=r.resolveName(e);r.callbacks[e.namespace]instanceof Object||(r.callbacks[e.namespace]={}),r.callbacks[e.namespace][e.value]instanceof Array||(r.callbacks[e.namespace][e.value]=[]),r.callbacks[e.namespace][e.value].push(t)}),this}off(e){const i=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=i.resolveName(e);if("base"!==t.namespace&&""===t.value)delete i.callbacks[t.namespace];else if("base"===t.namespace)for(const r in i.callbacks)i.callbacks[r]instanceof Object&&i.callbacks[r][t.value]instanceof Array&&(delete i.callbacks[r][t.value],0===Object.keys(i.callbacks[r]).length&&delete i.callbacks[r]);else i.callbacks[t.namespace]instanceof Object&&i.callbacks[t.namespace][t.value]instanceof Array&&(delete i.callbacks[t.namespace][t.value],0===Object.keys(i.callbacks[t.namespace]).length&&delete i.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const r=this;const i=t instanceof Array?t:[];let n=this.resolveNames(e);n=this.resolveName(n[0]),setTimeout(()=>{if("base"===n.namespace)for(const e in r.callbacks){if(r.callbacks[e]instanceof Object&&r.callbacks[e][n.value]instanceof Array&&r.callbacks[e][n.value])r.callbacks[e][n.value].forEach(function(e){e.apply(r,i)});else if(this.callbacks[n.namespace]instanceof Object&&r.callbacks[n.namespace][n.value]){if(""===n.value)return console.warn("wrong name"),this;r.callbacks[n.namespace][n.value].forEach(function(e){e.apply(r,i)})}return null}},100)}resolveNames(e){let t=e;return t=t.replace(/[^a-zA-Z0-9 ,/.]/g,""),t=t.replace(/[,/]+/g," "),t=t.split(" "),t}resolveName(e){const t={};var r=e.split(".");return t.original=e,t.value=r[0],t.namespace="base",1v(this,void 0,void 0,function*(){let e=new f(d);this.chapterList=yield e.getChapter(d.toc),this.chapterDocList=yield e.getChapterDoc();var t=this.chapterList,r=this.chapterDocList.map(e=>({href:e.href,label:e.label})),n=yield Promise.all(this.chapterDocList.map(r=>v(this,void 0,void 0,function*(){let t="";if(r.text.load){let e=yield fetch(yield r.text.load()).then(e=>e.blob());t=yield e.text()}return t})));let s=new window.JSZip;s.file("toc.json",JSON.stringify(t)),s.file("sections.json",JSON.stringify(r));let a=[];for(let i=0;ie.blob());e.file(t+"."+Se[o.type],o),r[t].src="imgs/"+i+"/"+t+"."+Se[o.type]}catch(e){console.log(e)}}var l=Array.from(e.getElementsByTagName("link"));for(let r=0;re.blob());t.file(r+"."+Se[c.type],c),e.href="css/"+i+"/"+r+"."+Se[c.type]}catch(e){console.log(e)}}a.push(e.documentElement.innerHTML)}let i=s.folder("chapters");for(let e=0;ev(this,void 0,void 0,function*(){h(yield new Response(e).arrayBuffer())})).catch(e=>{h("err")})}))}resolveChapter(e){var r=e;let i=-1;for(let e=0;e{let e=document.getElementById("page-area");if(e){var a=e.getElementsByTagName("iframe")[0];if(a){a=a.contentDocument;if(a){let e=de(a.body).filter(e=>!Ce(e)),t=e.filter(e=>(e.textContent||"").trim()),r=t.filter(e=>"img"!==e.textContent).map(e=>e.textContent),i=0;return xe(n,s)&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body),t=e.filter(e=>(e.getAttribute("style")===i&&e.setAttribute("style",""),(e.textContent||"").trim()&&e.textContent===r));0!Ce(e));for(let e=0;esetTimeout(e,1e3))),yield ve(this.element,this.mode,this.flatChapter(this.chapterList),this.tempLocation)})}getPosition(){return this.tempLocation}setStyle(t){let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){let e=r.contentDocument;e&&e.body.setAttribute("style",t+e.body.getAttribute("style"))}}}}const Me=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Oe={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Re={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ne={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},De={magic:[16,4,"string"],length:[20,4,"uint"],type:[24,4,"uint"],encoding:[28,4,"uint"],uid:[32,4,"uint"],version:[36,4,"uint"],titleOffset:[84,4,"uint"],titleLength:[88,4,"uint"],localeRegion:[94,1,"uint"],localeLanguage:[95,1,"uint"],resourceStart:[108,4,"uint"],huffcdic:[112,4,"uint"],numHuffcdic:[116,4,"uint"],exthFlag:[128,4,"uint"],trailingFlags:[240,4,"uint"],indx:[244,4,"uint"]},_e={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},Fe={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},He={magic:[0,4,"string"],length:[4,4,"uint"],type:[8,4,"uint"],idxt:[20,4,"uint"],numRecords:[24,4,"uint"],encoding:[28,4,"uint"],language:[32,4,"uint"],total:[36,4,"uint"],ordt:[40,4,"uint"],ligt:[44,4,"uint"],numLigt:[48,4,"uint"],numCncx:[52,4,"uint"]},Pe={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},Ue={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},je={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},$e={magic:[0,4,"string"],numEntries:[8,4,"uint"]},ze={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},We={1252:"windows-1252",65001:"utf-8"},qe={100:["creator","string",!0],101:["publisher"],103:["description"],104:["isbn"],105:["subject","string",!0],106:["date"],108:["contributor","string",!0],109:["rights"],110:["subjectCode","string",!0],112:["source","string",!0],113:["asin"],121:["boundary","uint"],122:["fixedLayout"],125:["numResources","uint"],126:["originalResolution"],127:["zeroGutter"],128:["zeroMargin"],129:["coverURI"],132:["regionMagnification"],201:["coverOffset","uint"],202:["thumbnailOffset","uint"],503:["title"],524:["language","string",!0],527:["pageProgressionDirection"]},Xe={1:["ar","ar-SA","ar-IQ","ar-EG","ar-LY","ar-DZ","ar-MA","ar-TN","ar-OM","ar-YE","ar-SY","ar-JO","ar-LB","ar-KW","ar-AE","ar-BH","ar-QA"],2:["bg"],3:["ca"],4:["zh","zh-TW","zh-CN","zh-HK","zh-SG"],5:["cs"],6:["da"],7:["de","de-DE","de-CH","de-AT","de-LU","de-LI"],8:["el"],9:["en","en-US","en-GB","en-AU","en-CA","en-NZ","en-IE","en-ZA","en-JM",null,"en-BZ","en-TT","en-ZW","en-PH"],10:["es","es-ES","es-MX",null,"es-GT","es-CR","es-PA","es-DO","es-VE","es-CO","es-PE","es-AR","es-EC","es-CL","es-UY","es-PY","es-BO","es-SV","es-HN","es-NI","es-PR"],11:["fi"],12:["fr","fr-FR","fr-BE","fr-CA","fr-CH","fr-LU","fr-MC"],13:["he"],14:["hu"],15:["is"],16:["it","it-IT","it-CH"],17:["ja"],18:["ko"],19:["nl","nl-NL","nl-BE"],20:["no","nb","nn"],21:["pl"],22:["pt","pt-BR","pt-PT"],23:["rm"],24:["ro"],25:["ru"],26:["hr",null,"sr"],27:["sk"],28:["sq"],29:["sv","sv-SE","sv-FI"],30:["th"],31:["tr"],32:["ur"],33:["id"],34:["uk"],35:["be"],36:["sl"],37:["et"],38:["lv"],39:["lt"],41:["fa"],42:["vi"],43:["hy"],44:["az"],45:["eu"],46:["hsb"],47:["mk"],48:["st"],49:["ts"],50:["tn"],52:["xh"],53:["zu"],54:["af"],55:["ka"],56:["fo"],57:["hi"],58:["mt"],59:["se"],62:["ms"],63:["kk"],65:["sw"],67:["uz",null,"uz-UZ"],68:["tt"],69:["bn"],70:["pa"],71:["gu"],72:["or"],73:["ta"],74:["te"],75:["kn"],76:["ml"],77:["as"],78:["mr"],79:["sa"],82:["cy","cy-GB"],83:["gl","gl-ES"],87:["kok"],97:["ne"],98:["fy"]},Ve=(e,t)=>{const r=new e.constructor(e.length+t.length);return r.set(e),r.set(t,e.length),r},Ge=(e,t,r)=>{const i=new e.constructor(e.length+t.length+r.length);return i.set(e),i.set(t,e.length),i.set(r,e.length+t.length),i},Je=new TextDecoder,Ke=e=>Je.decode(e),Ze=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Ye=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,r,i]])=>[e,("string"===i?Ke:Ze)(n.slice(t,t+r))])),Qe=e=>new TextDecoder(We[e]),et=(e,t=0)=>{let r=0,i=0;for(const n of e.subarray(t,t+4))if(r=r<<7|(127&n)>>>0,i++,128&n)break;return{value:r,length:i}},tt=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},rt=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},it=t=>{let r=[];for(let e=0;e>>3,a=3+(7&n);for(let e=0;e{const i=await r(t.huffcdic),{magic:e,offset1:n,offset2:s}=Ye(Ue,i);if("HUFF"!==e)throw new Error("Invalid HUFF record");const d=Array.from({length:256},(e,t)=>n+4*t).map(e=>Ze(i.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),u=[null].concat(Array.from({length:32},(e,t)=>s+8*t).map(e=>[Ze(i.slice(e,e+4)),Ze(i.slice(e+4,e+8))])),f=[];for(let e=1;e{let o=new Uint8Array;var l=8*a.byteLength;for(let s=0;s{var e=r+32,i=e>>3;let n=0n;for(let e=r>>3;e<=i;e++)n=n<<8n|BigInt(t[e]??0);return n>>8n-BigInt(7&e)&0xffffffffn})(a,s));let[e,t,r]=d[c>>>24];if(!e){for(;c>>>32-tl)break;var h=r-(c>>>32-t);let[i,n]=f[h];n||(i=p(i),f[h]=[i,!0]),o=Ve(o,i)}return o};return p},st=async(t,r)=>{const e=await r(t),i=Ye(He,e);if("INDX"!==i.magic)throw new Error("Invalid INDX record");const n=Qe(i.encoding),s=e.slice(i.length);var a=Ye(Pe,s);if("TAGX"!==a.magic)throw new Error("Invalid TAGX section");var o=(a.length-12)/4,l=Array.from({length:o},(e,t)=>new Uint8Array(s.slice(12+4*t,12+4*t+4)));const c={};let h=0;for(let e=0;e>rt(C),null,x]));const P={};for([k,E,B,A]of H){const U=[];if(null!=E)for(let e=0;eZe(r.slice(8*t,8*t+4))).map((e,t,r)=>[e,r[t+1]])}loadRecord(e){e=this.#offsets[e];if(!e)throw new RangeError("Record index out of bounds");return this.#file.slice(...e).arrayBuffer()}async loadMagic(e){e=this.#offsets[e][0];return Ke(await this.#file.slice(e,e+4).arrayBuffer())}}{#start=0;#resourceStart;#decoder;#encoder;#decompress;#removeTrailingEntries;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#getHeaders(await super.loadRecord(0)),this.#resourceStart=this.headers.mobi.resourceStart;let t=8<=this.headers.mobi.version;if(!t){e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#getHeaders(await super.loadRecord(e)),this.#start=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#setup(),new(t?mt:ct)(this).init()}#getHeaders(e){var t=Ye(Ne,e);const r=Ye(De,e);if("MOBI"!==r.magic)throw new Error("Missing MOBI header");var{titleOffset:i,titleLength:n,localeLanguage:s,localeRegion:a}=r;r.title=e.slice(i,i+n);s=Xe[s];r.language=s?.[a>>2]??s?.[0];s=64&r.exthFlag?((t,e)=>{var{magic:r,count:i}=Ye(Fe,t);if("EXTH"!==r)throw new Error("Invalid EXTH header");const n=Qe(e),s={};let a=12;for(let e=0;ee:2===e?it:17480===e?await nt(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const i=1&t,n=tt(t>>>1);this.#removeTrailingEntries=t=>{for(let e=0;e{let t=0;for(const r of e.subarray(-4))128&r&&(t=0),t=t<<7|127&r;return t})(t);t=t.subarray(0,-r)}var e;return i&&(e=1+(3&t[t.length-1]),t=t.subarray(0,-e)),t}}decode(...e){return this.#decoder.decode(...e)}encode(...e){return this.#encoder.encode(...e)}loadRecord(e){return super.loadRecord(this.#start+e)}loadMagic(e){return super.loadMagic(this.#start+e)}loadText(e){return this.loadRecord(e+1).then(e=>new Uint8Array(e)).then(this.#removeTrailingEntries).then(this.#decompress)}async loadResource(e){const t=await super.loadRecord(this.#resourceStart+e);e=Ke(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:r,dataStart:i,keyLength:n,keyStart:s}=Ye(ze,e);const a=new Uint8Array(e.slice(i));if(2&r)for(var i=16===n?1024:1040,o=new Uint8Array(e.slice(s,s+n)),l=Math.min(i,a.length),c=0;c{const{table:r,cncx:i}=await st(e,t),n=r.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:i[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),s=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(s)),t);return n.filter(e=>0===e.headingLevel).map(s)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Me(t?.title||this.decode(e.title)),author:t?.creator?.map(Me),publisher:Me(t?.publisher),language:t?.language??e.language,published:t?.date,description:Me(t?.description),subject:t?.subject?.map(Me),rights:Me(t?.rights)}}async getCover(){var e=this.headers["exth"],e=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=e){e=await this.loadResource(e);return new Blob([e])}}}const ot=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,lt=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class ct{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=Oe.HTML;constructor(e){this.mobi=e}async init(){let t=new Uint8Array;for(let e=0;eString.fromCharCode(e)).join("");this.#sections=[0].concat(Array.from(i.matchAll(ot),e=>e.index)).map((e,t,r)=>i.slice(e,r[t+1])).map(e=>Uint8Array.from(e,e=>e.charCodeAt(0))).map(e=>({book:this,raw:e})).reduce((e,t)=>{var r=e[e.length-1];return t.start=r?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)},[]),this.sections=this.#sections.map((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start}));try{this.landmarks=await this.getGuide();var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var r=this.resolveHref(e)["index"];const n=await this.sections[r].createDocument();let s,a=0,o=0;const l=new Map,c=new Map;this.toc=Array.from(n.querySelectorAll("a[filepos]")).reduce((e,t)=>{var r=(e=>{let t=0;for(;e;){const i=e.parentElement;var r;i&&("p"===(r=i.tagName.toLowerCase())?t+=1.5:"blockquote"===r&&(t+=2)),e=i}return t})(t),i={label:t.innerText?.trim(),href:`filepos:${t.getAttribute("filepos")}`},t=r>o?a+1:r===o?a:l.get(r)??Math.max(0,a-1);if(t>a)s?(s.subitems??=[],s.subitems.push(i),c.set(t,s)):e.push(i);else{const n=c.get(t);(n?n.subitems:e).push(i)}return s=i,a=t,o=r,l.set(r,t),e},[])}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(Array.from(i.matchAll(lt),e=>e[1]))].map(e=>({filepos:e,number:Number(e)})).sort((e,t)=>e.number-t.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#sections[0]);return Array.from(e.getElementsByTagName("reference"),e=>({label:e.getAttribute("title"),type:e.getAttribute("type")?.split(/\s/),href:`filepos:${e.getAttribute("filepos")}`}))}async loadResource(e){if(this.#resourceCache.has(e))return this.#resourceCache.get(e);var t=await this.mobi.loadResource(e),t=URL.createObjectURL(new Blob([t]));return this.#resourceCache.set(e,t),t}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const s of e.querySelectorAll("img[recindex]")){var t=s.getAttribute("recindex");try{s.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const a of e.querySelectorAll("[mediarecindex]")){var r=a.getAttribute("mediarecindex"),i=a.getAttribute("recindex");try{a.src=await this.loadRecindex(r),i&&(a.poster=await this.loadRecindex(i))}catch(e){console.warn(`Failed to load media ${r}`)}}for(const o of e.querySelectorAll("[filepos]")){var n=o.getAttribute("filepos");o.href=`filepos:${n}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const i=t["raw"],n=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let s=i;n.length&&(s=i.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},r)=>{r=n[r+1],e=this.mobi.encode(``);s=Ge(s,e,i.subarray(t,r?.offset))}));var e=this.mobi.decode(s).replaceAll(ot,"");return this.#textCache.set(t,e),e}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);const t=await this.createDocument(e),r=t.createElement("style");t.head.append(r),r.append(t.createTextNode(`blockquote { margin-block-start: 0; margin-block-end: 0; margin-inline-start: 1em;