diff --git a/public/lib/kookit/kookit.umd.js b/public/lib/kookit/kookit.umd.js index f72f130c..97bfbfed 100644 --- a/public/lib/kookit/kookit.umd.js +++ b/public/lib/kookit/kookit.umd.js @@ -1,9 +1,9 @@ -!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 u(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})}class s{static getKookitConfig(e){return(JSON.parse(localStorage.getItem("kookitConfig"))||{})[e]}static setKookitConfig(e,t){let r=JSON.parse(localStorage.getItem("kookitConfig"))||{};r[e]=t,localStorage.setItem("kookitConfig",JSON.stringify(r))}static removeKookitConfig(){localStorage.removeItem("kookitConfig")}}let i=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"];String.prototype.contains=function(e){return-1e&&!e.contains("[")&&!e.contains("(")&&!e.contains("。")&&!e.contains("“")&&!e.contains("‘")&&!e.contains(";")&&!e.contains(";")&&(e.startsWith("CHAPTER")||e.startsWith("Chapter")||e.startsWith("序章")||e.startsWith("前言")||e.startsWith("声明")||e.startsWith("聲明")||e.startsWith("写在前面的话")||e.startsWith("后记")||e.startsWith("楔子")||e.startsWith("后序")||e.startsWith("寫在前面的話")||e.startsWith("後記")||e.startsWith("後序")||e.startsWith("第")&&r(e)||e.startsWith("卷")&&n(e)||!t&&e.contains("第")&&(" "===e[e.indexOf("第")-1]||" "===e[e.indexOf("第")-1]||"、"===e[e.indexOf("第")-1]||":"===e[e.indexOf("第")-1]||":"===e[e.indexOf("第")-1])&&r(e.substr(e.indexOf("第")))||!t&&e.indexOf(" ")&&a(e)||!t&&e.indexOf(" ")&&a(e)||!t&&e.indexOf("、")&&c(e)||!t&&e.indexOf(":")&&o(e)||!t&&e.indexOf(":")&&o(e)),r=t=>{let r=!1;for(let e=0;e!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1))&&!/^\d+$/.test(e.substring(1)))),a=e=>!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(" ")))||(!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(" ")))||(!!/^\d+$/.test(e.substring(0,e.indexOf(" ")))||!!/^\d+$/.test(e.substring(0,e.indexOf(" "))))),o=e=>!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(":")))||(!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(":")))||(!!/^\d+$/.test(e.substring(0,e.indexOf(":")))||!!/^\d+$/.test(e.substring(0,e.indexOf(":"))))),c=e=>!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf("、")))||!!/^\d+$/.test(e.substring(0,e.indexOf("、"))),h=e=>"♦"===e.trim()||"●"===e.trim()||"◾"===e.trim()||"◀"===e.trim()||"◼"===e.trim()||"■"===e.trim(),f=e=>"|"===e.trim()||"Next"===e.trim()||"Main menu"===e.trim()||"Section menu"===e.trim()||"Previous"===e.trim();var d=window;window.a=window.atob;String.prototype.c=function(e){return-1"="!==e&&"-"!==e&&"_"!==e&&"+"!==e).join("")};const p=e=>{let t="",r=!1;var i;for(i of e.split("\n"))i.trim().slim()&&(l(i.trim().slim(),r)?((i.trim().slim().startsWith("第")||i.trim().slim().startsWith("Chapter")||i.trim().slim().startsWith("CHAPTER"))&&(r=!0),t+=`

${i}

`):t+=`

${i}

`);return t||`

Title

${e}

`},m=()=>u(void 0,void 0,void 0,function*(){s.removeKookitConfig();let e=yield new Promise((e,t)=>{e(d.e(d.a("ZG9jdW1lbnQudGl0bGU"+String.fromCharCode(61))))});return!!e.c(d.a("ZG8gUmU"+String.fromCharCode(61)))});var t="1.13.1",g="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||Function("return this")()||{},y=Array.prototype,b=Object.prototype,v="undefined"!=typeof Symbol?Symbol.prototype:null,w=y.push,x=y.slice,S=b.toString,T=b.hasOwnProperty,k="undefined"!=typeof ArrayBuffer,C="undefined"!=typeof DataView,L=Array.isArray,A=Object.keys,I=Object.create,B=k&&ArrayBuffer.isView,E=isNaN,M=isFinite,D=!{toString:null}.propertyIsEnumerable("toString"),O=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],N=Math.pow(2,53)-1;function R(n,a){return a=null==a?n.length-1:+a,function(){for(var e=Math.max(arguments.length-a,0),t=Array(e),r=0;r":">",'"':""","'":"'","`":"`"},nt=rt(it),at=rt(Ne(it)),ot=ye.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},st=/(.)^/,lt={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},ct=/\\|'|\r|\n|\u2028|\u2029/g;function ut(e){return"\\"+lt[e]}var ht=/^\s*(\w|\$)+\s*$/;var ft=0;function dt(e,t,r,i,n){if(!(i instanceof t))return e.apply(r,n);r=Fe(e.prototype),n=e.apply(r,n);return H(n)?n:r}var pt=R(function(n,a){function o(){for(var e=0,t=a.length,r=Array(t),i=0;i{let i=document.getElementById("page-area");if(i){let e=i.getElementsByTagName("iframe")[0];var n;e&&("scroll"===r?(n=e.contentDocument)&&(r=n.body,n=n.documentElement,e.height=2*Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight)+"px",setTimeout(()=>{let e=document.getElementById("page-area");if(e){let i=e.getElementsByTagName("iframe")[0];if(i){var n=i.contentDocument;if(n){let e=n.body;var a=e.lastElementChild,o=e.lastChild,s=e.getElementsByTagName("a"),l=e.getElementsByTagName("p"),c=e.getElementsByTagName("img"),u=e.getElementsByTagName("div"),n=s[s.length-1],s=l[l.length-1],c=l[c.length-1],u=u[u.length-1];let t=s||n||c||u;Yt.isElement(n)&&Yt.isElement(s)&&Yt.isElement(u)&&(t=n.clientHeight+n.offsetTop>s.clientHeight+s.offsetTop?n:s,u.clientHeight+u.offsetTop>t.clientHeight+t.offsetTop&&(t=u)),Yt.isElement(c)&&c.clientHeight+c.offsetTop>t.clientHeight+t.offsetTop&&(t=c);let r=0;if((a||t||o)&&(3!==o.nodeType||a||t)){if(3===o.nodeType&&document.createRange){let e=document.createRange();e.selectNodeContents(o),!e.getBoundingClientRect||(c=e.getBoundingClientRect())&&(r=c.bottom-c.top)}o=Math.max(Yt.isElement(a)?a.clientHeight+a.offsetTop:0,Yt.isElement(o)?o.clientHeight+o.offsetTop:0,Yt.isElement(t)?t.clientHeight+t.offsetTop:0)+400+(3===o.nodeType?r:0);i.height=o+"px"}}}}},500)):e.height=t.offsetHeight+"px")}},er=(e,t="")=>{var r=document.createElement("iframe");if(r.style.width="100%",r.style.border="0",r.style.margin="0",r.style.padding="0",r.style.fontSize="100%",r.style.font="inherit",r.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(r),t&&r.contentDocument){let e=r.contentDocument.createElement("style");e.id="azw3-style",e.textContent=t,r.contentDocument.head.appendChild(e)}},tr=(r,i)=>{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-count: 12;column-width: ${(r.offsetWidth-i)/n}px;`))}}}};class rr{constructor(e){this.bookStr=e,this.chapterList=[],this.chapterDocList=[]}getChapterDoc(){var t=-1")?this.bookStr.split("").filter(e=>""!==e.trim()):this.bookStr.split("
").filter(e=>""!==e.trim());let n=[],a=[],r="";for(let e=0;e{var t=0u(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;e&&(t=(t=Math.floor(r.clientWidth/12))%2==0?t:t-1,0{let a=document.getElementById("page-area");var o,s;a&&(!(o=a.getElementsByTagName("iframe")[0])||(s=o.contentDocument)&&Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<10&&Math.abs(s.body.scrollWidth-s.body.scrollLeft-s.body.clientWidth)<10&&(pr(e,t,r,i),n("rendered")))})(r,i,n,a,l),e.body.scrollBy({top:0,left:r.offsetWidth+t,behavior:s?"smooth":"auto"})))}}}),ur=(e,t,r,i)=>{var n=s.getKookitConfig("chapterTitle"),a=parseInt(s.getKookitConfig("chapterDocIndex")||"0"),o=s.getKookitConfig("chapterHref")||"";0!==a&&n&&(o=Yt.findLastIndex(t,{index:a,href:o}),s.setKookitConfig("chapterTitle",t[o-1].title),s.setKookitConfig("chapterHref",t[o-1].href),s.setKookitConfig("chapterDocIndex",t[o-1].index.toString()),s.setKookitConfig("text","prevChapter"),hr(t[o-1].index,t[o-1].title,r,e,i),t[o-1].href&&-1{let e=document.getElementById("page-area");if(e){var o=e.getElementsByTagName("iframe")[0];if(o){let e=o.contentDocument;e&&(e.body.innerHTML="",e.body.innerHTML=i[t].text,s.setKookitConfig("chapterTitle",r),s.setKookitConfig("chapterDocIndex",t.toString()),s.setKookitConfig("percentage",t/i.length+""),Qt(n,a),((i,n)=>{let e=document.getElementById("page-area");if(e){var a=e.getElementsByTagName("iframe")[0];if(a){let r=a.contentDocument;if(r){var o,a=Math.floor(i.clientWidth/12),s=a%2==0?a:a-1;let e,t;for(o of r.getElementsByTagName("img")){var l=o.parentElement;e=0,t=0,o.width&&o.height?o.height/o.width>l.clientHeight/l.clientWidth?(e=l.clientHeight,t=e*o.width/o.height):(t=l.clientWidth,e=t*o.height/o.width):e=l&&l.clientWidth&&0{let t=document.getElementById("page-area");if(t){var s=t.getElementsByTagName("iframe")[0];if(s){let r=s.contentDocument;if(r){var l,c;let t=r.body;if(n){let e=Array.from(r.body.querySelectorAll("h1,h2,h3,h4,p,img"));s=e.filter((e,t)=>(e.innerText.trim()&&(e.innerText.trim()===n.trim()||e.innerText.trim()===sr.t2s(n.trim())||e.innerText.trim()===sr.s2t(n.trim()))||e.getAttribute("recindex")&&e.getAttribute("recindex").trim()===n.trim())&&Math.abs(t-parseInt(a))<2);t=s[0]}else o&&-1u(void 0,void 0,void 0,function*(){if(!lr){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){let t=Array.from(e.body.querySelectorAll("h1,h2,h3,h4,p,img"));let r=t.filter(e=>mr(n,e,a)&&(e.innerText.trim()||e.getAttribute("recindex")))[0],i=0;for(let e=0;e{lr=!1},100)}}}}}),pr=(e,t,r,i)=>{var n=parseInt(s.getKookitConfig("chapterDocIndex")||"0"),a=s.getKookitConfig("chapterHref")||"",a=Yt.findLastIndex(t,{index:n,href:a});s.setKookitConfig("chapterTitle",t[a+1].title),s.setKookitConfig("chapterHref",t[a+1].href),s.setKookitConfig("chapterDocIndex",t[a+1].index.toString()),s.setKookitConfig("text",""),hr(t[a+1].index,t[a+1].title,r,e,i),t[a+1].href&&-1{var i,n=!1,a=t.getBoundingClientRect();return"scroll"!==r&&t.innerText.trim()?n=-10<(i=a.left)&&i<=e.offsetWidth:t.innerText.trim()?n=(i=a.top)>=e.scrollTop&&i<=e.scrollTop+e.offsetHeight:"scroll"!==r&&(t.id||t.onerror)&&"IMG"===t.tagName?n=0<=(r=a.left)&&r<=e.offsetWidth:(t.id||t.onerror)&&"IMG"===t.tagName&&(n=(a=a.top)>=e.scrollTop-e.clientHeight/2&&a<=e.scrollTop+e.offsetHeight+e.clientHeight/2),n};class gr{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",1{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let r=t.contentDocument;if(r){let e=Array.from(r.body.querySelectorAll("h1,h2,h3,h4,p,img")),t=e.filter(e=>mr(i,e,n)&&(e.innerText.trim()||e.getAttribute("recindex")));return("scroll"!==n?t:e).map(e=>e.innerText).join(" ")}}}})(this.element,this.mode)}doSearch(e){return((i,n)=>{let a=[];for(let r=0;r{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return{totalPage:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(t.body.scrollLeft/t.body.clientWidth+"")+1}}}})()}record(){dr(this.element,this.mode)}getPosition(){return{text:s.getKookitConfig("text"),chapterTitle:s.getKookitConfig("chapterTitle"),chapterDocIndex:s.getKookitConfig("chapterDocIndex"),chapterHref:s.getKookitConfig("chapterHref"),count:s.getKookitConfig("count"),percentage:s.getKookitConfig("percentage")}}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"))}}}}class br{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return u(this,void 0,void 0,function*(){return this.chapterList=yield Promise.all(e.map(t=>u(this,void 0,void 0,function*(){var e=(yield this.book.resolveHref(t.href)).index;return{title:t.label||"Content",href:t.href,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return u(this,void 0,void 0,function*(){let e=yield Promise.all(this.book.sections.map(e=>u(this,void 0,void 0,function*(){return e.load?(yield fetch(yield e.load()).then(e=>e.blob())).text():""})));const r=this.flattenChapters.map(e=>e.index);return e.map((e,t)=>-1u(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=()=>{i({name:t.title,author:t.author[0].name,description:t.description,publisher:t.publisher,cover:r.result})}}catch(e){i({name:t.title,author:t.author[0].name||t.author[0],description:t.description,publisher:t.publisher,cover:""})}}))}}const vr=(e,i)=>e.map((e,t,r)=>i(e,t,r)?t:null).filter(e=>null!=e),wr=(i,e)=>[-1,...e,i.length].reduce(({xs:e,a:t},r)=>({xs:e?.concat([i.slice(t+1,r)])??[],a:r}),{}).xs,xr=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),Sr=/\d/,Tr=/^epubcfi\((.*)\)$/,kr=e=>e.replace(/[\^[\](),;=]/g,"^$&"),Cr=e=>Tr.test(e)?e:`epubcfi(${e})`,Lr=(e,t)=>vr(e,([e])=>e===t),Ar=e=>{const t=[];let r;for(var[i,n]of e){if("/"===i)t.push({index:n});else{const a=t[t.length-1];if(":"===i)a.offset=n;else if("~"===i)a.temporal=n;else if("@"===i)a.spatial=(a.spatial??[]).concat(n);else if(";s"===i)a.side=n;else if("["===i){if("/"!==r||!n){a.text=(a.text??[]).concat(n);continue}a.id=n}}r=i}return t},Ir=e=>wr(e,Lr(e,"!")).map(Ar),Br=e=>{var t=(e=>{const t=[];let r,i,n="";var a=e=>(t.push(e),r=null,n=""),o=e=>(n+=e,i=!1);for(const s of Array.from(e.trim()).concat(""))if("^"!==s||i){if("!"===r)a(["!"]);else if(","===r)a([","]);else if("/"===r||":"===r){if(Sr.test(s)){o(s);continue}a([r,parseInt(n)])}else if("~"===r){if(Sr.test(s)||"."===s){o(s);continue}a(["~",parseFloat(n)])}else if("@"===r){if(":"===s){a(["@",parseFloat(n)]),r="@";continue}if(Sr.test(s)||"."===s){o(s);continue}a(["@",parseFloat(n)])}else{if("["===r){";"!==s||i?","!==s||i?"]"!==s||i?o(s):a(["[",n]):(a(["[",n]),r="["):(a(["[",n]),r=";");continue}if(r?.startsWith(";")){"="!==s||i?";"!==s||i?"]"!==s||i?o(s):a([r,n]):(a([r,n]),r=";"):(r=`;${n}`,n="");continue}}"/"!==s&&":"!==s&&"~"!==s&&"@"!==s&&"["!==s&&"!"!==s&&","!==s||(r=s)}else i=!0;return t})((r=e).match(Tr)?.[1]??r),e=Lr(t,",");if(!e.length)return Ir(t);var[r,t,e]=wr(t,e).map(Ir);return{parent:r,start:t,end:e}},Er=({index:e,id:t,offset:r,temporal:i,spatial:n,text:a,side:o})=>{var s=o?`;s=${o}`:"";return`/${e}`+(t?`[${kr(t)}${s}]`:"")+(null!=r&&e%2?`:${r}`:"")+(i?`~${i}`:"")+(n?`@${n.join(":")}`:"")+(a||!t&&o?"["+(a?.map(kr)?.join(",")??"")+s+"]":"")},Mr=e=>e.parent?[e.parent,e.start,e.end].map(Mr).join(","):e.map(e=>e.map(Er).join("")).join("!"),Dr=e=>Cr(Mr(e)),Or=(e,t)=>"string"==typeof e?Dr(Or(Br(e),t)):e.parent?xr(e.parent,e[t?"end":"start"]):e,Nr=({nodeType:e})=>3===e||4===e,Rr=({nodeType:e})=>1===e,Hr=e=>{const t=Array.from(e.childNodes).filter(e=>Nr(e)||Rr(e)).reduce((e,t)=>{let r=e[e.length-1];return r?Nr(t)?Array.isArray(r)?r.push(t):Nr(r)?e[e.length-1]=[r,t]:e.push(t):Rr(r)?e.push(null,t):e.push(t):e.push(t),e},[]);return Rr(t[0])&&t.unshift("first"),Rr(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},Ur=(e,t)=>e?Hr(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=Ur(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 a=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:a};let o=0;for(const l of e){var s=l.nodeValue["length"];if(o+s>=a)return{node:l,offset:a-o};o+=s}},jr=(t,r)=>{var{parentNode:e,id:i}=t;const n=Hr(e);var a=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),o=n[a];if(Array.isArray(o)){let e=0;for(const s of o){if(s===t){e+=r;break}e+=s.nodeValue.length}r=e}a={id:i,index:a,offset:r};return e!==t.ownerDocument.documentElement?jr(e).concat(a):[a]},Fr=(e,t)=>$r(e.documentElement,Or(t)).node,Pr={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"},zr={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)/},Wr=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),_r=e=>e?e.trim().replace(/\s{2,}/g," "):"",qr=(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,Xr=(...e)=>t=>t?Object.fromEntries(e.map(e=>[Wr(e),t.getAttribute(e)])):null,Kr=e=>_r(e?.textContent),Vr=(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)]}},Gr=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var r="whatever:///";return decodeURI(new URL(t,r+e).href.replace(r,""))}catch(e){return console.warn(e),t}},Zr=e=>/^(?!blob)\w+:/i.test(e),Jr=async(e,t,r)=>{const i=[];e.replace(t,(...e)=>(i.push(e),null));const n=[];for(const a of i)n.push(await r(...a));return e.replace(t,()=>n.shift())},Yr=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");Ie={attrs:["dir","xml:lang"]},it={name:"alternate-script",many:!0,...Ie,props:["file-as"]},Y={many:!0,...Ie,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",it]};const Qr=[{name:"title",many:!0,...Ie,props:["title-type","display-seq","file-as",it]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...Y},{name:"contributor",...Y},{name:"publisher",...Ie,props:["file-as",it]},{name:"description",...Ie,props:[it]},{name:"rights",...Ie,props:[it]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...Ie,props:["term","authority",it]},{name:"belongs-to-collection",type:"meta",many:!0,...Ie,props:["collection-type","group-position","dcterms:identifier","file-as",it,{name:"belongs-to-collection",recursive:!0}]}],ei=(e,a=e=>e)=>{const{$:o,$$:r,$$$:t}=Vr(e,Pr.XHTML),i=n=>e=>{const t=o(e,"a")??o(e,"span");var r=o(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(a(e)):null;const i={label:Kr(t)||t?.getAttribute("title"),href:e,subitems:s(r)};return n&&(i.type=t?.getAttributeNS(Pr.EPUB,"type")?.split(/\s/)),i},s=(e,t)=>e?r(e,"li").map(i(t)):null;var n=(e,t)=>s(o(e,"ol"),t);let l=null,c=null,u=null,h=[];for(const f of t(e,"nav")){const d=f.getAttributeNS(Pr.EPUB,"type")?.split(/\s/)??[];d.includes("toc")?l??=n(f):d.includes("page-list")?c??=n(f):d.includes("landmarks")?u??=n(f,!0):h.push({label:Kr(f.firstElementChild),type:d,list:n(f)})}return{toc:l,pageList:c,landmarks:u,others:h}},ti=(r,a=e=>e)=>{const{$:o,$$:s}=Vr(r,Pr.NCX),l=e=>{var t=o(e,"navLabel");const r=o(e,"content");var i=Kr(t),t=(t=r.getAttribute("src"))?decodeURI(a(t)):null;if("navPoint"!==e.localName)return{label:i,href:t};{const n=s(e,"navPoint");return{label:i,href:t,subitems:n.length?n.map(l):null}}},i=(e,t)=>s(e,t).map(l);var e=(e,t)=>{e=o(r.documentElement,e);return e?i(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:s(r.documentElement,"navList").map(e=>({label:Kr(o(e,"navLabel")),list:i(e,"navTarget")}))}},ri=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,a]=t;return 60*t+a}var[a,e]=e.split(/(?=[^\d.])/);return parseFloat(a)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},ii=(e,i=e=>e)=>{const{$:n,$$$:t}=Vr(e,Pr.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:ri(r.getAttribute("clipBegin")),clipEnd:ri(r.getAttribute("clipEnd"))}}:{id:t}})},ni=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ai=e=>Kr(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(Pr.DC,"identifier")[0]),oi=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(ai(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>oi(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const r=(e=>{for(const r of e.getElementsByTagNameNS(Pr.DC,"identifier")){var[t]=Kr(r).split(":").slice(-1);if(ni.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)=>oi(e,1024,t)}});class li{#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(Pr.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(Pr.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(Pr.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(r)){const n=this.#algorithms[r];if(!n){console.warn("Unknown encryption algorithm");continue}const a=await n.key(t);this.#decoders.set(r,e=>n.decode(a,e))}this.#uris.set(i,r)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class ci{constructor({opf:e,resolveHref:i}){this.opf=e;const{$:t,$$:r,$$$:n}=Vr(e,Pr.OPF);var a=t(e.documentElement,"manifest");const o=t(e.documentElement,"spine"),s=r(o,"itemref");this.manifest=r(a,"item").map(Xr("href","id","media-type","properties","media-overlay")).map(e=>(e.href=i(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=s.map(Xr("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=o.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(o.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===zr.NCX))?.href;a=t(e.documentElement,"guide");a&&(this.guide=r(a,"reference").map(Xr("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(qr("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 a=jr(n);for([r,i]of Hr(n).entries()){var o=e[t.length];i===o&&t.push(Dr([a.concat({id:o.id,index:r})]))}return t})(s)}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=Br(e),r=(t.parent??t).shift();let i=Fr(this.opf,r);i&&"idref"!==i.nodeName&&(r.at(-1).id=null,i=Fr(this.opf,r));const n=i?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var r=Or(t),i=Or(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 ui{#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=zr.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var a=t.at(-1);return this.#cache.has(r)?this.ref(r,a):(n||[zr.XHTML,zr.HTML,zr.CSS,zr.SVG].includes(i))&&t.every(e=>e!==r)?this.loadReplaced(e,t):this.createURL(r,await this.loadBlob(r),i,a)}async loadHref(e,t,r=[]){if(Zr(e))return e;const i=Gr(e,t);var n=this.manifest.find(e=>e.href===i);return n?this.loadItem(n,r.concat(t)):e}async loadReplaced(e,n=[]){const{href:a,mediaType:r}=e;var i,o=n.at(-1),s=await this.loadText(a);if(!s)return null;if([zr.XHTML,zr.HTML,zr.SVG].includes(r)){let t=(new DOMParser).parseFromString(s,r);if(r===zr.XHTML&&t.querySelector("parsererror")&&(e.mediaType=zr.HTML,t=(new DOMParser).parseFromString(s,e.mediaType)),[zr.XHTML,zr.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(i=await Jr(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,r,i)=>this.loadHref(r,a,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),a,n));for(const u of t.querySelectorAll("link[href]"))await l(u,"href");for(const h of t.querySelectorAll("[src]"))await l(h,"src");for(const f of t.querySelectorAll("[poster]"))await l(f,"poster");for(const d of t.querySelectorAll("object[data]"))await l(d,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(Pr.XLINK,"href",await this.loadHref(p.getAttributeNS(Pr.XLINK,"href"),a,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,a,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),a,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(a,c,e.mediaType,o)}const c=r===zr.CSS?await this.replaceCSS(s,a,n):await this.replaceString(s,a,n);return this.createURL(a,c,r,o)}async replaceCSS(e,r,i=[]){e=await Jr(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,r,i).then(e=>`url("${e}")`));const t=await Jr(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,r,i).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,a=window?.innerHeight??600,o=t.replace(/(\d*\.?\d+)vw/g,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/g,(e,t)=>parseFloat(t)*a/100+"px");return o.replaceAll("-epub-","")}replaceString(e,o,t=[]){const s=new Map,r=this.assets.map(e=>{if(e.href!==o){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("/")})(o.slice(0,o.lastIndexOf("/")+1),e.href),r=encodeURI(t),i="/"+e.href,n=encodeURI(i),n=new Set([t,r,i,n]);for(const a of n)s.set(a,e);return Array.from(n)}}).flat().filter(e=>e);if(!r.length)return e;var i=new RegExp(r.map(Yr).join("|"),"g");return Jr(e,i,async e=>this.loadItem(s.get(e.replace(/^\//,"")),t.concat(o)))}unloadItem(e){this.unref(e?.href)}}class hi{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 li(si(i))}#parseXML(e){return e?this.parser.parseFromString(e,zr.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(Pr.CONTAINER,"rootfile"),Xr("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 ci({opf:i,resolveHref:e=>Gr(e,r)});const a=new ui({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:()=>a.loadItem(n),unload:()=>a.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=>Gr(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:o}=this.resources;if(n)try{var s=ei(await this.#loadXML(n),e=>Gr(e,n));this.toc=s.toc,this.pageList=s.pageList,this.landmarks=s.landmarks}catch(e){console.warn(e)}if(!this.toc&&o)try{var l=ti(await this.#loadXML(o),e=>Gr(e,o));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:u,media:h}=(e=>{const{$:t,$$:r}=Vr(e,Pr.OPF),i=t(e.documentElement,"metadata"),a=Array.from(i.children),l=(o,t)=>{if(!t)return null;const{props:e=[],attrs:r=[]}=o,i=Kr(t);if(!e.length&&!r.length)return i;var n=t.getAttribute("id");const s=n?a.filter(qr("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=qr("property",i);const a=r?o:e;return[Wr(i),t?s.filter(n).map(e=>l(a,e)):l(a,s.find(n))]})).concat(r.map(e=>[Wr(e),t.getAttribute(e)])))},o=a.filter(qr("refines",null));e=t=>Object.fromEntries(r(i,"meta").filter(qr("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),Kr(e)]));return{metadata:Object.fromEntries(Qr.map(t=>{const{type:e,name:r,many:i}=t;var n="meta"===e?e=>e.namespaceURI===Pr.OPF&&e.getAttribute("property")===r:e=>e.namespaceURI===Pr.DC&&e.localName===r;return[Wr(r),i?o.filter(n).map(e=>l(t,e)):l(t,o.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(i);this.rendition=u,this.media=h,h.duration=ri(h.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:ai(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 f={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:f[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 ii(e,e=>Gr(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 Zr(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)}}}const fi=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},di={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},pi={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},mi={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},gi={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"]},yi={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},bi={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},vi={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"]},wi={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},xi={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},Si={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Ti={magic:[0,4,"string"],numEntries:[8,4,"uint"]},ki={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Ci={1252:"windows-1252",65001:"utf-8"},Li={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"]},Ai={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"]},Ii=(e,t)=>{const r=new e.constructor(e.length+t.length);return r.set(e),r.set(t,e.length),r},Bi=(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},Ei=new TextDecoder,Mi=e=>Ei.decode(e),Di=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Oi=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,r,i]])=>[e,("string"===i?Mi:Di)(n.slice(t,t+r))])),Ni=e=>new TextDecoder(Ci[e]),Ri=(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}},Hi=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},Ui=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},$i=t=>{let r=[];for(let e=0;e>>3,o=3+(7&n);for(let e=0;e{const i=await r(t.huffcdic),{magic:e,offset1:n,offset2:a}=Oi(xi,i);if("HUFF"!==e)throw new Error("Invalid HUFF record");const h=Array.from({length:256},(e,t)=>n+4*t).map(e=>Di(i.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),f=[null].concat(Array.from({length:32},(e,t)=>a+8*t).map(e=>[Di(i.slice(e,e+4)),Di(i.slice(e+4,e+8))])),d=[];for(let e=1;e{let s=new Uint8Array;var l=8*o.byteLength;for(let a=0;a{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})(o,a));let[e,t,r]=h[c>>>24];if(!e){for(;c>>>32-tl)break;var u=r-(c>>>32-t);let[i,n]=d[u];n||(i=p(i),d[u]=[i,!0]),s=Ii(s,i)}return s};return p},Fi=async(t,r)=>{const e=await r(t),i=Oi(vi,e);if("INDX"!==i.magic)throw new Error("Invalid INDX record");const n=Ni(i.encoding),a=e.slice(i.length);var o=Oi(wi,a);if("TAGX"!==o.magic)throw new Error("Invalid TAGX section");var s=(o.length-12)/4,l=Array.from({length:s},(e,t)=>new Uint8Array(a.slice(12+4*t,12+4*t+4)));const c={};let u=0;for(let e=0;e>Ui(S),null,x]));const j={};for([A,I,B,E]of $){const F=[];if(null!=I)for(let e=0;eDi(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 Mi(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?Zi:_i)(this).init()}#getHeaders(e){var t=Oi(mi,e);const r=Oi(gi,e);if("MOBI"!==r.magic)throw new Error("Missing MOBI header");var{titleOffset:i,titleLength:n,localeLanguage:a,localeRegion:o}=r;r.title=e.slice(i,i+n);a=Ai[a];r.language=a?.[o>>2]??a?.[0];a=64&r.exthFlag?((t,e)=>{var{magic:r,count:i}=Oi(bi,t);if("EXTH"!==r)throw new Error("Invalid EXTH header");const n=Ni(e),a={};let o=12;for(let e=0;ee:2===e?$i:17480===e?await ji(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const i=1&t,n=Hi(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=Mi(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:r,dataStart:i,keyLength:n,keyStart:a}=Oi(ki,e);const o=new Uint8Array(e.slice(i));if(2&r)for(var i=16===n?1024:1040,s=new Uint8Array(e.slice(a,a+n)),l=Math.min(i,o.length),c=0;c{const{table:r,cncx:i}=await Fi(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]})),a=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(a)),t);return n.filter(e=>0===e.headingLevel).map(a)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:fi(t?.title||this.decode(e.title)),author:t?.creator?.map(fi),publisher:fi(t?.publisher),language:t?.language??e.language,published:t?.date,description:fi(t?.description),subject:t?.subject?.map(fi),rights:fi(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 zi=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,Wi=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class _i{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=di.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(zi),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}));const n=[];try{const a=await this.mobi.getNCX(),o=({label:e,offset:t,children:r})=>{var i=t.toString().padStart(10,"0"),t=`filepos:${i}`;return n.push(i),{label:e=fi(e),href:t,subitems:r?.map(o)}};if(this.toc=a?.map(o),this.landmarks=await this.getGuide(),!this.toc){var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var r=this.resolveHref(e)["index"];const s=await this.sections[r].createDocument();this.toc=Array.from(s.querySelectorAll("a[filepos]"),e=>({label:e.innerText?.trim(),href:`filepos:${e.getAttribute("filepos")}`}))}}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(n.concat(Array.from(i.matchAll(Wi),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 a of e.querySelectorAll("img[recindex]")){var t=a.getAttribute("recindex");try{a.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const o of e.querySelectorAll("[mediarecindex]")){var r=o.getAttribute("mediarecindex"),i=o.getAttribute("recindex");try{o.src=await this.loadRecindex(r),i&&(o.poster=await this.loadRecindex(i))}catch(e){console.warn(`Failed to load media ${r}`)}}for(const s of e.querySelectorAll("[filepos]")){var n=s.getAttribute("filepos");s.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 a=i;n.length&&(a=i.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},r)=>{r=n[r+1],e=this.mobi.encode(``);a=Bi(a,e,i.subarray(t,r?.offset))}));var e=this.mobi.decode(a).replaceAll(zi,"");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 f(e,o,s,l){return new(s=s||Promise)(function(r,t){function n(e){try{a(l.next(e))}catch(e){t(e)}}function i(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(n,i)}a((l=l.apply(e,o||[])).next())})}class l{static getKookitConfig(e){return(JSON.parse(localStorage.getItem("kookitConfig"))||{})[e]}static setKookitConfig(e,t){let r=JSON.parse(localStorage.getItem("kookitConfig"))||{};r[e]=t,localStorage.setItem("kookitConfig",JSON.stringify(r))}static removeKookitConfig(){localStorage.removeItem("kookitConfig")}}let n=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"];String.prototype.contains=function(e){return-1Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title")),d=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),p=e=>e.trim().replace(/(\r\n|\n|\r)/gm,"").substring(0,100),o=e=>{var t=(new DOMParser).parseFromString(e,"text/html");let r=Array.from(t.querySelectorAll("img"));if(0===r.length)return e;for(let e=0;ee&&!e.contains("[")&&!e.contains("(")&&!e.contains("。")&&!e.contains("“")&&!e.contains("‘")&&!e.contains(";")&&!e.contains(";")&&(e.startsWith("CHAPTER")||e.startsWith("Chapter")||e.startsWith("序章")||e.startsWith("前言")||e.startsWith("声明")||e.startsWith("聲明")||e.startsWith("写在前面的话")||e.startsWith("后记")||e.startsWith("楔子")||e.startsWith("后序")||e.startsWith("寫在前面的話")||e.startsWith("後記")||e.startsWith("後序")||e.startsWith("第")&&r(e)||e.startsWith("卷")&&i(e)||!t&&e.contains("第")&&(" "===e[e.indexOf("第")-1]||" "===e[e.indexOf("第")-1]||"、"===e[e.indexOf("第")-1]||":"===e[e.indexOf("第")-1]||":"===e[e.indexOf("第")-1])&&r(e.substr(e.indexOf("第")))||!t&&e.indexOf(" ")&&a(e)||!t&&e.indexOf(" ")&&a(e)||!t&&e.indexOf("、")&&h(e)||!t&&e.indexOf(":")&&u(e)||!t&&e.indexOf(":")&&u(e)),r=t=>{let r=!1;for(let e=0;e!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1))&&!/^\d+$/.test(e.substring(1)))),a=e=>!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(" ")))||(!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(" ")))||(!!/^\d+$/.test(e.substring(0,e.indexOf(" ")))||!!/^\d+$/.test(e.substring(0,e.indexOf(" "))))),u=e=>!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(":")))||(!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(":")))||(!!/^\d+$/.test(e.substring(0,e.indexOf(":")))||!!/^\d+$/.test(e.substring(0,e.indexOf(":"))))),h=e=>!!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf("、")))||!!/^\d+$/.test(e.substring(0,e.indexOf("、"))),m=e=>"♦"===e.trim()||"●"===e.trim()||"◾"===e.trim()||"◀"===e.trim()||"◼"===e.trim()||"■"===e.trim(),g=e=>"|"===e.trim()||"Next"===e.trim()||"Main menu"===e.trim()||"Section menu"===e.trim()||"Previous"===e.trim();var y=window;window.a=window.atob;String.prototype.c=function(e){return-1"="!==e&&"-"!==e&&"_"!==e&&"+"!==e).join("")};const b=e=>{let t="",r=!1;var n;for(n of e.split("\n"))n.trim().slim()&&(c(n.trim().slim(),r)?((n.trim().slim().startsWith("第")||n.trim().slim().startsWith("Chapter")||n.trim().slim().startsWith("CHAPTER"))&&(r=!0),t+=`

${n}

`):t+=`

${n}

`);return t||`

Title

${e}

`},v=()=>f(void 0,void 0,void 0,function*(){l.removeKookitConfig();let e=yield new Promise((e,t)=>{e(y.e(y.a("ZG9jdW1lbnQudGl0bGU"+String.fromCharCode(61))))});return!!e.c(y.a("ZG8gUmU"+String.fromCharCode(61)))});var t="1.13.1",w="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||Function("return this")()||{},x=Array.prototype,T=Object.prototype,S="undefined"!=typeof Symbol?Symbol.prototype:null,k=x.push,C=x.slice,L=T.toString,A=T.hasOwnProperty,B="undefined"!=typeof ArrayBuffer,E="undefined"!=typeof DataView,I=Array.isArray,D=Object.keys,M=Object.create,O=B&&ArrayBuffer.isView,N=isNaN,R=isFinite,H=!{toString:null}.propertyIsEnumerable("toString"),U=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],$=Math.pow(2,53)-1;function j(i,a){return a=null==a?i.length-1:+a,function(){for(var e=Math.max(arguments.length-a,0),t=Array(e),r=0;r":">",'"':""","'":"'","`":"`"},lt=ot(st),ct=ot($e(st)),ut=xe.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},ht=/(.)^/,ft={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},dt=/\\|'|\r|\n|\u2028|\u2029/g;function pt(e){return"\\"+ft[e]}var mt=/^\s*(\w|\$)+\s*$/;var gt=0;function yt(e,t,r,n,i){if(!(n instanceof t))return e.apply(r,i);r=_e(e.prototype),i=e.apply(r,i);return P(i)?i:r}var bt=j(function(i,a){function o(){for(var e=0,t=a.length,r=Array(t),n=0;n{let n=document.getElementById("page-area");if(n){let e=n.getElementsByTagName("iframe")[0];var i;e&&("scroll"===r?(i=e.contentDocument)&&(r=i.body,i=i.documentElement,e.height=2*Math.max(r.scrollHeight,r.offsetHeight,i.clientHeight,i.scrollHeight,i.offsetHeight)+"px",setTimeout(()=>{let e=document.getElementById("page-area");if(e){let n=e.getElementsByTagName("iframe")[0];if(n){var i=n.contentDocument;if(i){let e=i.body;var a=e.lastElementChild,o=e.lastChild,s=e.getElementsByTagName("a"),l=e.getElementsByTagName("p"),c=e.getElementsByTagName("img"),u=e.getElementsByTagName("div"),i=s[s.length-1],s=l[l.length-1],c=l[c.length-1],u=u[u.length-1];let t=s||i||c||u;rr.isElement(i)&&rr.isElement(s)&&rr.isElement(u)&&(t=i.clientHeight+i.offsetTop>s.clientHeight+s.offsetTop?i:s,u.clientHeight+u.offsetTop>t.clientHeight+t.offsetTop&&(t=u)),rr.isElement(c)&&c.clientHeight+c.offsetTop>t.clientHeight+t.offsetTop&&(t=c);let r=0;if((a||t||o)&&(3!==o.nodeType||a||t)){if(3===o.nodeType&&document.createRange){let e=document.createRange();e.selectNodeContents(o),!e.getBoundingClientRect||(c=e.getBoundingClientRect())&&(r=c.bottom-c.top)}o=Math.max(rr.isElement(a)?a.clientHeight+a.offsetTop:0,rr.isElement(o)?o.clientHeight+o.offsetTop:0,rr.isElement(t)?t.clientHeight+t.offsetTop:0)+400+(3===o.nodeType?r:0);n.height=o+"px"}}}}},500)):e.height=t.offsetHeight+"px")}},ir=(e,t="")=>{var r=document.createElement("iframe");if(r.style.width="100%",r.style.border="0",r.style.margin="0",r.style.padding="0",r.style.fontSize="100%",r.style.font="inherit",r.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(r),t&&r.contentDocument){let e=r.contentDocument.createElement("style");e.id="azw3-style",e.textContent=t,r.contentDocument.head.appendChild(e)}},ar=(r,n)=>{let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){let t=i.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"!==n&&(i="double"===n?2:1,n=(n=Math.floor(r.clientWidth/12))%2==0?n:n-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: ${n}px;column-count: 12;column-width: ${(r.offsetWidth-n)/i}px;`))}}}};class or{constructor(e){this.bookStr=e,this.chapterList=[],this.chapterDocList=[]}getChapterDoc(){var t=this.bookStr.split("
").filter(e=>""!==e.trim()).map(e=>o(e));let n=[],i=[],r="";for(let e=0;e{let t=s(e);var r=0f(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;e&&(t=(t=Math.floor(r.clientWidth/12))%2==0?t:t-1,0{let a=document.getElementById("page-area");var o,s;a&&(!(o=a.getElementsByTagName("iframe")[0])||(s=o.contentDocument)&&Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<10&&Math.abs(s.body.scrollWidth-s.body.scrollLeft-s.body.clientWidth)<10&&(vr(e,t,r,n),i("rendered")))})(r,n,i,a,l),e.body.scrollBy({top:0,left:r.offsetWidth+t,behavior:s?"smooth":"auto"})))}}}),pr=(e,t,r,n)=>{r=r.filter(e=>e.href),t=rr.findLastIndex(r,{index:e,href:t});return"prev"===n?r[t-1]:r[t+1]},mr=(t,r,n,i)=>{var e=l.getKookitConfig("chapterTitle"),a=parseInt(l.getKookitConfig("chapterDocIndex")||"0"),o=l.getKookitConfig("chapterHref")||"";if(0!==a&&e){let e=pr(a,o,r,"prev");l.setKookitConfig("chapterTitle",e.title),l.setKookitConfig("chapterHref",e.href),l.setKookitConfig("chapterDocIndex",e.index.toString()),l.setKookitConfig("text","prevChapter"),gr(e.index,e.title,e.href,n,t,i),e.href&&-1{let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let e=s.contentDocument;e&&(e.body.innerHTML="",e.body.innerHTML=i[t].text,l.setKookitConfig("chapterTitle",r),l.setKookitConfig("chapterHref",n),l.setKookitConfig("chapterDocIndex",t.toString()),l.setKookitConfig("percentage",t/i.length+""),nr(a,o),((n,i)=>{let e=document.getElementById("page-area");if(e){var a=e.getElementsByTagName("iframe")[0];if(a){let r=a.contentDocument;if(r){var o,a=Math.floor(n.clientWidth/12),s=a%2==0?a:a-1;let e,t;for(o of r.getElementsByTagName("img")){var l=o.parentElement;e=0,t=0,o.width&&o.height?o.height/o.width>l.clientHeight/l.clientWidth?(e=l.clientHeight,t=e*o.width/o.height):(t=l.clientWidth,e=t*o.height/o.width):e=l&&l.clientWidth&&0f(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){let n=i.contentDocument;if(n){let e=Array.from(n.getElementsByTagName("link"));console.log(e),e.forEach(e=>{e.onload=()=>{console.log("finished")}});let t=[];e.forEach(r=>{t.push(new Promise((e,t)=>{r.addEventListener("load",e)}))});var a=yield Promise.all(t);console.log(a);let r=n.body;if(c){let e=d(n.body);var o=e.filter((e,t)=>p(e.innerText)&&(p(e.innerText)===p(c)||p(e.innerText)===hr.t2s(p(c))||p(e.innerText)===hr.s2t(p(c)))&&Math.abs(t-parseInt(u))<2);r=o[0]}else h&&-1f(void 0,void 0,void 0,function*(){if(!fr){let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let t=d(n.body);var i=t.filter(e=>wr(a,e,o)&&e.innerText.trim())[0];let r=0;for(let e=0;e{fr=!1},100)}}}}}),vr=(e,t,r,n)=>{var i=parseInt(l.getKookitConfig("chapterDocIndex")||"0"),a=l.getKookitConfig("chapterHref")||"";let o=pr(i,a,t,"next");l.setKookitConfig("chapterTitle",o.title),l.setKookitConfig("chapterHref",o.href),l.setKookitConfig("chapterDocIndex",o.index.toString()),l.setKookitConfig("text",""),gr(o.index,o.title,o.href,r,e,n),o.href&&-1{var n,i=!1,a=t.getBoundingClientRect();return"scroll"!==r&&t.innerText.trim()?i=-10<(n=a.left)&&n<=e.offsetWidth:t.innerText.trim()?i=(t=a.top)>=e.scrollTop&&t<=e.scrollTop+e.offsetHeight:"scroll"!==r&&(i=0<=(a=a.left)&&a<=e.offsetWidth),i};class xr{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 n=this.resolveNames(e);return n.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 n=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=n.resolveName(e);if("base"!==t.namespace&&""===t.value)delete n.callbacks[t.namespace];else if("base"===t.namespace)for(const r in n.callbacks)n.callbacks[r]instanceof Object&&n.callbacks[r][t.value]instanceof Array&&(delete n.callbacks[r][t.value],0===Object.keys(n.callbacks[r]).length&&delete n.callbacks[r]);else n.callbacks[t.namespace]instanceof Object&&n.callbacks[t.namespace][t.value]instanceof Array&&(delete n.callbacks[t.namespace][t.value],0===Object.keys(n.callbacks[t.namespace]).length&&delete n.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const r=this;const n=t instanceof Array?t:[];let i=this.resolveNames(e);i=this.resolveName(i[0]),setTimeout(()=>{if("base"===i.namespace)for(const e in r.callbacks){if(r.callbacks[e]instanceof Object&&r.callbacks[e][i.value]instanceof Array&&r.callbacks[e][i.value])r.callbacks[e][i.value].forEach(function(e){e.apply(r,n)});else if(this.callbacks[i.namespace]instanceof Object&&r.callbacks[i.namespace][i.value]){if(""===i.value)return console.warn("wrong name"),this;r.callbacks[i.namespace][i.value].forEach(function(e){e.apply(r,n)})}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",1{let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){i=i.contentDocument;if(i){let e=d(i.body),t=e.filter(e=>wr(r,e,n)&&e.innerText.trim());return("scroll"!==n?t:e).map(e=>e.innerText).join(" ")}}}})(this.element,this.mode)}doSearch(e){return((n,i)=>{let a=[];for(let r=0;r{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return{totalPage:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(t.body.scrollLeft/t.body.clientWidth+"")+1}}}})()}record(){br(this.element,this.mode)}getPosition(){return{text:l.getKookitConfig("text"),chapterTitle:l.getKookitConfig("chapterTitle"),chapterDocIndex:l.getKookitConfig("chapterDocIndex"),chapterHref:l.getKookitConfig("chapterHref"),count:l.getKookitConfig("count"),percentage:l.getKookitConfig("percentage")}}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"))}}}}class Sr{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return f(this,void 0,void 0,function*(){return this.chapterList=yield Promise.all(e.map(t=>f(this,void 0,void 0,function*(){var e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1;return{title:t.label||"Content",href:t.href,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return f(this,void 0,void 0,function*(){let e=yield Promise.all(this.book.sections.map(e=>f(this,void 0,void 0,function*(){return e.load?(yield fetch(yield e.load()).then(e=>e.blob())).text():""})));const r=this.flattenChapters.map(e=>e.index);return e.map(e=>o(e)).map((e,t)=>-1f(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[0].name,description:t.description,publisher:t.publisher,cover:r.result})}}catch(e){n({name:t.title,author:t.author[0].name||t.author[0],description:t.description,publisher:t.publisher,cover:""})}}))}}const kr=(e,n)=>e.map((e,t,r)=>n(e,t,r)?t:null).filter(e=>null!=e),Cr=(n,e)=>[-1,...e,n.length].reduce(({xs:e,a:t},r)=>({xs:e?.concat([n.slice(t+1,r)])??[],a:r}),{}).xs,Lr=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),Ar=/\d/,Br=/^epubcfi\((.*)\)$/,Er=e=>e.replace(/[\^[\](),;=]/g,"^$&"),Ir=e=>Br.test(e)?e:`epubcfi(${e})`,Dr=(e,t)=>kr(e,([e])=>e===t),Mr=e=>{const t=[];let r;for(var[n,i]of e){if("/"===n)t.push({index:i});else{const a=t[t.length-1];if(":"===n)a.offset=i;else if("~"===n)a.temporal=i;else if("@"===n)a.spatial=(a.spatial??[]).concat(i);else if(";s"===n)a.side=i;else if("["===n){if("/"!==r||!i){a.text=(a.text??[]).concat(i);continue}a.id=i}}r=n}return t},Or=e=>Cr(e,Dr(e,"!")).map(Mr),Nr=e=>{var t=(e=>{const t=[];let r,n,i="";var a=e=>(t.push(e),r=null,i=""),o=e=>(i+=e,n=!1);for(const s of Array.from(e.trim()).concat(""))if("^"!==s||n){if("!"===r)a(["!"]);else if(","===r)a([","]);else if("/"===r||":"===r){if(Ar.test(s)){o(s);continue}a([r,parseInt(i)])}else if("~"===r){if(Ar.test(s)||"."===s){o(s);continue}a(["~",parseFloat(i)])}else if("@"===r){if(":"===s){a(["@",parseFloat(i)]),r="@";continue}if(Ar.test(s)||"."===s){o(s);continue}a(["@",parseFloat(i)])}else{if("["===r){";"!==s||n?","!==s||n?"]"!==s||n?o(s):a(["[",i]):(a(["[",i]),r="["):(a(["[",i]),r=";");continue}if(r?.startsWith(";")){"="!==s||n?";"!==s||n?"]"!==s||n?o(s):a([r,i]):(a([r,i]),r=";"):(r=`;${i}`,i="");continue}}"/"!==s&&":"!==s&&"~"!==s&&"@"!==s&&"["!==s&&"!"!==s&&","!==s||(r=s)}else n=!0;return t})((r=e).match(Br)?.[1]??r),e=Dr(t,",");if(!e.length)return Or(t);var[r,t,e]=Cr(t,e).map(Or);return{parent:r,start:t,end:e}},Rr=({index:e,id:t,offset:r,temporal:n,spatial:i,text:a,side:o})=>{var s=o?`;s=${o}`:"";return`/${e}`+(t?`[${Er(t)}${s}]`:"")+(null!=r&&e%2?`:${r}`:"")+(n?`~${n}`:"")+(i?`@${i.join(":")}`:"")+(a||!t&&o?"["+(a?.map(Er)?.join(",")??"")+s+"]":"")},Hr=e=>e.parent?[e.parent,e.start,e.end].map(Hr).join(","):e.map(e=>e.map(Rr).join("")).join("!"),Ur=e=>Ir(Hr(e)),$r=(e,t)=>"string"==typeof e?Ur($r(Nr(e),t)):e.parent?Lr(e.parent,e[t?"end":"start"]):e,jr=({nodeType:e})=>3===e||4===e,Pr=({nodeType:e})=>1===e,Fr=e=>{const t=Array.from(e.childNodes).filter(e=>jr(e)||Pr(e)).reduce((e,t)=>{let r=e[e.length-1];return r?jr(t)?Array.isArray(r)?r.push(t):jr(r)?e[e.length-1]=[r,t]:e.push(t):Pr(r)?e.push(null,t):e.push(t):e.push(t),e},[]);return Pr(t[0])&&t.unshift("first"),Pr(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},zr=(e,t)=>e?Fr(e)[t]:null,Wr=(e,t)=>{var r,n=t[t.length-1]["id"];if(n){n=e.ownerDocument.getElementById(n);if(n)return{node:n,offset:0}}for({index:r}of t){var i=zr(e,r);if("first"===i)return{node:e.firstChild??e};if("last"===i)return{node:e.lastChild??e};if("before"===i)return{node:e,before:!0};if("after"===i)return{node:e,after:!0};e=i}var a=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:a};let o=0;for(const l of e){var s=l.nodeValue["length"];if(o+s>=a)return{node:l,offset:a-o};o+=s}},_r=(t,r)=>{var{parentNode:e,id:n}=t;const i=Fr(e);var a=i.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),o=i[a];if(Array.isArray(o)){let e=0;for(const s of o){if(s===t){e+=r;break}e+=s.nodeValue.length}r=e}a={id:n,index:a,offset:r};return e!==t.ownerDocument.documentElement?_r(e).concat(a):[a]},Xr=(e,t)=>Wr(e.documentElement,$r(t)).node,qr={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"},Kr={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)/},Vr=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),Gr=e=>e?e.trim().replace(/\s{2,}/g," "):"",Zr=(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,Jr=(...e)=>t=>t?Object.fromEntries(e.map(e=>[Vr(e),t.getAttribute(e)])):null,Yr=e=>Gr(e?.textContent),Qr=(e,r)=>{e=e.lookupNamespaceURI(null)===r||e.lookupPrefix(r);const n=e?(e,t)=>e=>e.namespaceURI===r&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(n(e,t)),$$:(e,t)=>[...e.children].filter(n(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(r,t)]:(e,t)=>[...e.getElementsByTagName(r,t)]}},en=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var r="whatever:///";return decodeURI(new URL(t,r+e).href.replace(r,""))}catch(e){return console.warn(e),t}},tn=e=>/^(?!blob)\w+:/i.test(e),rn=async(e,t,r)=>{const n=[];e.replace(t,(...e)=>(n.push(e),null));const i=[];for(const a of n)i.push(await r(...a));return e.replace(t,()=>i.shift())},nn=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");Me={attrs:["dir","xml:lang"]},st={name:"alternate-script",many:!0,...Me,props:["file-as"]},re={many:!0,...Me,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",st]};const an=[{name:"title",many:!0,...Me,props:["title-type","display-seq","file-as",st]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...re},{name:"contributor",...re},{name:"publisher",...Me,props:["file-as",st]},{name:"description",...Me,props:[st]},{name:"rights",...Me,props:[st]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...Me,props:["term","authority",st]},{name:"belongs-to-collection",type:"meta",many:!0,...Me,props:["collection-type","group-position","dcterms:identifier","file-as",st,{name:"belongs-to-collection",recursive:!0}]}],on=(e,a=e=>e)=>{const{$:o,$$:r,$$$:t}=Qr(e,qr.XHTML),n=i=>e=>{const t=o(e,"a")??o(e,"span");var r=o(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(a(e)):null;const n={label:Yr(t)||t?.getAttribute("title"),href:e,subitems:s(r)};return i&&(n.type=t?.getAttributeNS(qr.EPUB,"type")?.split(/\s/)),n},s=(e,t)=>e?r(e,"li").map(n(t)):null;var i=(e,t)=>s(o(e,"ol"),t);let l=null,c=null,u=null,h=[];for(const f of t(e,"nav")){const d=f.getAttributeNS(qr.EPUB,"type")?.split(/\s/)??[];d.includes("toc")?l??=i(f):d.includes("page-list")?c??=i(f):d.includes("landmarks")?u??=i(f,!0):h.push({label:Yr(f.firstElementChild),type:d,list:i(f)})}return{toc:l,pageList:c,landmarks:u,others:h}},sn=(r,a=e=>e)=>{const{$:o,$$:s}=Qr(r,qr.NCX),l=e=>{var t=o(e,"navLabel");const r=o(e,"content");var n=Yr(t),t=(t=r.getAttribute("src"))?decodeURI(a(t)):null;if("navPoint"!==e.localName)return{label:n,href:t};{const i=s(e,"navPoint");return{label:n,href:t,subitems:i.length?i.map(l):null}}},n=(e,t)=>s(e,t).map(l);var e=(e,t)=>{e=o(r.documentElement,e);return e?n(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:s(r.documentElement,"navList").map(e=>({label:Yr(o(e,"navLabel")),list:n(e,"navTarget")}))}},ln=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[r,n,i]=t;return 60*r*60+60*n+i}if(2===t.length){var[t,a]=t;return 60*t+a}var[a,e]=e.split(/(?=[^\d.])/);return parseFloat(a)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},cn=(e,n=e=>e)=>{const{$:i,$$$:t}=Qr(e,qr.SMIL);return t(e,"par").map(e=>{var t=i(e,"text")?.getAttribute("src")?.split("#")?.[1];const r=i(e,"audio");return r?{id:t,audio:{src:(e=r.getAttribute("src"))?decodeURI(n(e)):null,clipBegin:ln(r.getAttribute("clipBegin")),clipEnd:ln(r.getAttribute("clipEnd"))}}:{id:t}})},un=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,hn=e=>Yr(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(qr.DC,"identifier")[0]),fn=async(e,t,r)=>{const n=new Uint8Array(await r.slice(0,t).arrayBuffer());t=Math.min(t,n.length);for(var i=0;i{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(hn(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>fn(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const r=(e=>{for(const r of e.getElementsByTagNameNS(qr.DC,"identifier")){var[t]=Yr(r).split(":").slice(-1);if(un.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)=>fn(e,1024,t)}});class pn{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var r,n;if(e)for({algorithm:r,uri:n}of Array.from(e.getElementsByTagNameNS(qr.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(qr.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(qr.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(r)){const i=this.#algorithms[r];if(!i){console.warn("Unknown encryption algorithm");continue}const a=await i.key(t);this.#decoders.set(r,e=>i.decode(a,e))}this.#uris.set(n,r)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class mn{constructor({opf:e,resolveHref:n}){this.opf=e;const{$:t,$$:r,$$$:i}=Qr(e,qr.OPF);var a=t(e.documentElement,"manifest");const o=t(e.documentElement,"spine"),s=r(o,"itemref");this.manifest=r(a,"item").map(Jr("href","id","media-type","properties","media-overlay")).map(e=>(e.href=n(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=s.map(Jr("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=o.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(o.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===Kr.NCX))?.href;a=t(e.documentElement,"guide");a&&(this.guide=r(a,"reference").map(Jr("type","title","href")).map(({type:e,title:t,href:r})=>({label:t,type:e.split(/\s/),href:n(r)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(i(e,"meta").find(Zr("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var r,n,i=e[0]["parentNode"];const a=_r(i);for([r,n]of Fr(i).entries()){var o=e[t.length];n===o&&t.push(Ur([a.concat({id:o.id,index:r})]))}return t})(s)}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=Nr(e),r=(t.parent??t).shift();let n=Xr(this.opf,r);n&&"idref"!==n.nodeName&&(r.at(-1).id=null,n=Xr(this.opf,r));const i=n?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===i),anchor:e=>((e,t)=>{var r=$r(t),n=$r(t,!0),t=e.documentElement,r=Wr(t,r[0]),n=Wr(t,n[0]);const i=e.createRange();return r.before?i.setStartBefore(r.node):r.after?i.setStartAfter(r.node):i.setStart(r.node,r.offset),n.before?i.setEndBefore(n.node):n.after?i.setEndAfter(n.node):i.setEnd(n.node,n.offset),i})(e,t)}}}class gn{#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,n){if(!t)return"";r=URL.createObjectURL(new Blob([t],{type:r}));if(this.#cache.set(e,r),this.#refCount.set(e,1),n){const i=this.#children.get(n);i?i.push(e):this.#children.set(n,[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:n}=e;var i=Kr.JS.test(e.mediaType);if(i&&!this.allowScript)return null;var a=t.at(-1);return this.#cache.has(r)?this.ref(r,a):(i||[Kr.XHTML,Kr.HTML,Kr.CSS,Kr.SVG].includes(n))&&t.every(e=>e!==r)?this.loadReplaced(e,t):this.createURL(r,await this.loadBlob(r),n,a)}async loadHref(e,t,r=[]){if(tn(e))return e;const n=en(e,t);var i=this.manifest.find(e=>e.href===n);return i?this.loadItem(i,r.concat(t)):e}async loadReplaced(e,i=[]){const{href:a,mediaType:r}=e;var n,o=i.at(-1),s=await this.loadText(a);if(!s)return null;if([Kr.XHTML,Kr.HTML,Kr.SVG].includes(r)){let t=(new DOMParser).parseFromString(s,r);if(r===Kr.XHTML&&t.querySelector("parsererror")&&(e.mediaType=Kr.HTML,t=(new DOMParser).parseFromString(s,e.mediaType)),[Kr.XHTML,Kr.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(n=await rn(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,r,n)=>this.loadHref(r,a,i).then(e=>`${t}${e}${n}`)),e.replaceWith(t.createProcessingInstruction(e.target,n))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),a,i));for(const u of t.querySelectorAll("link[href]"))await l(u,"href");for(const h of t.querySelectorAll("[src]"))await l(h,"src");for(const f of t.querySelectorAll("[poster]"))await l(f,"poster");for(const d of t.querySelectorAll("object[data]"))await l(d,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(qr.XLINK,"href",await this.loadHref(p.getAttributeNS(qr.XLINK,"href"),a,i));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,a,i));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),a,i));const c=(new XMLSerializer).serializeToString(t);return this.createURL(a,c,e.mediaType,o)}const c=r===Kr.CSS?await this.replaceCSS(s,a,i):await this.replaceString(s,a,i);return this.createURL(a,c,r,o)}async replaceCSS(e,r,n=[]){e=await rn(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,r,n).then(e=>`url("${e}")`));const t=await rn(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,r,n).then(e=>`@import "${e}"`)),i=window?.innerWidth??800,a=window?.innerHeight??600,o=t.replace(/(\d*\.?\d+)vw/g,(e,t)=>parseFloat(t)*i/100+"px").replace(/(\d*\.?\d+)vh/g,(e,t)=>parseFloat(t)*a/100+"px");return o.replaceAll("-epub-","")}replaceString(e,o,t=[]){const s=new Map,r=this.assets.map(e=>{if(e.href!==o){var t=((e,t)=>{if(!e)return t;const r=e.replace(/\/$/,"").split("/"),n=t.replace(/\/$/,"").split("/");t=(r.length>n.length?r:n).findIndex((e,t)=>r[t]!==n[t]);return t<0?"":Array(r.length-t).fill("..").concat(n.slice(t)).join("/")})(o.slice(0,o.lastIndexOf("/")+1),e.href),r=encodeURI(t),n="/"+e.href,i=encodeURI(n),i=new Set([t,r,n,i]);for(const a of i)s.set(a,e);return Array.from(i)}}).flat().filter(e=>e);if(!r.length)return e;var n=new RegExp(r.map(nn).join("|"),"g");return rn(e,n,async e=>this.loadItem(s.get(e.replace(/^\//,"")),t.concat(o)))}unloadItem(e){this.unref(e?.href)}}class yn{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:r,sha1:n}){this.loadText=e,this.loadBlob=t,this.getSize=r,this.#encryption=new pn(dn(n))}#parseXML(e){return e?this.parser.parseFromString(e,Kr.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(qr.CONTAINER,"rootfile"),Jr("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 n=await this.#loadXML(r);if(!n)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,n),this.resources=new mn({opf:n,resolveHref:e=>en(e,r)});const a=new gn({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:n,properties:e=[]}=e;const i=this.resources.getItemByID(r);return i?{id:this.resources.getItemByID(r)?.href,load:()=>a.loadItem(i),unload:()=>a.unloadItem(i),createDocument:()=>this.loadDocument(i),size:this.getSize(i.href),cfi:this.resources.cfis[t],linear:n,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=>en(e,i.href),loadMediaOverlay:()=>this.loadMediaOverlay(i)}:(console.warn(`Could not find item with ID "${r}" in manifest`),null)}).filter(e=>e);const{navPath:i,ncxPath:o}=this.resources;if(i)try{var s=on(await this.#loadXML(i),e=>en(e,i));this.toc=s.toc,this.pageList=s.pageList,this.landmarks=s.landmarks}catch(e){console.warn(e)}if(!this.toc&&o)try{var l=sn(await this.#loadXML(o),e=>en(e,o));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:u,media:h}=(e=>{const{$:t,$$:r}=Qr(e,qr.OPF),n=t(e.documentElement,"metadata"),a=Array.from(n.children),l=(o,t)=>{if(!t)return null;const{props:e=[],attrs:r=[]}=o,n=Yr(t);if(!e.length&&!r.length)return n;var i=t.getAttribute("id");const s=i?a.filter(Zr("refines","#"+i)):[];return Object.fromEntries([["value",n]].concat(e.map(e=>{var{many:t,recursive:r}=e,n="string"==typeof e?e:e.name,i=Zr("property",n);const a=r?o:e;return[Vr(n),t?s.filter(i).map(e=>l(a,e)):l(a,s.find(i))]})).concat(r.map(e=>[Vr(e),t.getAttribute(e)])))},o=a.filter(Zr("refines",null));e=t=>Object.fromEntries(r(n,"meta").filter(Zr("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),Yr(e)]));return{metadata:Object.fromEntries(an.map(t=>{const{type:e,name:r,many:n}=t;var i="meta"===e?e=>e.namespaceURI===qr.OPF&&e.getAttribute("property")===r:e=>e.namespaceURI===qr.DC&&e.localName===r;return[Vr(r),n?o.filter(i).map(e=>l(t,e)):l(t,o.find(i))]})),rendition:e("rendition:"),media:e("media:")}})(n);this.rendition=u,this.media=h,h.duration=ln(h.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:hn(n),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 f={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};n=r=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:f[e])??r))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[r],e]};return c?.creator?.map(n("author"))?.concat(c?.contributor?.map?.(n("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 cn(e,e=>en(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,r]=e.split("#"),n=this.resources.getItemByHref(decodeURI(t));return n?{index:this.resources.spine.findIndex(({idref:e})=>e===n.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 tn(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)}}}const bn=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},vn={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},wn={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},xn={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Tn={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"]},Sn={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},kn={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Cn={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"]},Ln={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},An={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},Bn={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},En={magic:[0,4,"string"],numEntries:[8,4,"uint"]},In={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Dn={1252:"windows-1252",65001:"utf-8"},Mn={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"]},On={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"]},Nn=(e,t)=>{const r=new e.constructor(e.length+t.length);return r.set(e),r.set(t,e.length),r},Rn=(e,t,r)=>{const n=new e.constructor(e.length+t.length+r.length);return n.set(e),n.set(t,e.length),n.set(r,e.length+t.length),n},Hn=new TextDecoder,Un=e=>Hn.decode(e),$n=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},jn=(e,i)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,r,n]])=>[e,("string"===n?Un:$n)(i.slice(t,t+r))])),Pn=e=>new TextDecoder(Dn[e]),Fn=(e,t=0)=>{let r=0,n=0;for(const i of e.subarray(t,t+4))if(r=r<<7|(127&i)>>>0,n++,128&i)break;return{value:r,length:n}},zn=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},Wn=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},_n=t=>{let r=[];for(let e=0;e>>3,o=3+(7&i);for(let e=0;e{const n=await r(t.huffcdic),{magic:e,offset1:i,offset2:a}=jn(An,n);if("HUFF"!==e)throw new Error("Invalid HUFF record");const h=Array.from({length:256},(e,t)=>i+4*t).map(e=>$n(n.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),f=[null].concat(Array.from({length:32},(e,t)=>a+8*t).map(e=>[$n(n.slice(e,e+4)),$n(n.slice(e+4,e+8))])),d=[];for(let e=1;e{let s=new Uint8Array;var l=8*o.byteLength;for(let a=0;a{var e=r+32,n=e>>3;let i=0n;for(let e=r>>3;e<=n;e++)i=i<<8n|BigInt(t[e]??0);return i>>8n-BigInt(7&e)&0xffffffffn})(o,a));let[e,t,r]=h[c>>>24];if(!e){for(;c>>>32-tl)break;var u=r-(c>>>32-t);let[n,i]=d[u];i||(n=p(n),d[u]=[n,!0]),s=Nn(s,n)}return s};return p},qn=async(t,r)=>{const e=await r(t),n=jn(Cn,e);if("INDX"!==n.magic)throw new Error("Invalid INDX record");const i=Pn(n.encoding),a=e.slice(n.length);var o=jn(Ln,a);if("TAGX"!==o.magic)throw new Error("Invalid TAGX section");var s=(o.length-12)/4,l=Array.from({length:s},(e,t)=>new Uint8Array(a.slice(12+4*t,12+4*t+4)));const c={};let u=0;for(let e=0;e>Wn(T),null,x]));const j={};for([A,B,E,I]of $){const P=[];if(null!=B)for(let e=0;e$n(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 Un(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?ri:Zn)(this).init()}#getHeaders(e){var t=jn(xn,e);const r=jn(Tn,e);if("MOBI"!==r.magic)throw new Error("Missing MOBI header");var{titleOffset:n,titleLength:i,localeLanguage:a,localeRegion:o}=r;r.title=e.slice(n,n+i);a=On[a];r.language=a?.[o>>2]??a?.[0];a=64&r.exthFlag?((t,e)=>{var{magic:r,count:n}=jn(kn,t);if("EXTH"!==r)throw new Error("Invalid EXTH header");const i=Pn(e),a={};let o=12;for(let e=0;ee:2===e?_n:17480===e?await Xn(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const n=1&t,i=zn(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 n&&(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=Un(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:r,dataStart:n,keyLength:i,keyStart:a}=jn(In,e);const o=new Uint8Array(e.slice(n));if(2&r)for(var n=16===i?1024:1040,s=new Uint8Array(e.slice(a,a+i)),l=Math.min(n,o.length),c=0;c{const{table:r,cncx:n}=await qn(e,t),i=r.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:n[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),a=t=>(null==t.firstChild||(t.children=i.filter(e=>e.parent===t.index).map(a)),t);return i.filter(e=>0===e.headingLevel).map(a)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:bn(t?.title||this.decode(e.title)),author:t?.creator?.map(bn),publisher:bn(t?.publisher),language:t?.language??e.language,published:t?.date,description:bn(t?.description),subject:t?.subject?.map(bn),rights:bn(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 Vn=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,Gn=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class Zn{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=vn.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(n.matchAll(Vn),e=>e.index)).map((e,t,r)=>n.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}));const i=[];try{const a=await this.mobi.getNCX(),o=({label:e,offset:t,children:r})=>{var n=t.toString().padStart(10,"0"),t=`filepos:${n}`;return i.push(n),{label:e=bn(e),href:t,subitems:r?.map(o)}};if(this.toc=a?.map(o),this.landmarks=await this.getGuide(),!this.toc){var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var r=this.resolveHref(e)["index"];const s=await this.sections[r].createDocument();this.toc=Array.from(s.querySelectorAll("a[filepos]"),e=>({label:e.innerText?.trim(),href:`filepos:${e.getAttribute("filepos")}`}))}}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(i.concat(Array.from(n.matchAll(Gn),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 a of e.querySelectorAll("img[recindex]")){var t=a.getAttribute("recindex");try{a.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const o of e.querySelectorAll("[mediarecindex]")){var r=o.getAttribute("mediarecindex"),n=o.getAttribute("recindex");try{o.src=await this.loadRecindex(r),n&&(o.poster=await this.loadRecindex(n))}catch(e){console.warn(`Failed to load media ${r}`)}}for(const s of e.querySelectorAll("[filepos]")){var i=s.getAttribute("filepos");s.href=`filepos:${i}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const n=t["raw"],i=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let a=n;i.length&&(a=n.subarray(0,i[0].offset),i.forEach(({filepos:e,offset:t},r)=>{r=i[r+1],e=this.mobi.encode(``);a=Rn(a,e,n.subarray(t,r?.offset))}));var e=this.mobi.decode(a).replaceAll(Vn,"");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; margin-inline-end: 0; - }`)),await this.replaceResources(t);var i=this.serializer.serializeToString(t),i=URL.createObjectURL(new Blob([i],{type:this.#type}));return this.#cache.set(e,i),i}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],r=Number(t);return{index:this.#sections.findIndex(e=>e.end>r),anchor:e=>e.getElementById(`filepos${t}`)}}splitTOCHref(e){e=e.match(/filepos:(.*)/)[1];const t=Number(e);return[this.#sections.findIndex(e=>e.end>t),`filepos${e}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}}const qi=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,Xi=/kindle:pos:fid:(\w+):off:(\w+)/,Ki=e=>{var[t,e]=e.match(Xi).slice(1);return{fid:parseInt(t,32),off:parseInt(e,32)}},Vi=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,Gi=e=>{var t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(t){var[,e,t]=t;return`[${e}="${CSS.escape(t)}"]`}};class Zi{parser=new DOMParser;#cache=new Map;#fragmentOffsets=new Map;#fragmentSelectors=new Map;#tables={};#sections;#fullRawLength;#rawHead=new Uint8Array;#rawTail=new Uint8Array;#lastLoadedHead=-1;#lastLoadedTail=-1;#checkType=!0;#type=di.XHTML;constructor(e){this.mobi=e}async init(){const e=this.mobi.loadRecord.bind(this.mobi);var t=this.mobi.headers["kf8"];try{const l=await e(t.fdst);var r=Oi(Ti,l);if("FDST"!==r.magic)throw new Error("Missing FDST record");var i=Array.from({length:r.numEntries},(e,t)=>12+8*t).map(e=>[Di(l.slice(e,e+4)),Di(l.slice(e+4,e+8))]);this.#tables.fdstTable=i,this.#fullRawLength=i[i.length-1][1]}catch{}const n=(await Fi(t.skel,e)).table.map(({name:e,tagMap:t},r)=>({index:r,name:e,numFrag:t[1][0],offset:t[6][0],length:t[6][1]})),a=await Fi(t.frag,e),o=a.table.map(({name:e,tagMap:t})=>({insertOffset:parseInt(e),selector:a.cncx[t[2][0]],index:t[4][0],offset:t[6][0],length:t[6][1]}));this.#tables.skelTable=n,this.#tables.fragTable=o,this.#sections=n.reduce((e,t)=>{var r=e[e.length-1],i=r?.fragEnd??0,n=i+t.numFrag;const a=o.slice(i,n);i=t.length+a.map(e=>e.length).reduce((e,t)=>e+t);return e.concat({skel:t,frags:a,fragEnd:n,length:i,totalLength:(r?.totalLength??0)+i})},[]),this.#sections.unshift({frags:[]}),this.sections=this.#sections.map((e,t)=>e.frags.length?{id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.length}:{linear:"no"});try{const c=await this.mobi.getNCX(),u=({label:e,pos:t,children:r})=>{var[i,n]=t,t=Vi(i,n);const a=this.#fragmentOffsets.get(i);return a?a.push(n):this.#fragmentOffsets.set(i,[n]),{label:fi(e),href:t,subitems:r?.map(u)}};this.toc=c?.map(u),this.landmarks=await this.getGuide()}catch(e){console.warn(e)}const s=this.mobi.headers["exth"];return this.dir=s.pageProgressionDirection,this.rendition={layout:"true"===s.fixedLayout?"pre-paginated":"reflowable",viewport:Object.fromEntries(s.originalResolution?.split("x")?.slice(0,2)?.map((e,t)=>[t?"height":"width",e])??[])},this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getResourcesByMagic(t){const r={};var i=this.mobi.headers.kf8.resourceStart,n=this.mobi.pdb.numRecords;for(let e=i;ee===o);a&&(r[a]=e)}catch{}return r}async getGuide(){var e=this.mobi.headers.kf8.guide;if(e<4294967295){var t=this.mobi.loadRecord.bind(this.mobi);const{table:r,cncx:i}=await Fi(e,t);return r.map(({name:e,tagMap:t})=>({label:i[t[1][0]]??"",type:e?.split(/\s/),href:Vi(t[6]?.[0]??t[3]?.[0])}))}}async loadResourceBlob(e){var{resourceType:t,id:r,type:e}=(e=>{var[t,r,e]=e.match(qi).slice(1);return{resourceType:t,id:parseInt(r,32),type:e}})(e),r="flow"===t?await this.loadFlow(r):await this.mobi.loadResource(r-1),r=[di.XHTML,di.HTML,di.CSS,di.SVG].includes(e)?await this.replaceResources(this.mobi.decode(r)):r;return new Blob([r],{type:e})}async loadResource(e){if(this.#cache.has(e))return this.#cache.get(e);var t=await this.loadResourceBlob(e),t=URL.createObjectURL(t);return this.#cache.set(e,t),t}replaceResources(e){return(async(e,t,r)=>{const i=[];e.replace(t,(...e)=>(i.push(e),null));const n=[];for(const a of i)n.push(await r(...a));return e.replace(t,()=>n.shift())})(e,new RegExp(qi,"g"),this.loadResource.bind(this))}async loadRaw(e,t){var r=t-this.#rawHead.length,i=null==this.#fullRawLength?1/0:this.#fullRawLength-this.#rawTail.length-e;if(r<0||re;){var a=this.mobi.headers.palmdoc.numTextRecords-1-++this.#lastLoadedTail,a=await this.mobi.loadText(a);this.#rawTail=Ii(a,this.#rawTail)}i=this.#fullRawLength-this.#rawTail.length;return this.#rawTail.slice(e-i,t-i)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#tables.fdstTable[e])}async loadText(e){var{skel:t,frags:r,length:e}=e;const i=await this.loadRaw(t.offset,t.offset+e);let n=i.slice(0,t.length);for(const c of r){var a=c.insertOffset-t.offset,o=t.length+c.offset,s=i.slice(o,o+c.length);n=Bi(n.slice(0,a),s,n.slice(a));a=this.#fragmentOffsets.get(c.index);if(a)for(const u of a){var l=this.mobi.decode(s).slice(u),l=Gi(l);this.#setFragmentSelector(c.index,u,l)}}return this.mobi.decode(n)}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);var t=await this.loadText(e);this.#checkType&&this.parser.parseFromString(t,this.#type).querySelector("parsererror")&&(this.#type=di.HTML),this.#checkType&&(this.#checkType=!1);t=await this.replaceResources(t),t=URL.createObjectURL(new Blob([t],{type:this.#type}));return this.#cache.set(e,t),t}getIndexByFID(t){return this.#sections.findIndex(e=>e.frags.some(e=>e.index===t))}#setFragmentSelector(e,t,r){const i=this.#fragmentSelectors.get(e);if(i)i.set(t,r);else{const i=new Map;this.#fragmentSelectors.set(e,i),i.set(t,r)}}async resolveHref(e){const{fid:t,off:r}=Ki(e);var i=this.getIndexByFID(t);if(!(i<0)){const a=this.#fragmentSelectors.get(t)?.get(r);if(a)return{index:i,anchor:e=>e.querySelector(a)};const{skel:o,frags:s}=this.#sections[i];var n=s.find(e=>e.index===t),e=o.offset+o.length+n.offset,n=await this.loadRaw(e,e+n.length),n=this.mobi.decode(n).slice(r);const l=Gi(n);this.#setFragmentSelector(t,r,l);return{index:i,anchor:e=>e.querySelector(l)}}}splitTOCHref(e){e=Ki(e);return[this.getIndexByFID(e.fid),e]}getTOCFragment(e,{fid:t,off:r}){r=this.#fragmentSelectors.get(t)?.get(r);return e.querySelector(r)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}}const Ji={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"};class Yi{constructor(e,t,r,i,n){this.fileNameList=e,this.zip=t,this.bookStr="",this.format=n,this.bookDoc=null,this.mode=r,this.chapterList=[],console.log(this.fileNameList),this.extension=this.fileNameList[0].split(".").reverse()[0],this.element=i,this.getBookStr()}getBookStr(){let r=document.createElement("div");var i="single"===this.mode?1:2,e=Math.floor(this.element.clientWidth/12),n=e%2==0?e:e-1;for(let t=0;tu(this,void 0,void 0,function*(){var e=new Image;e.onload=function(){t(e.height/e.width)},e.src=yield this.getFirstImage()}))}getFirstImage(){return u(this,void 0,void 0,function*(){this.extension=this.fileNameList[0].split(".").reverse()[0];let e=new ArrayBuffer(0);return"CBR"===this.format?e=this.zip.decompress(this.fileNameList[0]):"CBT"===this.format?e=this.zip[Yt.findLastIndex(this.zip,{name:this.fileNameList[0]})].buffer:"CBZ"===this.format&&(e=yield this.zip.file(this.fileNameList[0]).async("arraybuffer")),"data:"+Ji[this.extension.toLowerCase()]+";base64,"+this.base64ArrayBuffer(e)})}renderComic(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;e&&(e.body.innerHTML=this.bookDoc.outerHTML)}}}renderImage(n){return new Promise((i,e)=>u(this,void 0,void 0,function*(){console.log(this.fileNameList[0]),this.extension=this.fileNameList[0].split(".").reverse()[0];let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){let t=r.contentDocument;if(t)if(t.getElementById(n+"")&&!t.getElementById(n+"").src){let e;e="cbr"===this.format?this.zip.decompress(this.fileNameList[n]):"cbt"===this.format?this.zip[Yt.findLastIndex(this.zip,{name:this.fileNameList[n]})].buffer:yield this.zip.file(this.fileNameList[n]).async("arraybuffer"),t.getElementById(n+"")&&(t.getElementById(n+"").src="data:"+Ji[this.extension.toLowerCase()]+";base64,"+this.base64ArrayBuffer(e)),i()}else i()}}}))}base64ArrayBuffer(e){for(var t,r="",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),a=n.byteLength,e=a%3,o=a-e,s=0;s>18]+i[(258048&t)>>12]+i[(4032&t)>>6]+i[63&t];return 1==e?r+=i[(252&(t=n[o]))>>2]+i[(3&t)<<4]+"==":2==e&&(r+=i[(64512&(t=n[o]<<8|n[1+o]))>>10]+i[(1008&t)>>4]+i[(15&t)<<2]+"="),r}getMetadata(){return new Promise((e,t)=>u(this,void 0,void 0,function*(){e({cover:yield this.getFirstImage()})}))}}const Qi=(r,i,n)=>u(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;e&&(t=(t=Math.floor(r.clientWidth/12))%2==0?t:t-1,0{var n=e||parseInt(s.getKookitConfig("count")||"0");let t=document.getElementById("page-area");if(t){e=t.getElementsByTagName("iframe")[0];if(e){let t=e.contentDocument;if(t)if(n){let e=Array.from(t.body.querySelectorAll("img"))[n];"scroll"!==i?t.body.scrollTo(n&&e?e.getBoundingClientRect().left:0,0):r.scrollTo(0,n&&e?e.getBoundingClientRect().top:0)}else("scroll"!==i?t.body:r).scrollTo(0,0)}}};var it={exports:{}},tn=it.exports=function(){function t(r){function i(e){for(var t=0,r=n.length;t127){if(a>191&&a<224){if(t>=e.length)throw"UTF-8 decode: incomplete 2-byte sequence";a=(31&a)<<6|63&e[t]}else if(a>223&&a<240){if(t+1>=e.length)throw"UTF-8 decode: incomplete 3-byte sequence";a=(15&a)<<12|(63&e[t])<<6|63&e[++t]}else{if(!(a>239&&a<248))throw"UTF-8 decode: unknown multibyte start 0x"+a.toString(16)+" at index "+(t-1);if(t+2>=e.length)throw"UTF-8 decode: incomplete 4-byte sequence";a=(7&a)<<18|(63&e[t])<<12|(63&e[++t])<<6|63&e[++t]}++t}if(a<=65535)r+=String.fromCharCode(a);else{if(!(a<=1114111))throw"UTF-8 decode: code point 0x"+a.toString(16)+" exceeds UTF-16 reach";a-=65536,r+=String.fromCharCode(a>>10|55296),r+=String.fromCharCode(1023&a|56320)}}return r}function PaxHeader(e){this._fields=e}function TarFile(){}function UntarStream(e){this._bufferView=new DataView(e),this._position=0}function UntarFileStream(e){this._stream=new UntarStream(e),this._globalPaxHeader=null}if(UntarWorker.prototype={onmessage:function(e){try{if("extract"!==e.data.type)throw new Error("Unknown message type: "+e.data.type);this.untarBuffer(e.data.buffer)}catch(r){this.postError(r)}},postError:function(e){this.postMessage({type:"error",data:{message:e.message}})},postLog:function(e,r){this.postMessage({type:"log",data:{level:e,msg:r}})},untarBuffer:function(e){try{for(var r=new UntarFileStream(e);r.hasNext();){var t=r.next();this.postMessage({type:"extract",data:t},[t.buffer])}this.postMessage({type:"complete"})}catch(a){this.postError(a)}},postMessage:function(e,r){self.postMessage(e,r)}},"undefined"!=typeof self){var worker=new UntarWorker;self.onmessage=function(e){worker.onmessage(e)}}PaxHeader.parse=function(e){for(var r=new Uint8Array(e),t=[];r.length>0;){var a=parseInt(decodeUTF8(r.subarray(0,r.indexOf(32)))),n=decodeUTF8(r.subarray(0,a)),i=n.match(/^\\d+ ([^=]+)=(.*)\\n$/);if(null===i)throw new Error("Invalid PAX header data format.");var s=i[1],o=i[2];0===o.length?o=null:null!==o.match(/^\\d+$/)&&(o=parseInt(o));var f={name:s,value:o};t.push(f),r=r.subarray(a)}return new PaxHeader(t)},PaxHeader.prototype={applyHeader:function(e){this._fields.forEach(function(r){var t=r.name,a=r.value;"path"===t?(t="name",void 0!==e.prefix&&delete e.prefix):"linkpath"===t&&(t="linkname"),null===a?delete e[t]:e[t]=a})}},UntarStream.prototype={readString:function(e){for(var r=1,t=e*r,a=[],n=0;n-1&&(r.version=e.readString(2),r.uname=e.readString(32),r.gname=e.readString(32),r.devmajor=parseInt(e.readString(8)),r.devminor=parseInt(e.readString(8)),r.namePrefix=e.readString(155),r.namePrefix.length>0&&(r.name=r.namePrefix+"/"+r.name)),e.position(i),r.type){case"0":case"":r.buffer=e.readBuffer(r.size);break;case"1":break;case"2":break;case"3":break;case"4":break;case"5":break;case"6":break;case"7":break;case"g":t=!0,this._globalPaxHeader=PaxHeader.parse(e.readBuffer(r.size));break;case"x":t=!0,a=PaxHeader.parse(e.readBuffer(r.size))}void 0===r.buffer&&(r.buffer=new ArrayBuffer(0));var s=i+r.size;return r.size%512!==0&&(s+=512-r.size%512),e.position(s),t&&(r=this._readNextFile()),null!==this._globalPaxHeader&&this._globalPaxHeader.applyHeader(r),null!==a&&a.applyHeader(r),r}};']));return e}();const rn=e=>e?.trim()?.replace(/\s{2,}/g," "),nn=e=>rn(e?.textContent),an={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},on={XML:"application/xml",XHTML:"application/xhtml+xml"},sn={strong:["strong","self"],emphasis:["em","self"],style:["span","self"],a:"anchor",strikethrough:["s","self"],sub:["sub","self"],sup:["sup","self"],code:["code","self"],image:"image"};const ln={epigraph:["blockquote"],subtitle:["h2",sn],"text-author":["p",sn],date:["p",sn],stanza:"stanza"},cn={title:["header",{p:["h1",sn],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",sn],poem:["blockquote",ln],subtitle:["h2",sn],cite:["blockquote","self"],"empty-line":["br"],table:["table",{tr:["tr",["align"]],th:["th",["colspan","rowspan","align","valign"]],td:["td",["colspan","rowspan","align","valign"]]}],"text-author":["p",sn]};ln.epigraph.push(cn);const un={image:"image",title:["section",{p:["h1",sn],"empty-line":["br"]}],epigraph:["section",cn],section:["section",cn]},hn=e=>{const t=e.getAttributeNS(an.XLINK,"href");var[,r]=t.split("#");const i=e.getRootNode().getElementById(r);return i?`data:${i.getAttribute("content-type")};base64,${i.textContent}`:t};class fn{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(an.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",hn(e)),t}anchor(e){const t=this.convert(e,{a:["a",sn]});return t.setAttribute("href",e.getAttributeNS(an.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(an.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",sn],"empty-line":["br"]}],subtitle:["p",sn]}]});for(const r of e.children)"v"===r.nodeName&&(t.append(this.doc.createTextNode(r.textContent)),t.append(this.doc.createElement("br")));return t}convert(e,t){if(3===e.nodeType)return this.doc.createTextNode(e.textContent);if(4===e.nodeType)return this.doc.createCDATASection(e.textContent);if(8===e.nodeType)return this.doc.createComment(e.textContent);var r=t?.[e.nodeName];if(!r)return null;if("string"==typeof r)return this[r](e);var[i,r]=r;const n=this.doc.createElement(i);if(e.id&&(n.id=e.id),n.classList.add(e.nodeName),Array.isArray(r))for(const l of r)n.setAttribute(l,e.getAttribute(l));var a="self"===r?t:Array.isArray(r)?null:r;let o=e.firstChild;for(;o;){var s=this.convert(o,a);s&&n.append(s),o=o.nextSibling}return n}}const dn=URL.createObjectURL(new Blob([` + }`)),await this.replaceResources(t);var n=this.serializer.serializeToString(t),n=URL.createObjectURL(new Blob([n],{type:this.#type}));return this.#cache.set(e,n),n}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],r=Number(t);return{index:this.#sections.findIndex(e=>e.end>r),anchor:e=>e.getElementById(`filepos${t}`)}}splitTOCHref(e){e=e.match(/filepos:(.*)/)[1];const t=Number(e);return[this.#sections.findIndex(e=>e.end>t),`filepos${e}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}}const Jn=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,Yn=/kindle:pos:fid:(\w+):off:(\w+)/,Qn=e=>{var[t,e]=e.match(Yn).slice(1);return{fid:parseInt(t,32),off:parseInt(e,32)}},ei=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,ti=e=>{var t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(t){var[,e,t]=t;return`[${e}="${CSS.escape(t)}"]`}};class ri{parser=new DOMParser;#cache=new Map;#fragmentOffsets=new Map;#fragmentSelectors=new Map;#tables={};#sections;#fullRawLength;#rawHead=new Uint8Array;#rawTail=new Uint8Array;#lastLoadedHead=-1;#lastLoadedTail=-1;#checkType=!0;#type=vn.XHTML;constructor(e){this.mobi=e}async init(){const e=this.mobi.loadRecord.bind(this.mobi);var t=this.mobi.headers["kf8"];try{const l=await e(t.fdst);var r=jn(En,l);if("FDST"!==r.magic)throw new Error("Missing FDST record");var n=Array.from({length:r.numEntries},(e,t)=>12+8*t).map(e=>[$n(l.slice(e,e+4)),$n(l.slice(e+4,e+8))]);this.#tables.fdstTable=n,this.#fullRawLength=n[n.length-1][1]}catch{}const i=(await qn(t.skel,e)).table.map(({name:e,tagMap:t},r)=>({index:r,name:e,numFrag:t[1][0],offset:t[6][0],length:t[6][1]})),a=await qn(t.frag,e),o=a.table.map(({name:e,tagMap:t})=>({insertOffset:parseInt(e),selector:a.cncx[t[2][0]],index:t[4][0],offset:t[6][0],length:t[6][1]}));this.#tables.skelTable=i,this.#tables.fragTable=o,this.#sections=i.reduce((e,t)=>{var r=e[e.length-1],n=r?.fragEnd??0,i=n+t.numFrag;const a=o.slice(n,i);n=t.length+a.map(e=>e.length).reduce((e,t)=>e+t);return e.concat({skel:t,frags:a,fragEnd:i,length:n,totalLength:(r?.totalLength??0)+n})},[]),this.#sections.unshift({frags:[]}),this.sections=this.#sections.map((e,t)=>e.frags.length?{id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.length}:{linear:"no"});try{const c=await this.mobi.getNCX(),u=({label:e,pos:t,children:r})=>{var[n,i]=t,t=ei(n,i);const a=this.#fragmentOffsets.get(n);return a?a.push(i):this.#fragmentOffsets.set(n,[i]),{label:bn(e),href:t,subitems:r?.map(u)}};this.toc=c?.map(u),this.landmarks=await this.getGuide()}catch(e){console.warn(e)}const s=this.mobi.headers["exth"];return this.dir=s.pageProgressionDirection,this.rendition={layout:"true"===s.fixedLayout?"pre-paginated":"reflowable",viewport:Object.fromEntries(s.originalResolution?.split("x")?.slice(0,2)?.map((e,t)=>[t?"height":"width",e])??[])},this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getResourcesByMagic(t){const r={};var n=this.mobi.headers.kf8.resourceStart,i=this.mobi.pdb.numRecords;for(let e=n;ee===o);a&&(r[a]=e)}catch{}return r}async getGuide(){var e=this.mobi.headers.kf8.guide;if(e<4294967295){var t=this.mobi.loadRecord.bind(this.mobi);const{table:r,cncx:n}=await qn(e,t);return r.map(({name:e,tagMap:t})=>({label:n[t[1][0]]??"",type:e?.split(/\s/),href:ei(t[6]?.[0]??t[3]?.[0])}))}}async loadResourceBlob(e){var{resourceType:t,id:r,type:e}=(e=>{var[t,r,e]=e.match(Jn).slice(1);return{resourceType:t,id:parseInt(r,32),type:e}})(e),r="flow"===t?await this.loadFlow(r):await this.mobi.loadResource(r-1),r=[vn.XHTML,vn.HTML,vn.CSS,vn.SVG].includes(e)?await this.replaceResources(this.mobi.decode(r)):r;return new Blob([r],{type:e})}async loadResource(e){if(this.#cache.has(e))return this.#cache.get(e);var t=await this.loadResourceBlob(e),t=URL.createObjectURL(t);return this.#cache.set(e,t),t}replaceResources(e){return(async(e,t,r)=>{const n=[];e.replace(t,(...e)=>(n.push(e),null));const i=[];for(const a of n)i.push(await r(...a));return e.replace(t,()=>i.shift())})(e,new RegExp(Jn,"g"),this.loadResource.bind(this))}async loadRaw(e,t){var r=t-this.#rawHead.length,n=null==this.#fullRawLength?1/0:this.#fullRawLength-this.#rawTail.length-e;if(r<0||re;){var a=this.mobi.headers.palmdoc.numTextRecords-1-++this.#lastLoadedTail,a=await this.mobi.loadText(a);this.#rawTail=Nn(a,this.#rawTail)}n=this.#fullRawLength-this.#rawTail.length;return this.#rawTail.slice(e-n,t-n)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#tables.fdstTable[e])}async loadText(e){var{skel:t,frags:r,length:e}=e;const n=await this.loadRaw(t.offset,t.offset+e);let i=n.slice(0,t.length);for(const c of r){var a=c.insertOffset-t.offset,o=t.length+c.offset,s=n.slice(o,o+c.length);i=Rn(i.slice(0,a),s,i.slice(a));a=this.#fragmentOffsets.get(c.index);if(a)for(const u of a){var l=this.mobi.decode(s).slice(u),l=ti(l);this.#setFragmentSelector(c.index,u,l)}}return this.mobi.decode(i)}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);var t=await this.loadText(e);this.#checkType&&this.parser.parseFromString(t,this.#type).querySelector("parsererror")&&(this.#type=vn.HTML),this.#checkType&&(this.#checkType=!1);t=await this.replaceResources(t),t=URL.createObjectURL(new Blob([t],{type:this.#type}));return this.#cache.set(e,t),t}getIndexByFID(t){return this.#sections.findIndex(e=>e.frags.some(e=>e.index===t))}#setFragmentSelector(e,t,r){const n=this.#fragmentSelectors.get(e);if(n)n.set(t,r);else{const n=new Map;this.#fragmentSelectors.set(e,n),n.set(t,r)}}async resolveHref(e){const{fid:t,off:r}=Qn(e);var n=this.getIndexByFID(t);if(!(n<0)){const a=this.#fragmentSelectors.get(t)?.get(r);if(a)return{index:n,anchor:e=>e.querySelector(a)};const{skel:o,frags:s}=this.#sections[n];var i=s.find(e=>e.index===t),e=o.offset+o.length+i.offset,i=await this.loadRaw(e,e+i.length),i=this.mobi.decode(i).slice(r);const l=ti(i);this.#setFragmentSelector(t,r,l);return{index:n,anchor:e=>e.querySelector(l)}}}splitTOCHref(e){e=Qn(e);return[this.getIndexByFID(e.fid),e]}getTOCFragment(e,{fid:t,off:r}){r=this.#fragmentSelectors.get(t)?.get(r);return e.querySelector(r)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}}const ni={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"};class ii{constructor(e,t,r,n,i){this.fileNameList=e,this.zip=t,this.bookStr="",this.format=i,this.bookDoc=null,this.mode=r,this.chapterList=[],console.log(this.fileNameList),this.extension=this.fileNameList[0].split(".").reverse()[0],this.element=n,this.getBookStr()}getBookStr(){let r=document.createElement("div");var n="single"===this.mode?1:2,e=Math.floor(this.element.clientWidth/12),i=e%2==0?e:e-1;for(let t=0;tf(this,void 0,void 0,function*(){var e=new Image;e.onload=function(){t(e.height/e.width)},e.src=yield this.getFirstImage()}))}getFirstImage(){return f(this,void 0,void 0,function*(){this.extension=this.fileNameList[0].split(".").reverse()[0];let e=new ArrayBuffer(0);return"CBR"===this.format?e=this.zip.decompress(this.fileNameList[0]):"CBT"===this.format?e=this.zip[rr.findLastIndex(this.zip,{name:this.fileNameList[0]})].buffer:"CBZ"===this.format&&(e=yield this.zip.file(this.fileNameList[0]).async("arraybuffer")),"data:"+ni[this.extension.toLowerCase()]+";base64,"+this.base64ArrayBuffer(e)})}renderComic(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;e&&(e.body.innerHTML=this.bookDoc.outerHTML)}}}renderImage(i){return new Promise((n,e)=>f(this,void 0,void 0,function*(){console.log(this.fileNameList[0]),this.extension=this.fileNameList[0].split(".").reverse()[0];let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){let t=r.contentDocument;if(t)if(t.getElementById(i+"")&&!t.getElementById(i+"").src){let e;e="cbr"===this.format?this.zip.decompress(this.fileNameList[i]):"cbt"===this.format?this.zip[rr.findLastIndex(this.zip,{name:this.fileNameList[i]})].buffer:yield this.zip.file(this.fileNameList[i]).async("arraybuffer"),t.getElementById(i+"")&&(t.getElementById(i+"").src="data:"+ni[this.extension.toLowerCase()]+";base64,"+this.base64ArrayBuffer(e)),n()}else n()}}}))}base64ArrayBuffer(e){for(var t,r="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=new Uint8Array(e),a=i.byteLength,e=a%3,o=a-e,s=0;s>18]+n[(258048&t)>>12]+n[(4032&t)>>6]+n[63&t];return 1==e?r+=n[(252&(t=i[o]))>>2]+n[(3&t)<<4]+"==":2==e&&(r+=n[(64512&(t=i[o]<<8|i[1+o]))>>10]+n[(1008&t)>>4]+n[(15&t)<<2]+"="),r}getMetadata(){return new Promise((e,t)=>f(this,void 0,void 0,function*(){e({cover:yield this.getFirstImage()})}))}}const ai=(r,n,i)=>f(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;e&&(t=(t=Math.floor(r.clientWidth/12))%2==0?t:t-1,0{var i=e||parseInt(l.getKookitConfig("count")||"0");let t=document.getElementById("page-area");if(t){e=t.getElementsByTagName("iframe")[0];if(e){let t=e.contentDocument;if(t)if(i){let e=Array.from(t.body.querySelectorAll("img"))[i];"scroll"!==n?t.body.scrollTo(i&&e?e.getBoundingClientRect().left:0,0):r.scrollTo(0,i&&e?e.getBoundingClientRect().top:0)}else("scroll"!==n?t.body:r).scrollTo(0,0)}}};var st={exports:{}},si=st.exports=function(){function t(r){function n(e){for(var t=0,r=i.length;t127){if(a>191&&a<224){if(t>=e.length)throw"UTF-8 decode: incomplete 2-byte sequence";a=(31&a)<<6|63&e[t]}else if(a>223&&a<240){if(t+1>=e.length)throw"UTF-8 decode: incomplete 3-byte sequence";a=(15&a)<<12|(63&e[t])<<6|63&e[++t]}else{if(!(a>239&&a<248))throw"UTF-8 decode: unknown multibyte start 0x"+a.toString(16)+" at index "+(t-1);if(t+2>=e.length)throw"UTF-8 decode: incomplete 4-byte sequence";a=(7&a)<<18|(63&e[t])<<12|(63&e[++t])<<6|63&e[++t]}++t}if(a<=65535)r+=String.fromCharCode(a);else{if(!(a<=1114111))throw"UTF-8 decode: code point 0x"+a.toString(16)+" exceeds UTF-16 reach";a-=65536,r+=String.fromCharCode(a>>10|55296),r+=String.fromCharCode(1023&a|56320)}}return r}function PaxHeader(e){this._fields=e}function TarFile(){}function UntarStream(e){this._bufferView=new DataView(e),this._position=0}function UntarFileStream(e){this._stream=new UntarStream(e),this._globalPaxHeader=null}if(UntarWorker.prototype={onmessage:function(e){try{if("extract"!==e.data.type)throw new Error("Unknown message type: "+e.data.type);this.untarBuffer(e.data.buffer)}catch(r){this.postError(r)}},postError:function(e){this.postMessage({type:"error",data:{message:e.message}})},postLog:function(e,r){this.postMessage({type:"log",data:{level:e,msg:r}})},untarBuffer:function(e){try{for(var r=new UntarFileStream(e);r.hasNext();){var t=r.next();this.postMessage({type:"extract",data:t},[t.buffer])}this.postMessage({type:"complete"})}catch(a){this.postError(a)}},postMessage:function(e,r){self.postMessage(e,r)}},"undefined"!=typeof self){var worker=new UntarWorker;self.onmessage=function(e){worker.onmessage(e)}}PaxHeader.parse=function(e){for(var r=new Uint8Array(e),t=[];r.length>0;){var a=parseInt(decodeUTF8(r.subarray(0,r.indexOf(32)))),n=decodeUTF8(r.subarray(0,a)),i=n.match(/^\\d+ ([^=]+)=(.*)\\n$/);if(null===i)throw new Error("Invalid PAX header data format.");var s=i[1],o=i[2];0===o.length?o=null:null!==o.match(/^\\d+$/)&&(o=parseInt(o));var f={name:s,value:o};t.push(f),r=r.subarray(a)}return new PaxHeader(t)},PaxHeader.prototype={applyHeader:function(e){this._fields.forEach(function(r){var t=r.name,a=r.value;"path"===t?(t="name",void 0!==e.prefix&&delete e.prefix):"linkpath"===t&&(t="linkname"),null===a?delete e[t]:e[t]=a})}},UntarStream.prototype={readString:function(e){for(var r=1,t=e*r,a=[],n=0;n-1&&(r.version=e.readString(2),r.uname=e.readString(32),r.gname=e.readString(32),r.devmajor=parseInt(e.readString(8)),r.devminor=parseInt(e.readString(8)),r.namePrefix=e.readString(155),r.namePrefix.length>0&&(r.name=r.namePrefix+"/"+r.name)),e.position(i),r.type){case"0":case"":r.buffer=e.readBuffer(r.size);break;case"1":break;case"2":break;case"3":break;case"4":break;case"5":break;case"6":break;case"7":break;case"g":t=!0,this._globalPaxHeader=PaxHeader.parse(e.readBuffer(r.size));break;case"x":t=!0,a=PaxHeader.parse(e.readBuffer(r.size))}void 0===r.buffer&&(r.buffer=new ArrayBuffer(0));var s=i+r.size;return r.size%512!==0&&(s+=512-r.size%512),e.position(s),t&&(r=this._readNextFile()),null!==this._globalPaxHeader&&this._globalPaxHeader.applyHeader(r),null!==a&&a.applyHeader(r),r}};']));return e}();const li=e=>e?.trim()?.replace(/\s{2,}/g," "),ci=e=>li(e?.textContent),ui={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},hi={XML:"application/xml",XHTML:"application/xhtml+xml"},fi={strong:["strong","self"],emphasis:["em","self"],style:["span","self"],a:"anchor",strikethrough:["s","self"],sub:["sub","self"],sup:["sup","self"],code:["code","self"],image:"image"};const di={epigraph:["blockquote"],subtitle:["h2",fi],"text-author":["p",fi],date:["p",fi],stanza:"stanza"},pi={title:["header",{p:["h1",fi],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",fi],poem:["blockquote",di],subtitle:["h2",fi],cite:["blockquote","self"],"empty-line":["br"],table:["table",{tr:["tr",["align"]],th:["th",["colspan","rowspan","align","valign"]],td:["td",["colspan","rowspan","align","valign"]]}],"text-author":["p",fi]};di.epigraph.push(pi);const mi={image:"image",title:["section",{p:["h1",fi],"empty-line":["br"]}],epigraph:["section",pi],section:["section",pi]},gi=e=>{const t=e.getAttributeNS(ui.XLINK,"href");var[,r]=t.split("#");const n=e.getRootNode().getElementById(r);return n?`data:${n.getAttribute("content-type")};base64,${n.textContent}`:t};class yi{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(ui.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",gi(e)),t}anchor(e){const t=this.convert(e,{a:["a",fi]});return t.setAttribute("href",e.getAttributeNS(ui.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(ui.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",fi],"empty-line":["br"]}],subtitle:["p",fi]}]});for(const r of e.children)"v"===r.nodeName&&(t.append(this.doc.createTextNode(r.textContent)),t.append(this.doc.createElement("br")));return t}convert(e,t){if(3===e.nodeType)return this.doc.createTextNode(e.textContent);if(4===e.nodeType)return this.doc.createCDATASection(e.textContent);if(8===e.nodeType)return this.doc.createComment(e.textContent);var r=t?.[e.nodeName];if(!r)return null;if("string"==typeof r)return this[r](e);var[n,r]=r;const i=this.doc.createElement(n);if(e.id&&(i.id=e.id),i.classList.add(e.nodeName),Array.isArray(r))for(const l of r)i.setAttribute(l,e.getAttribute(l));var a="self"===r?t:Array.isArray(r)?null:r;let o=e.firstChild;for(;o;){var s=this.convert(o,a);s&&i.append(s),o=o.nextSibling}return i}}const bi=URL.createObjectURL(new Blob([` @namespace epub "http://www.idpf.org/2007/ops"; body > img, section > img { display: block; @@ -49,8 +49,8 @@ a[epub|type~="noteref"] { body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph { margin: 3em 0; } -`],{type:"text/css"})),pn="data-foliate-id",mn=async e=>{const t={},r=await(async e=>{var t=await e.arrayBuffer();const r=new TextDecoder("utf-8").decode(t),i=new DOMParser;e=i.parseFromString(r,on.XML);const n=e.xmlEncoding||r.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1];if(n&&"utf-8"!==n.toLowerCase()){const r=new TextDecoder(n).decode(t);return i.parseFromString(r,on.XML)}return e})(e),i=new fn(r),n=e=>r.querySelector(e);var a=e=>[...r.querySelectorAll(e)],o=e=>{var t=nn(e.querySelector("nickname"));if(t)return t;const r=nn(e.querySelector("first-name")),i=nn(e.querySelector("middle-name")),n=nn(e.querySelector("last-name"));return{name:[r,i,n].filter(e=>e).join(" "),sortAs:n?[n,[r,i].filter(e=>e).join(" ")].join(", "):null}},s=e=>e?.getAttribute("value")??nn(e),e=n("title-info annotation");t.metadata={title:nn(n("title-info book-title")),identifier:nn(n("document-info id")),language:nn(n("title-info lang")),author:a("title-info author").map(o),translator:a("title-info translator").map(o),producer:a("document-info author").map(o).concat(a("document-info program-used").map(nn)),publisher:nn(n("publish-info publisher")),published:s(n("title-info date")),modified:s(n("document-info date")),description:e?i.convert(e,{annotation:["div",cn]}).innerHTML:null,subject:a("title-info genre").map(nn)},t.getCover=()=>fetch(hn(n("coverpage image"))).then(e=>e.blob());const l=Array.from(r.querySelectorAll("body"),e=>{e=i.convert(e,{body:["body",un]});return[Array.from(e.children,e=>{var t=[e,...e.querySelectorAll("[id]")].map(e=>e.id);return{el:e,ids:t}}),e]}),c=l[0][0].map(({el:e,ids:t})=>{return{ids:t,titles:Array.from(e.querySelectorAll(":scope > section > .title"),(e,t)=>(e.setAttribute(pn,t),{title:nn(e),index:t})),el:e}}).concat(l.slice(1).map(([e,t])=>{e=e.map(e=>e.ids).flat();return t.classList.add("notesBodyType"),{ids:e,el:t,linear:"no"}})).map(({ids:e,titles:t,el:r,linear:i})=>{const n=(a=r.outerHTML,` +`],{type:"text/css"})),vi="data-foliate-id",wi=async e=>{const t={},r=await(async e=>{var t=await e.arrayBuffer();const r=new TextDecoder("utf-8").decode(t),n=new DOMParser;e=n.parseFromString(r,hi.XML);const i=e.xmlEncoding||r.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1];if(i&&"utf-8"!==i.toLowerCase()){const r=new TextDecoder(i).decode(t);return n.parseFromString(r,hi.XML)}return e})(e),n=new yi(r),i=e=>r.querySelector(e);var a=e=>[...r.querySelectorAll(e)],o=e=>{var t=ci(e.querySelector("nickname"));if(t)return t;const r=ci(e.querySelector("first-name")),n=ci(e.querySelector("middle-name")),i=ci(e.querySelector("last-name"));return{name:[r,n,i].filter(e=>e).join(" "),sortAs:i?[i,[r,n].filter(e=>e).join(" ")].join(", "):null}},s=e=>e?.getAttribute("value")??ci(e),e=i("title-info annotation");t.metadata={title:ci(i("title-info book-title")),identifier:ci(i("document-info id")),language:ci(i("title-info lang")),author:a("title-info author").map(o),translator:a("title-info translator").map(o),producer:a("document-info author").map(o).concat(a("document-info program-used").map(ci)),publisher:ci(i("publish-info publisher")),published:s(i("title-info date")),modified:s(i("document-info date")),description:e?n.convert(e,{annotation:["div",pi]}).innerHTML:null,subject:a("title-info genre").map(ci)},t.getCover=()=>fetch(gi(i("coverpage image"))).then(e=>e.blob());const l=Array.from(r.querySelectorAll("body"),e=>{e=n.convert(e,{body:["body",mi]});return[Array.from(e.children,e=>{var t=[e,...e.querySelectorAll("[id]")].map(e=>e.id);return{el:e,ids:t}}),e]}),c=l[0][0].map(({el:e,ids:t})=>{return{ids:t,titles:Array.from(e.querySelectorAll(":scope > section > .title"),(e,t)=>(e.setAttribute(vi,t),{title:ci(e),index:t})),el:e}}).concat(l.slice(1).map(([e,t])=>{e=e.map(e=>e.ids).flat();return t.classList.add("notesBodyType"),{ids:e,el:t,linear:"no"}})).map(({ids:e,titles:t,el:r,linear:n})=>{const i=(a=r.outerHTML,` - + ${a} -`);var a=new Blob([n],{type:on.XHTML});const o=URL.createObjectURL(a);return{ids:e,title:rn(r.querySelector(".title, .subtitle, p")?.textContent??(r.classList.contains("title")?r.textContent:"")),titles:t,load:()=>o,createDocument:()=>(new DOMParser).parseFromString(n,on.XHTML),size:a.size-Array.from(r.querySelectorAll("[src]"),e=>e.getAttribute("src")?.length??0).reduce((e,t)=>e+t,0),linear:i}}),u=new Map;return t.sections=c.map((e,t)=>{var{ids:r,load:i,createDocument:n,size:a,linear:e}=e;for(const o of r)o&&u.set(o,t);return{id:t,load:i,createDocument:n,size:a,linear:e}}),t.toc=c.map(({title:e,titles:t},r)=>{const i=r.toString();return{label:e,href:i,subitems:t?.length?t.map(({title:e,index:t})=>({label:e,href:`${i}#${t}`})):null}}).filter(e=>e),t.resolveHref=e=>{const[t,r]=e.split("#");return t?{index:Number(t),anchor:e=>e.querySelector(`[${pn}="${r}"]`)}:{index:u.get(r),anchor:e=>e.getElementById(r)}},t.splitTOCHref=e=>e?.split("#")?.map(e=>Number(e))??[],t.getTOCFragment=(e,t)=>e.querySelector(`[${pn}="${t}"]`),t};window.e=window.eval,window.a=window.atob,e.ComicRender=class extends gr{constructor(e,t,r,i){super(),this.isSliding=i||!1,this.mode=t,this.dataSource=[],this.zip="",this.format=r,this.comicBuffer=e,this.element="",this.parser=null,this.chapterList=[],this.largestId=parseInt(s.getKookitConfig("count")||"0")}renderTo(l,c=0){return new Promise((s,e)=>u(this,void 0,void 0,function*(){(yield m())?(this.element=l,er(l),yield this.handleArchive(),yield u(this,void 0,void 0,function*(){this.parser=new Yi(this.dataSource,this.zip,this.mode,this.element,this.format),this.chapterList=this.parser.getChapter(),this.parser.renderComic(),yield this.renderImage(c);let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){let e=r.contentDocument;if(e&&e.getElementById(c+"")){var i=yield this.parser.getImgRatio(),n=e.getElementById(c+"").clientWidth*i;let t=e.getElementsByTagName("img");var a,r=Math.floor(this.element.clientWidth/12),o=r%2==0?r:r-1;for(let e=0;ethis.element.clientHeight?(t[e].style.height=this.element.clientHeight+"px",t[e].style.width=this.element.clientHeight/i+"px",t[e].style.paddingLeft=(this.element.clientWidth-("single"===this.mode?0:o))/2/a-this.element.clientHeight/i/2+"px"):(t[e].style.height=n+"px",t[e].style.marginTop=this.element.clientHeight/2-n/2+"px"));tr(l,this.mode),Qt(l,this.mode),this.trigger("rendered"),s()}}}})):s()}))}handleArchive(){return u(this,void 0,void 0,function*(){var e;"CBZ"===this.format?(this.zip=new window.JSZip,e=yield this.zip.loadAsync(this.comicBuffer),console.log(e),this.dataSource=Object.keys(e.files).sort(),console.log(this.dataSource)):"CBT"===this.format?(this.zip=yield tn(this.comicBuffer),this.dataSource=this.zip.map(e=>e.name)):"CBR"===this.format&&(this.zip=new window.Unrar(this.comicBuffer),this.dataSource=this.zip.getEntries().map(e=>e.name))})}flatChapter(e){return e}getProgress(){return{totalPage:this.chapterList.length,currentPage:parseInt(s.getKookitConfig("count")||"0")}}getPageSize(){return{width:this.element.clientWidth,height:this.element.clientHeight}}renderImage(e){return u(this,void 0,void 0,function*(){this.parser&&(yield this.parser.renderImage(e-3),yield this.parser.renderImage(e-2),yield this.parser.renderImage(e-1),yield this.parser.renderImage(e),yield this.parser.renderImage(e+1),yield this.parser.renderImage(e+2),yield this.parser.renderImage(e+3))})}getChapter(){return this.chapterList}goToPosition(e){var e=JSON.parse(e)["id"];en(this.element,this.mode,e),this.record()}goToChapter(e){return u(this,void 0,void 0,function*(){en(this.element,this.mode,this.dataSource.indexOf(e)+""),yield this.renderImage(this.dataSource.indexOf(e))})}record(){return u(this,void 0,void 0,function*(){dr(this.element,this.mode);var e=parseInt(s.getKookitConfig("count")||"0");this.parser&&(yield this.parser.renderImage(e-3),yield this.parser.renderImage(e-2),yield this.parser.renderImage(e-1),yield this.parser.renderImage(e),yield this.parser.renderImage(e+1),yield this.parser.renderImage(e+2),yield this.parser.renderImage(e+3))})}removeContent(){this.element.innerHTML=""}prev(){return u(this,void 0,void 0,function*(){var e=parseInt(s.getKookitConfig("count")||"0");this.parser&&(yield this.parser.renderImage(e),yield this.parser.renderImage(e-1),yield this.parser.renderImage(e-2),yield this.parser.renderImage(e-3),yield this.parser.renderImage(e-4),Qi(this.element,1,this.isSliding),dr(this.element,this.mode))})}next(){return u(this,void 0,void 0,function*(){var e=parseInt(s.getKookitConfig("count")||"0");this.parser&&(yield this.parser.renderImage(e),yield this.parser.renderImage(e+1),yield this.parser.renderImage(e+2),yield this.parser.renderImage(e+3),yield this.parser.renderImage(e+4),Qi(this.element,-1,this.isSliding),dr(this.element,this.mode))})}getPosition(){return{text:s.getKookitConfig("text"),chapterTitle:s.getKookitConfig("chapterTitle"),chapterDocIndex:s.getKookitConfig("chapterDocIndex"),count:s.getKookitConfig("count"),percentage:s.getKookitConfig("percentage")}}getMetadata(){return u(this,void 0,void 0,function*(){return yield this.handleArchive(),this.parser=new Yi(this.dataSource,this.zip,this.mode,this.element,this.format),yield this.parser.getMetadata()})}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"))}}}},e.EpubRender=class extends yr{constructor(e,t,r){super(t,r),this.epubBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.isSliding=r||!1}renderTo(i){return new Promise((r,e)=>u(this,void 0,void 0,function*(){if(yield m()){var t=new Blob([this.epubBuffer]),t=new File([t],"book",{lastModified:(new Date).getTime(),type:t.type}),t=yield this.makeZipLoader(t);this.book=yield new hi(t).init();let e=new br(this.book);this.element=i,console.log(this.book),this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),console.log(this.chapterList),console.log(this.chapterDocList),er(i),tr(i,this.mode),this.trigger("rendered"),r()}else r()}))}makeZipLoader(c){return u(this,void 0,void 0,function*(){const{ZipReader:e,BlobReader:t,TextWriter:r,BlobWriter:i}=window.zip;window.zip.configure({useWebWorkers:!1});const n=new e(new t(c)),a=yield n.getEntries(),o=new Map(a.map(e=>[e.filename,e]));var s=r=>(e,...t)=>o.has(e)?r(o.get(e),...t):null,l=s(e=>e.getData(new r)),s=s((e,t)=>e.getData(new i(t)));return{entries:a,loadText:l,loadBlob:s,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.uncompressedSize)&&void 0!==e?e:0}}})}getMetadata(){return u(this,void 0,void 0,function*(){var e=new Blob([this.epubBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type}),e=yield this.makeZipLoader(e);this.book=yield new hi(e).init();let t=new br(this.book);return yield t.getMetadata()})}},e.Fb2Render=class extends yr{constructor(e,t,r){super(t,r),this.fb2Buffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.isSliding=r||!1}renderTo(i){return new Promise((r,e)=>u(this,void 0,void 0,function*(){if(yield m()){var t=new Blob([this.fb2Buffer]);this.book=yield mn(t);let e=new br(this.book);this.element=i,this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),er(i),tr(i,this.mode),this.trigger("rendered"),r()}else r()}))}getMetadata(){return u(this,void 0,void 0,function*(){var e=new Blob([this.fb2Buffer]);this.book=yield mn(e);let t=new br(this.book);return yield t.getMetadata()})}},e.MobiRender=class extends yr{constructor(e,t,r){super(t,r),this.mobiBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.isSliding=r||!1}renderTo(i){return new Promise((r,e)=>u(this,void 0,void 0,function*(){if(yield m()){var t=new Blob([this.mobiBuffer]),t=new File([t],"book",{lastModified:(new Date).getTime(),type:t.type});if(yield(async e=>{return"BOOKMOBI"===Mi(await e.slice(60,68).arrayBuffer())})(t)){this.book=yield new Pi({unzlib:window.fflate.unzlibSync}).open(t);let e=new br(this.book);this.element=i,this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),this.metadata=yield e.getMetadata(),console.log(this.chapterList),console.log(this.chapterDocList),er(i),tr(i,this.mode),this.trigger("rendered"),r()}}else r()}))}getMetadata(){return u(this,void 0,void 0,function*(){var e=new Blob([this.mobiBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});this.book=yield new Pi({unzlib:window.fflate.unzlibSync}).open(e);let t=new br(this.book);return yield t.getMetadata()})}},e.StrRender=class extends yr{constructor(e,t,r){super(t,r),this.bookStr=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element="",this.isSliding=r||!1}renderTo(r){return new Promise((t,e)=>u(this,void 0,void 0,function*(){if(yield m()){this.element=r;let e=new ir(this.bookStr);e.isContainChapter()||(this.bookStr=p(e.getDocText()),e=new ir(this.bookStr)),this.chapterList=e.getChapter(),this.chapterDocList=e.getChapterDoc(),er(r),tr(r,this.mode),this.trigger("rendered"),t()}else t()}))}},e.TxtRender=class extends yr{constructor(e,t,r,i){super(t,i),this.txtBuffer=e,this.encoding=r,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.bookStr="",this.element="",this.isSliding=i||!1}renderTo(i){return new Promise((r,e)=>u(this,void 0,void 0,function*(){if(yield m()){var t=new TextDecoder(this.encoding).decode(this.txtBuffer),t=p(t);this.bookStr=t,this.element=i;let e=new ir(this.bookStr);this.chapterList=e.getChapter(),this.chapterDocList=e.getChapterDoc(),er(i),tr(i,this.mode),this.trigger("rendered"),r()}else r()}))}},Object.defineProperty(e,"__esModule",{value:!0})}); +`);var a=new Blob([i],{type:hi.XHTML});const o=URL.createObjectURL(a);return{ids:e,title:li(r.querySelector(".title, .subtitle, p")?.textContent??(r.classList.contains("title")?r.textContent:"")),titles:t,load:()=>o,createDocument:()=>(new DOMParser).parseFromString(i,hi.XHTML),size:a.size-Array.from(r.querySelectorAll("[src]"),e=>e.getAttribute("src")?.length??0).reduce((e,t)=>e+t,0),linear:n}}),u=new Map;return t.sections=c.map((e,t)=>{var{ids:r,load:n,createDocument:i,size:a,linear:e}=e;for(const o of r)o&&u.set(o,t);return{id:t,load:n,createDocument:i,size:a,linear:e}}),t.toc=c.map(({title:e,titles:t},r)=>{const n=r.toString();return{label:e,href:n,subitems:t?.length?t.map(({title:e,index:t})=>({label:e,href:`${n}#${t}`})):null}}).filter(e=>e),t.resolveHref=e=>{const[t,r]=e.split("#");return t?{index:Number(t),anchor:e=>e.querySelector(`[${vi}="${r}"]`)}:{index:u.get(r),anchor:e=>e.getElementById(r)}},t.splitTOCHref=e=>e?.split("#")?.map(e=>Number(e))??[],t.getTOCFragment=(e,t)=>e.querySelector(`[${vi}="${t}"]`),t};window.e=window.eval,window.a=window.atob,e.ComicRender=class extends xr{constructor(e,t,r,n){super(),this.isSliding=n||!1,this.mode=t,this.dataSource=[],this.zip="",this.format=r,this.comicBuffer=e,this.element="",this.parser=null,this.chapterList=[],this.largestId=parseInt(l.getKookitConfig("count")||"0")}renderTo(l,c=0){return new Promise((s,e)=>f(this,void 0,void 0,function*(){(yield v())?(this.element=l,ir(l),yield this.handleArchive(),yield f(this,void 0,void 0,function*(){this.parser=new ii(this.dataSource,this.zip,this.mode,this.element,this.format),this.chapterList=this.parser.getChapter(),this.parser.renderComic(),yield this.renderImage(c);let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){let e=r.contentDocument;if(e&&e.getElementById(c+"")){var n=yield this.parser.getImgRatio(),i=e.getElementById(c+"").clientWidth*n;let t=e.getElementsByTagName("img");var a,r=Math.floor(this.element.clientWidth/12),o=r%2==0?r:r-1;for(let e=0;ethis.element.clientHeight?(t[e].style.height=this.element.clientHeight+"px",t[e].style.width=this.element.clientHeight/n+"px",t[e].style.paddingLeft=(this.element.clientWidth-("single"===this.mode?0:o))/2/a-this.element.clientHeight/n/2+"px"):(t[e].style.height=i+"px",t[e].style.marginTop=this.element.clientHeight/2-i/2+"px"));ar(l,this.mode),nr(l,this.mode),this.trigger("rendered"),s()}}}})):s()}))}handleArchive(){return f(this,void 0,void 0,function*(){var e;"CBZ"===this.format?(this.zip=new window.JSZip,e=yield this.zip.loadAsync(this.comicBuffer),console.log(e),this.dataSource=Object.keys(e.files).sort(),console.log(this.dataSource)):"CBT"===this.format?(this.zip=yield si(this.comicBuffer),this.dataSource=this.zip.map(e=>e.name)):"CBR"===this.format&&(this.zip=new window.Unrar(this.comicBuffer),this.dataSource=this.zip.getEntries().map(e=>e.name))})}flatChapter(e){return e}getProgress(){return{totalPage:this.chapterList.length,currentPage:parseInt(l.getKookitConfig("count")||"0")}}getPageSize(){return{width:this.element.clientWidth,height:this.element.clientHeight}}renderImage(e){return f(this,void 0,void 0,function*(){this.parser&&(yield this.parser.renderImage(e-3),yield this.parser.renderImage(e-2),yield this.parser.renderImage(e-1),yield this.parser.renderImage(e),yield this.parser.renderImage(e+1),yield this.parser.renderImage(e+2),yield this.parser.renderImage(e+3))})}getChapter(){return this.chapterList}goToPosition(e){var e=JSON.parse(e)["id"];oi(this.element,this.mode,e),this.record()}goToChapter(e){return f(this,void 0,void 0,function*(){oi(this.element,this.mode,this.dataSource.indexOf(e)+""),yield this.renderImage(this.dataSource.indexOf(e))})}record(){return f(this,void 0,void 0,function*(){br(this.element,this.mode);var e=parseInt(l.getKookitConfig("count")||"0");this.parser&&(yield this.parser.renderImage(e-3),yield this.parser.renderImage(e-2),yield this.parser.renderImage(e-1),yield this.parser.renderImage(e),yield this.parser.renderImage(e+1),yield this.parser.renderImage(e+2),yield this.parser.renderImage(e+3))})}removeContent(){this.element.innerHTML=""}prev(){return f(this,void 0,void 0,function*(){var e=parseInt(l.getKookitConfig("count")||"0");this.parser&&(yield this.parser.renderImage(e),yield this.parser.renderImage(e-1),yield this.parser.renderImage(e-2),yield this.parser.renderImage(e-3),yield this.parser.renderImage(e-4),ai(this.element,1,this.isSliding),br(this.element,this.mode))})}next(){return f(this,void 0,void 0,function*(){var e=parseInt(l.getKookitConfig("count")||"0");this.parser&&(yield this.parser.renderImage(e),yield this.parser.renderImage(e+1),yield this.parser.renderImage(e+2),yield this.parser.renderImage(e+3),yield this.parser.renderImage(e+4),ai(this.element,-1,this.isSliding),br(this.element,this.mode))})}getPosition(){return{text:l.getKookitConfig("text"),chapterTitle:l.getKookitConfig("chapterTitle"),chapterDocIndex:l.getKookitConfig("chapterDocIndex"),count:l.getKookitConfig("count"),percentage:l.getKookitConfig("percentage")}}getMetadata(){return f(this,void 0,void 0,function*(){return yield this.handleArchive(),this.parser=new ii(this.dataSource,this.zip,this.mode,this.element,this.format),yield this.parser.getMetadata()})}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"))}}}},e.EpubRender=class extends Tr{constructor(e,t,r){super(t,r),this.epubBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.isSliding=r||!1}renderTo(n){return new Promise((r,e)=>f(this,void 0,void 0,function*(){if(yield v()){var t=new Blob([this.epubBuffer]),t=new File([t],"book",{lastModified:(new Date).getTime(),type:t.type}),t=yield this.makeZipLoader(t);this.book=yield new yn(t).init();let e=new Sr(this.book);this.element=n,this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),console.log(this.chapterList),console.log(this.chapterDocList),ir(n),ar(n,this.mode),this.trigger("rendered"),r()}else r()}))}makeZipLoader(c){return f(this,void 0,void 0,function*(){const{ZipReader:e,BlobReader:t,TextWriter:r,BlobWriter:n}=window.zip;window.zip.configure({useWebWorkers:!1});const i=new e(new t(c)),a=yield i.getEntries(),o=new Map(a.map(e=>[e.filename,e]));var s=r=>(e,...t)=>o.has(e)?r(o.get(e),...t):null,l=s(e=>e.getData(new r)),s=s((e,t)=>e.getData(new n(t)));return{entries:a,loadText:l,loadBlob:s,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.uncompressedSize)&&void 0!==e?e:0}}})}getMetadata(){return f(this,void 0,void 0,function*(){var e=new Blob([this.epubBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type}),e=yield this.makeZipLoader(e);this.book=yield new yn(e).init();let t=new Sr(this.book);return yield t.getMetadata()})}},e.Fb2Render=class extends Tr{constructor(e,t,r){super(t,r),this.fb2Buffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.isSliding=r||!1}renderTo(n){return new Promise((r,e)=>f(this,void 0,void 0,function*(){if(yield v()){var t=new Blob([this.fb2Buffer]);this.book=yield wi(t);let e=new Sr(this.book);this.element=n,this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),ir(n),ar(n,this.mode),this.trigger("rendered"),r()}else r()}))}getMetadata(){return f(this,void 0,void 0,function*(){var e=new Blob([this.fb2Buffer]);this.book=yield wi(e);let t=new Sr(this.book);return yield t.getMetadata()})}},e.MobiRender=class extends Tr{constructor(e,t,r){super(t,r),this.mobiBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.isSliding=r||!1}renderTo(n){return new Promise((r,e)=>f(this,void 0,void 0,function*(){if(yield v()){var t=new Blob([this.mobiBuffer]),t=new File([t],"book",{lastModified:(new Date).getTime(),type:t.type});if(yield(async e=>{return"BOOKMOBI"===Un(await e.slice(60,68).arrayBuffer())})(t)){this.book=yield new Kn({unzlib:window.fflate.unzlibSync}).open(t);let e=new Sr(this.book);this.element=n,this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),this.metadata=yield e.getMetadata(),console.log(this.chapterList),console.log(this.chapterDocList),ir(n),ar(n,this.mode),this.trigger("rendered"),r()}}else r()}))}getMetadata(){return f(this,void 0,void 0,function*(){var e=new Blob([this.mobiBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});this.book=yield new Kn({unzlib:window.fflate.unzlibSync}).open(e);let t=new Sr(this.book);return yield t.getMetadata()})}},e.StrRender=class extends Tr{constructor(e,t,r){super(t,r),this.bookStr=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element="",this.isSliding=r||!1}renderTo(r){return new Promise((t,e)=>f(this,void 0,void 0,function*(){if(yield v()){this.element=r;let e=new sr(this.bookStr);e.isContainChapter()||(this.bookStr=b(e.getDocText()),e=new sr(this.bookStr)),this.chapterList=e.getChapter(),this.chapterDocList=e.getChapterDoc(),ir(r),ar(r,this.mode),this.trigger("rendered"),t()}else t()}))}},e.TxtRender=class extends Tr{constructor(e,t,r,n){super(t,n),this.txtBuffer=e,this.encoding=r,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.bookStr="",this.element="",this.isSliding=n||!1}renderTo(n){return new Promise((r,e)=>f(this,void 0,void 0,function*(){if(yield v()){var t=new TextDecoder(this.encoding).decode(this.txtBuffer),t=b(t);this.bookStr=t,this.element=n;let e=new sr(this.bookStr);this.chapterList=e.getChapter(),this.chapterDocList=e.getChapterDoc(),ir(n),ar(n,this.mode),this.trigger("rendered"),r()}else r()}))}},Object.defineProperty(e,"__esModule",{value:!0})}); diff --git a/src/components/textToSpeech/component.tsx b/src/components/textToSpeech/component.tsx index 18f3d440..213cee13 100644 --- a/src/components/textToSpeech/component.tsx +++ b/src/components/textToSpeech/component.tsx @@ -83,7 +83,7 @@ class TextToSpeech extends React.Component< if (StorageUtil.getReaderConfig("isSliding") === "yes") { await sleep(1000); } - text = await this.props.htmlBook.rendition.visibleText(); + text = this.props.htmlBook.rendition.visibleText(); text = text .replace(/\s\s/g, "") .replace(/\r/g, "") diff --git a/src/containers/htmlViewer/component.tsx b/src/containers/htmlViewer/component.tsx index 776dd750..51568f22 100644 --- a/src/containers/htmlViewer/component.tsx +++ b/src/containers/htmlViewer/component.tsx @@ -163,7 +163,7 @@ class Viewer extends React.Component { this.props.currentBook.key, this.state.readerMode ); - let chapters = await rendition.getChapter(); + let chapters = rendition.getChapter(); let flattenChapters = rendition.flatChapter(chapters); this.props.handleHtmlBook({ key: this.props.currentBook.key, @@ -206,8 +206,8 @@ class Viewer extends React.Component { }) ); - rendition.on("rendered", async () => { - await this.handleLocation(); + rendition.on("rendered", () => { + this.handleLocation(); let bookLocation: { text: string; count: string; @@ -264,8 +264,8 @@ class Viewer extends React.Component { return false; }); }; - handleLocation = async () => { - let position = await this.props.htmlBook.rendition.getPosition(); + handleLocation = () => { + let position = this.props.htmlBook.rendition.getPosition(); RecordLocation.recordHtmlLocation( this.props.currentBook.key, position.text, @@ -321,7 +321,7 @@ class Viewer extends React.Component { document.getElementsByClassName("html-viewer-page")[0], parseInt(bookLocation.count) || 0 ); - this.handleRest(rendition); + await this.handleRest(rendition); }; handleMobi = async (result: ArrayBuffer) => { let rendition = new MobiRender( @@ -332,7 +332,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }; handleEpub = async (result: ArrayBuffer) => { let rendition = new EpubRender( @@ -353,7 +353,7 @@ class Viewer extends React.Component { document.getElementsByClassName("html-viewer-page")[0], bookLocation.cfi ); - this.handleRest(rendition); + await this.handleRest(rendition); }; handleTxt = async (result: ArrayBuffer) => { const array = new Uint8Array(result as ArrayBuffer); @@ -374,7 +374,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }; handleMD = (result: ArrayBuffer) => { var blob = new Blob([result], { type: "text/plain" }); @@ -389,7 +389,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }; reader.readAsText(blob, "UTF-8"); }; @@ -416,7 +416,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }) ); }; @@ -432,7 +432,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }); }; handleFb2 = async (result: ArrayBuffer) => { @@ -444,7 +444,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }; handleHtml = (result: ArrayBuffer, format: string) => { var blob = new Blob([result], { @@ -461,7 +461,7 @@ class Viewer extends React.Component { await rendition.renderTo( document.getElementsByClassName("html-viewer-page")[0] ); - this.handleRest(rendition); + await this.handleRest(rendition); }; reader.readAsText(blob, "UTF-8"); }; diff --git a/src/containers/lists/contentList/component.tsx b/src/containers/lists/contentList/component.tsx index b39e5ea6..7557b8bb 100644 --- a/src/containers/lists/contentList/component.tsx +++ b/src/containers/lists/contentList/component.tsx @@ -20,7 +20,7 @@ class ContentList extends React.Component { chapters: this.props.htmlBook.chapters, }); } - handleJump(event: any) { + async handleJump(event: any) { event.preventDefault(); let href = event.target.getAttribute("href"); let chapterIndex = _.findIndex(this.props.htmlBook.flattenChapters, { @@ -29,7 +29,7 @@ class ContentList extends React.Component { console.log(chapterIndex, this.props.htmlBook.flattenChapters); let title = this.props.htmlBook.flattenChapters[chapterIndex].title; let index = this.props.htmlBook.flattenChapters[chapterIndex].index; - this.props.htmlBook.rendition.goToChapter(index.toString(), href, ""); + await this.props.htmlBook.rendition.goToChapter(index.toString(), href, ""); this.props.handleCurrentChapter(title); this.props.handleCurrentChapterIndex(index); } diff --git a/src/containers/lists/navList/component.tsx b/src/containers/lists/navList/component.tsx index 060fc4e6..14ee09f5 100644 --- a/src/containers/lists/navList/component.tsx +++ b/src/containers/lists/navList/component.tsx @@ -86,8 +86,8 @@ class NavList extends React.Component { ) : null}
{ - this.handleJump(item.cfi); + onClick={async () => { + await this.handleJump(item.cfi); }} style={{ cursor: "pointer" }} > diff --git a/src/containers/pageWidget/component.tsx b/src/containers/pageWidget/component.tsx index 65aace4c..012a50ce 100644 --- a/src/containers/pageWidget/component.tsx +++ b/src/containers/pageWidget/component.tsx @@ -21,17 +21,18 @@ class Background extends React.Component { this.isFirst = true; } - async UNSAFE_componentWillReceiveProps(nextProps: BackgroundProps) { + UNSAFE_componentWillReceiveProps(nextProps: BackgroundProps) { if (nextProps.htmlBook !== this.props.htmlBook && nextProps.htmlBook) { - await this.handlePageNum(nextProps.htmlBook.rendition); - nextProps.htmlBook.rendition.on("page-changed", async () => { - await this.handlePageNum(nextProps.htmlBook.rendition); - await this.handleLocation(); + this.handlePageNum(nextProps.htmlBook.rendition); + nextProps.htmlBook.rendition.on("page-changed", () => { + this.handlePageNum(nextProps.htmlBook.rendition); + this.handleLocation(); }); } } - handleLocation = async () => { - let position = await this.props.htmlBook.rendition.getPosition(); + handleLocation = () => { + let position = this.props.htmlBook.rendition.getPosition(); + console.log(position); RecordLocation.recordHtmlLocation( this.props.currentBook.key, position.text, @@ -43,8 +44,8 @@ class Background extends React.Component { position.cfi ); }; - async handlePageNum(rendition) { - let pageInfo = await rendition.getProgress(); + handlePageNum(rendition) { + let pageInfo = rendition.getProgress(); this.setState({ prevPage: this.state.isSingle ? pageInfo.currentPage diff --git a/src/containers/panels/operationPanel/component.tsx b/src/containers/panels/operationPanel/component.tsx index b3ed095c..5bbce73c 100644 --- a/src/containers/panels/operationPanel/component.tsx +++ b/src/containers/panels/operationPanel/component.tsx @@ -38,10 +38,10 @@ class OperationPanel extends React.Component< } componentDidMount() { - this.props.htmlBook.rendition.on("page-changed", async () => { + this.props.htmlBook.rendition.on("page-changed", () => { this.speed = Date.now() - this.timeStamp; this.timeStamp = Date.now(); - let pageProgress = await this.props.htmlBook.rendition.getProgress(); + let pageProgress = this.props.htmlBook.rendition.getProgress(); this.setState({ timeLeft: ((pageProgress.totalPage - pageProgress.currentPage) * this.speed) / @@ -91,7 +91,7 @@ class OperationPanel extends React.Component< } StorageUtil.setReaderConfig("isFullscreen", "no"); } - handleAddBookmark = async () => { + handleAddBookmark = () => { let bookKey = this.props.currentBook.key; let bookLocation = RecordLocation.getHtmlLocation(bookKey); let text = bookLocation.text; @@ -100,7 +100,7 @@ class OperationPanel extends React.Component< let cfi = JSON.stringify(bookLocation); if (!text) { - text = await this.props.htmlBook.rendition.visibleText(); + text = this.props.htmlBook.rendition.visibleText(); } text = text .replace(/\s\s/g, "") diff --git a/src/containers/panels/progressPanel/component.tsx b/src/containers/panels/progressPanel/component.tsx index 379f7730..ebd33872 100644 --- a/src/containers/panels/progressPanel/component.tsx +++ b/src/containers/panels/progressPanel/component.tsx @@ -22,16 +22,16 @@ class ProgressPanel extends React.Component< }; } - async UNSAFE_componentWillReceiveProps(nextProps: ProgressPanelProps) { + UNSAFE_componentWillReceiveProps(nextProps: ProgressPanelProps) { if (nextProps.htmlBook !== this.props.htmlBook && nextProps.htmlBook) { - await this.handlePageNum(nextProps.htmlBook.rendition); + this.handlePageNum(nextProps.htmlBook.rendition); nextProps.htmlBook.rendition.on("page-changed", async () => { - await this.handlePageNum(nextProps.htmlBook.rendition); + this.handlePageNum(nextProps.htmlBook.rendition); }); } } - async handlePageNum(rendition) { - let pageInfo = await rendition.getProgress(); + handlePageNum(rendition) { + let pageInfo = rendition.getProgress(); this.setState({ currentPage: this.state.isSingle ? pageInfo.currentPage @@ -39,14 +39,14 @@ class ProgressPanel extends React.Component< totalPage: pageInfo.totalPage, }); } - onProgressChange = (event: any) => { + onProgressChange = async (event: any) => { const percentage = event.target.value / 100; if (this.props.htmlBook.flattenChapters.length > 0) { let chapterIndex = percentage === 1 ? this.props.htmlBook.flattenChapters.length - 1 : Math.floor(this.props.htmlBook.flattenChapters.length * percentage); - this.props.htmlBook.rendition.goToChapter( + await this.props.htmlBook.rendition.goToChapter( this.props.htmlBook.flattenChapters[chapterIndex].index.toString(), this.props.htmlBook.flattenChapters[chapterIndex].href, "" @@ -63,10 +63,10 @@ class ProgressPanel extends React.Component< this.props.htmlBook.rendition.prevChapter(); } }; - handleJumpChapter = (event: any) => { + handleJumpChapter = async (event: any) => { let targetChapter = parseInt(event.target.value.trim()) - 1; if (this.props.htmlBook.flattenChapters.length > 0) { - this.props.htmlBook.rendition.goToChapter( + await this.props.htmlBook.rendition.goToChapter( this.props.htmlBook.flattenChapters[targetChapter].index, this.props.htmlBook.flattenChapters[targetChapter].href, "" diff --git a/src/pages/htmlReader/component.tsx b/src/pages/htmlReader/component.tsx index 62ef355e..a08c0de3 100644 --- a/src/pages/htmlReader/component.tsx +++ b/src/pages/htmlReader/component.tsx @@ -159,7 +159,7 @@ class Reader extends React.Component { className="previous-chapter-single-container" onClick={async () => { this.props.htmlBook.rendition.prev(); - await this.handleLocation(); + this.handleLocation(); }} > diff --git a/src/utils/readUtils/recordLocation.tsx b/src/utils/readUtils/recordLocation.tsx index a26db732..845f39b3 100644 --- a/src/utils/readUtils/recordLocation.tsx +++ b/src/utils/readUtils/recordLocation.tsx @@ -38,16 +38,10 @@ class RecordLocation { localStorage.setItem("recordLocation", JSON.stringify(obj)); } else { if ( - (!text || - !chapterTitle || - !chapterDocIndex || - !chapterHref || - !count || - !percentage) && + (!text || !chapterTitle || !chapterDocIndex || !count || !percentage) && document.location.href.indexOf("/cb") === -1 //漫画的情况,cbr,cbt,cbz ) return; - let json = localStorage.getItem("recordLocation"); let obj = JSON.parse(json || "{}"); obj[bookKey] = { diff --git a/src/utils/serviceUtils/mouseEvent.tsx b/src/utils/serviceUtils/mouseEvent.tsx index b6b72dec..f5ba7778 100644 --- a/src/utils/serviceUtils/mouseEvent.tsx +++ b/src/utils/serviceUtils/mouseEvent.tsx @@ -136,8 +136,8 @@ const gesture = (rendition: any, type: string) => { } }; -const handleLocation = async (key: string, rendition: any) => { - let position = await rendition.getPosition(); +const handleLocation = (key: string, rendition: any) => { + let position = rendition.getPosition(); RecordLocation.recordHtmlLocation( key, position.text,