@prose-reader/streamer 1.291.0 → 1.292.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- (function(m,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("@prose-reader/shared"),require("@prose-reader/archive-parser"),require("xmldoc"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@prose-reader/shared","@prose-reader/archive-parser","xmldoc","rxjs"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m["prose-streamer"]={},m.shared,m.archiveParser,m.xmldoc,m.rxjs))})(this,(function(m,f,y,I,c){"use strict";const S=(n,t)=>{const s=n.split(/(\d+)/),r=t.split(/(\d+)/);for(let e=0,i=s.length;e<i;e++)if(s[e]!==r[e])return s[e]?.match(/\d/)?+(s[e]||"")-+(r[e]||""):(s[e]||"").localeCompare(r[e]||"");return 1},w=n=>n.substring(n.lastIndexOf("/")+1)||n,E=n=>n.endsWith("/")?n.slice(0,-1):n,C=n=>{const t=n.lastIndexOf("/");return t>=0?n.substring(0,t):""},V=async(n,{orderByAlpha:t,name:s}={})=>{let r=n;return t&&(r=r.slice().sort((e,i)=>S(e.name,i.name))),{filename:s||"",records:r.map(e=>{const i=e.size,o=w(e.name);return e.isDir?{dir:!0,basename:o,uri:e.name,size:i}:{dir:e.isDir,basename:o,encodingFormat:f.detectMimeTypeFromName(e.name),uri:e.name,blob:async()=>new Blob([await e.data()],{type:f.detectMimeTypeFromName(e.name)??""}),string:async()=>{const a=await e.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(a)))},size:i}}),close:()=>Promise.resolve()}},h=f.Report.namespace("@prose-reader/streamer",!1,{color:"#ffae42"}),q=n=>{const t={};for(const r of n){const e=r.split("/");let i=t;for(let o=0;o<e.length;o++){const a=e[o];a!==void 0&&(i[a]||(i[a]={}),i=i[a])}}const s=(r,e="")=>Object.keys(r).sort().map((i,o,a)=>{const d=o===a.length-1,u=e+(d?"└── ":"├── "),p=e+(d?" ":"│ "),g=r[i];return g&&Object.keys(g).length>0?`${u}${i}/
2
- ${s(g,p)}`:`${u}${i}`}).join(`
3
- `);return s(t)},G=async(n,{orderByAlpha:t,name:s}={})=>{let r=Object.values(n.files);t&&(r=r.slice().sort((i,o)=>S(i.name,o.name)));const e={filename:s||"",records:r.map(i=>{const o=i._data.uncompressedSize,a=w(i.name);return i.dir?{dir:!0,basename:a,uri:i.name,size:o}:{dir:!1,basename:w(i.name),uri:i.name,encodingFormat:f.detectMimeTypeFromName(i.name),blob:()=>i.async("blob"),string:()=>i.async("string"),...i.internalStream&&{stream:i.internalStream},size:i._data.uncompressedSize}}),close:()=>Promise.resolve()};if(h.log("Generated archive",e),process.env.NODE_ENV==="development"&&h.isEnabled()){const i=q(r.map(o=>o.name));h.groupCollapsed(...h.getGroupArgs("Archive folder structure")),h.log(`
4
- ${i}`),h.groupEnd()}return e},H=async(n,{name:t}={})=>{const s=await n.getFilesArray(),r={close:()=>n.close(),filename:t??"",records:s.map(e=>({dir:!1,basename:e.file.name,encodingFormat:f.detectMimeTypeFromName(e.file.name),size:e.file.size,uri:`${e.path}${e.file.name}`,blob:async()=>await e.file.extract(),string:async()=>(await e.file.extract()).text()}))};return h.log("Generated archive",r),r},J=async(n,{mimeType:t,direction:s}={mimeType:"text/plain"})=>{const r=`
1
+ (function(f,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("@prose-reader/shared"),require("@prose-reader/archive-parser"),require("xmldoc"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@prose-reader/shared","@prose-reader/archive-parser","xmldoc","rxjs"],m):(f=typeof globalThis<"u"?globalThis:f||self,m(f["prose-streamer"]={},f.shared,f.archiveParser,f.xmldoc,f.rxjs))})(this,(function(f,m,y,T,c){"use strict";const I=(e,t)=>{const i=e.split(/(\d+)/),r=t.split(/(\d+)/);for(let n=0,o=i.length;n<o;n++)if(i[n]!==r[n])return i[n]?.match(/\d/)?+(i[n]||"")-+(r[n]||""):(i[n]||"").localeCompare(r[n]||"");return 1},w=e=>e.substring(e.lastIndexOf("/")+1)||e,L=e=>e.endsWith("/")?e.slice(0,-1):e,M=e=>{const t=e.lastIndexOf("/");return t>=0?e.substring(0,t):""},te=async(e,{orderByAlpha:t,name:i}={})=>{let r=e;return t&&(r=r.slice().sort((n,o)=>I(n.name,o.name))),{filename:i||"",records:r.map(n=>{const o=n.size,s=w(n.name);return n.isDir?{dir:!0,basename:s,uri:n.name,size:o}:{dir:n.isDir,basename:s,encodingFormat:m.detectMimeTypeFromName(n.name),uri:n.name,blob:async()=>new Blob([await n.data()],{type:m.detectMimeTypeFromName(n.name)??""}),string:async()=>{const a=await n.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(a)))},size:o}}),close:()=>Promise.resolve()}},h=m.Report.namespace("@prose-reader/streamer",!1,{color:"#ffae42"}),ne=e=>{const t={};for(const r of e){const n=r.split("/");let o=t;for(let s=0;s<n.length;s++){const a=n[s];a!==void 0&&(o[a]||(o[a]={}),o=o[a])}}const i=(r,n="")=>Object.keys(r).sort().map((o,s,a)=>{const d=s===a.length-1,p=n+(d?"└── ":"├── "),u=n+(d?" ":"│ "),g=r[o];return g&&Object.keys(g).length>0?`${p}${o}/
2
+ ${i(g,u)}`:`${p}${o}`}).join(`
3
+ `);return i(t)},re=async(e,{orderByAlpha:t,name:i}={})=>{let r=Object.values(e.files);t&&(r=r.slice().sort((o,s)=>I(o.name,s.name)));const n={filename:i||"",records:r.map(o=>{const s=o._data.uncompressedSize,a=w(o.name);return o.dir?{dir:!0,basename:a,uri:o.name,size:s}:{dir:!1,basename:w(o.name),uri:o.name,encodingFormat:m.detectMimeTypeFromName(o.name),blob:()=>o.async("blob"),string:()=>o.async("string"),...o.internalStream&&{stream:o.internalStream},size:o._data.uncompressedSize}}),close:()=>Promise.resolve()};if(h.log("Generated archive",n),process.env.NODE_ENV==="development"&&h.isEnabled()){const o=ne(r.map(s=>s.name));h.groupCollapsed(...h.getGroupArgs("Archive folder structure")),h.log(`
4
+ ${o}`),h.groupEnd()}return n},ie=async(e,{name:t}={})=>{const i=await e.getFilesArray(),r={close:()=>e.close(),filename:t??"",records:i.map(n=>({dir:!1,basename:n.file.name,encodingFormat:m.detectMimeTypeFromName(n.file.name),size:n.file.size,uri:`${n.path}${n.file.name}`,blob:async()=>await n.file.extract(),string:async()=>(await n.file.extract()).text()}))};return h.log("Generated archive",r),r},oe=async(e,{mimeType:t,direction:i}={mimeType:"text/plain"})=>{const r=`
5
5
  <?xml version="1.0" encoding="UTF-8"?>
6
6
  <package xmlns="http://www.idpf.org/2007/opf" version="3.0" xml:lang="ja" prefix="rendition: http://www.idpf.org/vocab/rendition/#"
7
7
  unique-identifier="ootuya-id">
@@ -12,28 +12,55 @@ ${i}`),h.groupEnd()}return e},H=async(n,{name:t}={})=>{const s=await n.getFilesA
12
12
  <manifest>
13
13
  <item id="p01" href="p01.txt" media-type="text/plain"/>
14
14
  </manifest>
15
- <spine page-progression-direction="${s??"ltr"}">
15
+ <spine page-progression-direction="${i??"ltr"}">
16
16
  <itemref idref="p01" />
17
17
  </spine>
18
18
  </package>
19
- `;return{filename:"content.txt",records:[{dir:!1,basename:w("generated.opf"),uri:"generated.opf",blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:w("p01.txt"),uri:"p01.txt",blob:async()=>typeof n=="string"?new Blob([n]):n,string:async()=>typeof n=="string"?n:n.text(),size:typeof n=="string"?n.length:n.size,encodingFormat:t}],close:()=>Promise.resolve()}},K=async(n,t)=>{const s=`
19
+ `;return{filename:"content.txt",records:[{dir:!1,basename:w("generated.opf"),uri:"generated.opf",blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:w("p01.txt"),uri:"p01.txt",blob:async()=>typeof e=="string"?new Blob([e]):e,string:async()=>typeof e=="string"?e:e.text(),size:typeof e=="string"?e.length:e.size,encodingFormat:t}],close:()=>Promise.resolve()}},se=async(e,t)=>{const i=`
20
20
  <?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="bookid">
21
21
  <metadata>
22
22
  <meta property="rendition:layout">${t?.useRenditionFlow?"reflowable":"pre-paginated"}</meta>
23
23
  ${t?.useRenditionFlow?'<meta property="rendition:flow">scrolled-continuous</meta>':""}
24
24
  </metadata>
25
25
  <manifest>
26
- ${n.map(i=>`<item id="${w(i)}" href="${i}" media-type="${f.detectMimeTypeFromName(i)}"/>`).join(`
26
+ ${e.map(o=>`<item id="${w(o)}" href="${o}" media-type="${m.detectMimeTypeFromName(o)}"/>`).join(`
27
27
  `)}
28
28
  </manifest>
29
29
  <spine>
30
- ${n.map(i=>`<itemref idref="${w(i)}" />`).join(`
30
+ ${e.map(o=>`<itemref idref="${w(o)}" />`).join(`
31
31
  `)}
32
32
  </spine>
33
33
  </package>
34
- `,r=n.map(i=>({dir:!1,basename:w(i),encodingFormat:f.detectMimeTypeFromName(i),uri:i,size:100/n.length,blob:async()=>(await fetch(i)).blob(),string:async()=>""}));return{filename:"",records:[{dir:!1,basename:"content.opf",uri:"content.opf",size:0,blob:async()=>new Blob,string:async()=>s},...r],close:()=>Promise.resolve()}},Y=({enableReport:n}={})=>{h.enable(!!n)},L=n=>{const s=Object.values(n.records).filter(r=>!r.dir).find(r=>r.uri.endsWith(".opf"));return{data:s,basePath:s?.uri.substring(0,s.uri.lastIndexOf("/"))||""}};async function M(n){const{data:t,basePath:s}=L(n)||{};if(!t||t.dir)return;const r=await t.string();return{opf:y.parseOpf(r),basePath:s}}const x=y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),Q=({archive:n})=>async t=>{const s=n.records.find(e=>!e.dir&&e.basename.toLowerCase()===x);if(!s||s.dir)return t;const r=await s.string();try{const e=y.parseAppleDisplayOptionsXml(r),{renditionLayout:i}=y.resolveArchiveMetadata(e);return{...t,renditionLayout:t.renditionLayout??i}}catch(e){return console.error(`Unable to parse ${y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME} for content
35
- `,r),console.error(e),t}},N=y.COMIC_INFO_FILENAME.toLowerCase(),Z=({archive:n})=>async t=>{const s=n.records.find(i=>i.basename.toLowerCase()===N&&!i.dir);if(!s||s.dir)return t;const r={...t,spineItems:t.spineItems.filter(i=>!i.id.toLowerCase().endsWith(N)).map((i,o,a)=>({...i,progressionWeight:1/a.length}))},e=await s.string();try{const i=y.parseComicInfo(e),o=y.resolveArchiveMetadata(i);return{...r,readingDirection:o.readingDirection??"ltr"}}catch(i){return console.error(`Unable to parse ${y.COMIC_INFO_FILENAME} for content
36
- `,e),console.error(i),r}},j=({archive:n,baseUrl:t})=>async()=>{const s=Object.values(n.records).filter(r=>!r.dir);return{filename:n.filename,title:n.records.find(({dir:r})=>r)?.basename.replace(/\/$/,"")||n.filename,renditionLayout:void 0,renditionSpread:"auto",readingDirection:"ltr",spineItems:s.filter(r=>!r.basename.endsWith(".db")).map((r,e)=>{const i=t||(/^https?:\/\//.test(r.uri)?"":"file://");return{id:`${e}.${r.basename}`,index:e,href:encodeURI(`${i}${r.uri}`),renditionLayout:void 0,progressionWeight:1/s.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:r.encodingFormat}}),items:s.map((r,e)=>({id:`${e}.${r.basename}`,href:encodeURI(`${t}${r.uri}`)}))}},k=async({archive:n,archiveOpf:t})=>{if(!t)return[];const{opf:s,basePath:r}=t,{spineRows:e}=s;return n.records.filter(o=>e.find(a=>r?`${r}/${a.href}`===o.uri:`${a.href}`===o.uri))},O=(n,t,s)=>{const{basePath:r}=L(t)||{};return n.map(e=>{const i=e.href,o=s?.(i)??"";return{href:r?`${o}${r}/${i}`:`${o}${i}`,id:e.id,mediaType:e.mediaType}})},ee=n=>{const t=n?.trim();return t==="scrolled-continuous"||t==="scrolled-doc"||t==="paginated"||t==="auto"?t:"auto"},te=n=>{const t=n?.trim();if(t==="none"||t==="landscape"||t==="portrait"||t==="both"||t==="auto")return t},ne=n=>{const t=n?.trim();if(t==="cover"||t==="title-page"||t==="copyright-page"||t==="text")return t},re=({archive:n,baseUrl:t,archiveOpf:s})=>async r=>{if(!s)return r;const{opf:e,basePath:i}=s,o=y.resolveArchiveMetadata(e);h.groupCollapsed(...h.getGroupArgs("OPF parsed")),h.log("opf",e),h.groupEnd();const a=e.renditionLayoutMeta?.trim(),d=a==="reflowable"||a==="pre-paginated"?a:o.renditionLayout,u=e.title?.trim()||n.records.find(({dir:l})=>l)?.basename||"",p=o.readingDirection??"ltr",v=(await k({archive:n,archiveOpf:s})).reduce((l,A)=>A.size+l,0),$=e.guide,F=[];for(const l of $){const A=ne(l.type);A!==void 0&&F.push({href:l.href,title:l.title,type:A})}return{filename:n.filename,renditionLayout:d,renditionFlow:ee(e.renditionFlowMeta),renditionSpread:te(e.renditionSpreadMeta),title:u,readingDirection:p,spineItems:e.spineRows.map((l,A)=>{const b=n.records.find(R=>R.uri.endsWith(l.href))?.size||0,T=t||(/^https?:\/\//.test(l.href)?"":"file://");return{id:l.id,index:A,href:l.href.startsWith("https://")?l.href:i?`${T}${i}/${l.href}`:`${T}${l.href}`,renditionLayout:l.renditionLayout??d,progressionWeight:b/v,pageSpreadLeft:l.pageSpreadLeft,pageSpreadRight:l.pageSpreadRight,mediaType:l.mediaType}}),items:O(e.manifestItems,n,l=>/^https?:\/\//.test(l)?"":t||"file://"),guide:F.length>0?F:void 0}},ie=n=>{const t=n.descendantWithPath("head")?.childrenNamed("meta").find(s=>s.attr.name==="viewport");return!!(t&&t.attr.name==="viewport")},se=n=>n.reduce(async(t,s)=>{if(!await t||!f.isXmlBasedMimeType({mimeType:s.encodingFormat,uri:s.uri}))return!1;const e=s.dir?null:await s.string();return e?ie(new I.XmlDocument(e)):!1},Promise.resolve(!0)),oe=({archive:n,archiveOpf:t})=>async s=>{if(s.renditionLayout==="reflowable"&&s.spineItems.every(e=>e.renditionLayout==="reflowable")){const e=await k({archive:n,archiveOpf:t});if(await se(e))return{...s,spineItems:s.spineItems.map(o=>({...o,renditionLayout:"pre-paginated"})),renditionLayout:"pre-paginated"}}return s},ae=async n=>{let t;return await Promise.all(n.records.map(async s=>{if(s.dir||!s.uri.endsWith(y.KOBO_DISPLAY_OPTIONS_FILENAME))return;const r=await s.string();try{const{renditionLayout:e}=y.parseKoboXml(r);e&&(t=e)}catch(e){console.error(`Unable to parse ${y.KOBO_DISPLAY_OPTIONS_FILENAME} for content
37
- `,r),console.error(e)}})),{kind:"kobo",...t!==void 0?{renditionLayout:t}:{}}},ce=({archive:n})=>async t=>{const s=await ae(n),{renditionLayout:r}=y.resolveArchiveMetadata(s);return{...t,renditionLayout:t.renditionLayout??r}},de=n=>n.records.some(t=>t.basename.endsWith(".opf")),le=({archive:n})=>async t=>de(n)?t:{...t,spineItems:t.spineItems.map(r=>{const e=n.records.find(o=>decodeURI(r.href).endsWith(o.uri)),i=f.parseContentType(e?.encodingFormat??"")||f.detectMimeTypeFromName(e?.basename??"");return{...r,renditionLayout:i&&f.isMediaContentMimeType(i)?"pre-paginated":r.renditionLayout}})},W=n=>n?n.children.map(t=>t instanceof I.XmlTextNode?t.text:t instanceof I.XmlElement?W(t):"").join("").trim():"",ue=n=>y.tokenizeXmlSpaceSeparatedList(n.properties).includes("nav"),P=(n,{basePath:t,baseUrl:s})=>{const r={contents:[],path:"",href:"",title:""};let e=n.childNamed("span")||n.childNamed("a");r.title=(e?.attr.title||e?.val.trim()||W(e))??"";let i=e?.name;i!=="a"&&(e=n.descendantWithPath(`${i}.a`),e&&(i=e.name.toLowerCase())),i==="a"&&e?.attr.href&&(r.path=f.urlJoin(t,e.attr.href),r.href=f.urlJoin(s,t,e.attr.href));const o=n.childNamed("ol");if(o){const a=o.childrenNamed("li");a&&a.length>0&&(r.contents=a.map(d=>P(d,{basePath:t,baseUrl:s})))}return r},pe=(n,{basePath:t,baseUrl:s})=>{const r=[];let e;return n.descendantWithPath("body.nav.ol")?e=n.descendantWithPath("body.nav.ol")?.children:n.descendantWithPath("body.section.nav.ol")&&(e=n.descendantWithPath("body.section.nav.ol")?.children),e&&e.length>0&&e.filter(i=>i.name==="li").forEach(i=>{r.push(P(i,{basePath:t,baseUrl:s}))}),r},me=async(n,t,{baseUrl:s})=>{const r=n.manifestItems.find(ue);if(r?.href){const e=Object.values(t.records).find(i=>i.uri.endsWith(r.href));if(e&&!e.dir){const i=new I.XmlDocument(await e.string()),o=C(e.uri);return pe(i,{basePath:o,baseUrl:s})}}},B=(n,{opfBasePath:t,baseUrl:s,prefix:r})=>{const e=n?.childNamed(`${r}content`)?.attr.src||"",i={title:n?.descendantWithPath(`${r}navLabel.${r}text`)?.val||"",path:f.urlJoin(t,e),href:f.urlJoin(s,t,e),contents:[]},o=n.childrenNamed(`${r}navPoint`);return o&&o.length>0&&(i.contents=o.map(a=>B(a,{opfBasePath:t,baseUrl:s,prefix:r}))),i},fe=(n,{opfBasePath:t,baseUrl:s})=>{const r=[],e=n.name;let i="";return e.indexOf(":")!==-1&&(i=`${e.split(":")[0]}:`),n.childNamed(`${i}navMap`)?.childrenNamed(`${i}navPoint`).forEach(o=>{r.push(B(o,{opfBasePath:t,baseUrl:s,prefix:i}))}),r},he=async({opf:n,opfBasePath:t,baseUrl:s,archive:r})=>{const e=n.spineTocIdref;if(e){const i=n.manifestItems.find(o=>o.id===e);if(i){const o=`${t}${t===""?"":"/"}${i.href}`,a=Object.values(r.records).find(d=>d.uri.endsWith(o));if(a&&!a.dir){const d=new I.XmlDocument(await a.string());return fe(d,{opfBasePath:t,baseUrl:s})}}}},ge=async(n,t,{baseUrl:s})=>{const{basePath:r}=L(t)||{},e=await me(n,t,{baseUrl:s});if(e)return e;const i=await he({opf:n,opfBasePath:r??"",archive:t,baseUrl:s});if(i)return i},ye=n=>n.replace(/\.[^.]+$/,"").replace(/[_-]/g," ").replace(/\s+/g," ").trim(),be=(n,t)=>{if(!(n.spineItems.length===0||!n.spineItems.every(r=>(f.parseContentType(r.mediaType??"")||f.detectMimeTypeFromName(r.href))?.startsWith("audio/"))))return n.spineItems.map(r=>{const e=t.records.find(i=>!i.dir&&decodeURI(r.href).endsWith(i.uri));return{title:ye(e?.basename??r.href),href:r.href,path:e?.uri??r.href,contents:[]}})},ve=(n,{baseUrl:t})=>{const s=[...n.records].sort((e,i)=>S(e.uri,i.uri)),r=(e,i,o,a,d)=>{const u=e.find(v=>v.title===i),[p,...g]=o;return u?p?[...e.filter($=>$!==u),{...u,contents:[...u.contents,...r(u.contents,p,g,a,d)]}]:u.path.split("/").length>d.split("/").length?[...e.filter($=>$!==u),{...u,path:d,href:a}]:e:p?[...e,{contents:r([],p,g,a,d),href:a,path:d,title:i}]:[...e,{contents:[],href:a,path:d,title:i}]};return s.reduce((e,i)=>{if(i.dir)return e;const o=i.uri.split("/").slice(0,-1),[a,...d]=o;if(!a)return e;const u=f.urlJoin(t,encodeURI(i.uri)).replace(/\/$/,""),p=i.uri.replace(/\/$/,"");return r(e,a,d,u,p)},[])},we=async(n,t,{baseUrl:s,archiveOpf:r})=>{if(r)return await ge(r.opf,n,{baseUrl:s})||[];const e=be(t,n);if(e)return e;const i=ve(n,{baseUrl:s});if(i.length!==0)return i},$e=({archive:n,baseUrl:t,archiveOpf:s})=>async r=>{if(r.nav)return r;const e=await we(n,r,{baseUrl:t,archiveOpf:s});return e?{...r,nav:{toc:e}}:r},z=async(n,{baseUrl:t=""}={})=>{const s=await M(n),r=[re({archive:n,baseUrl:t,archiveOpf:s}),Z({archive:n}),Q({archive:n}),le({archive:n}),oe({archive:n,archiveOpf:s}),ce({archive:n}),$e({archive:n,baseUrl:t,archiveOpf:s})];try{const e=j({archive:n,baseUrl:t})(),i=await r.reduce(async(o,a)=>await a(await o),e);if(h.log("Generated manifest",i),process.env.NODE_ENV==="development"&&h.isEnabled()){const o=JSON.stringify(i,null,2);h.groupCollapsed(...h.getGroupArgs("Generated manifest")),h.log(`
38
- ${o}`),h.groupEnd()}return i}catch(e){throw h.error(e),e}},Fe=n=>{const t=n.descendantWithPath("head")?.childrenNamed("meta").find(s=>s.attr.name==="calibre:cover");return!!(t&&t.attr.name==="calibre:cover")},Ae=n=>n.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(t=>t.attr.width==="100%"&&t.attr.preserveAspectRatio==="none"),Te=({archive:n,resourcePath:t})=>async s=>{const r=Object.values(n.records).find(e=>e.uri===t&&!e.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const e=s.body??await r.string(),i=new I.XmlDocument(e);if(Fe(i)){const o=Ae(i);return o&&delete o.attr.preserveAspectRatio,{...s,body:i?.toString()}}}return s},Ie=({archive:n,resourcePath:t})=>async s=>Te({archive:n,resourcePath:t})(s),Se=({archive:n,resourcePath:t})=>async s=>{const r=Object.values(n.records).find(e=>e.uri===t&&!e.dir);if(r&&!r.dir&&r.basename.endsWith(".css")){const i=(s.body??await r.string()).replaceAll("-webkit-writing-mode","writing-mode");return{...s,body:i}}return s},Le=async(n,t)=>{const s=await M(n);if(s){const{opf:r}=s,e=O(r.manifestItems,n,()=>"");if(e.find(o=>t.endsWith(o.href))?.mediaType)return{mediaType:e.find(o=>t.endsWith(o.href))?.mediaType}}return{mediaType:Ee(t)}},Ee=n=>{if(n.endsWith(".css"))return"text/css; charset=UTF-8";if(n.endsWith(".jpg"))return"image/jpg";if(n.endsWith(".xhtml"))return"application/xhtml+xml";if(n.endsWith(".mp4"))return"video/mp4";if(n.endsWith(".svg"))return"image/svg+xml"},Re=({archive:n,resourcePath:t})=>async s=>{const r=Object.values(n.records).find(i=>i.uri===t&&!i.dir);if(!r||r.dir)return s;const e=await Le(n,t);return{...s,params:{...s.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...e.mediaType&&{contentType:e.mediaType}}}},_=["div","span","p","a","li","ul","ol","h1","h2","h3","h4","h5","h6","table","tr","td","th","thead","tbody","tfoot","section","article","header","footer","nav","aside","main","figure","figcaption","blockquote","pre","code","form","textarea","select","option","button","label","fieldset","legend","caption","dl","dt","dd","iframe","video","audio","canvas","script","style"],Ce=({archive:n,resourcePath:t})=>async s=>{const r=Object.values(n.records).find(e=>e.uri===t&&!e.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const e=s.body??await r.string();if(!new RegExp(`<(${_.join("|")})[\\s/>]`,"i").test(e))return s;const o=new RegExp(`<(${_.join("|")})(\\s[^>]*)?\\s*/>`,"gi"),a=e.replace(o,(d,u,p="")=>`<${u} ${p.trim()}></${u}>`);return{...s,body:a}}return s},D=async(n,t)=>{const s=Object.values(n.records).find(i=>i.uri===t&&!i.dir);if(!s||s.dir)throw new Error(`no file found for resourcePath:${t}`);const r={params:{}},e=[Re({archive:n,resourcePath:t}),Ce({archive:n,resourcePath:t}),Se({archive:n,resourcePath:t}),Ie({archive:n,resourcePath:t})];try{const i=await e.reduce(async(o,a)=>await a(await o),Promise.resolve(r));return h.log("Generated resource",t,i),{...i,body:i.body??await s.blob()}}catch(i){throw h.error(i),i}};class Me{constructor(t){this.cleanArchiveAfter=t,this.state$=new c.BehaviorSubject({status:"idle",locks:0})}update(t){this.state$.next({...this.state$.getValue(),...t})}get locks$(){return this.state$.pipe(c.map(({locks:t})=>t))}get state(){return this.state$.getValue()}get isUnlocked$(){return this.locks$.pipe(c.map(t=>t<=0),c.distinctUntilChanged(),c.shareReplay())}get overTTL$(){return this.isUnlocked$.pipe(c.switchMap(t=>t?this.cleanArchiveAfter===1/0?c.NEVER:c.timer(this.cleanArchiveAfter):c.NEVER))}}const Ne=({getArchive:n,cleanArchiveAfter:t=300*1e3})=>{const s=new c.Subject,r=new c.Subject,e=new c.Subject,i={},o=s.pipe(c.mergeMap(u=>{const p=i[u];if(!p||p.state.status!=="idle")return c.EMPTY;let g=!1;const v=b=>{h.debug(`Cleaning up archive with key: ${b}`);const T=i[b];delete i[b],g||(T?.state.archive?.close(),g=!0)};p.update({status:"loading"});const $=p.locks$,F=p.isUnlocked$,l=$.pipe(c.pairwise(),c.filter(([b,T])=>T>b),c.startWith(!0));return c.from(n(u)).pipe(c.tap(b=>{p.update({archive:b,status:"success"})}),c.catchError(b=>(v(u),p.update({status:"error",error:b}),c.EMPTY)),c.switchMap(()=>{const b=l.pipe(c.switchMap(()=>e),c.switchMap(()=>F),c.filter(R=>R));return c.merge(b,p.overTTL$).pipe(c.first(),c.tap(()=>{v(u)}))}))}),c.takeUntil(r)),a=u=>{let p=!1;const g=i[u]??new Me(t);i[u]=g,g.update({locks:g.state.locks+1});const v=()=>{p||(p=!0,g.update({locks:g.state.locks-1}))};s.next(u);const $=g.state$.pipe(c.map(({archive:l})=>l),c.filter(l=>!!l)),F=g.state$.pipe(c.tap(({error:l})=>{if(l)throw l}),c.ignoreElements());return c.merge($,F).pipe(c.first(),c.map(l=>({archive:l,release:v})),c.catchError(l=>{throw v(),l}))},d=()=>{e.next()};return o.subscribe(),{access:a,purge:d,_archives:i}},U=n=>n?/^\d+$/.test(n)?{valid:!0,value:Number.parseInt(n,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},ke=n=>{if(!n.toLowerCase().startsWith("bytes="))return{kind:"missing"};const t=n.slice(6).trim();if(!t)return{kind:"invalid"};if(t.includes(","))return{kind:"multi"};const s=/^(\d*)-(\d*)$/.exec(t);if(!s)return{kind:"invalid"};const[,r="",e=""]=s,i=U(r.trim()),o=U(e.trim());return!i.valid||!o.valid?{kind:"invalid"}:{kind:"single",start:i.value,end:o.value}},Oe=n=>{if(n instanceof Blob)return{size:n.size,slice:(s,r)=>{const e=n.slice(s,r);return{content:e,length:e.size}}};const t=new TextEncoder().encode(n);return{size:t.byteLength,slice:(s,r)=>{const e=t.slice(s,r);return{content:e,length:e.byteLength}}}},We=({body:n,contentType:t,rangeHeader:s})=>{const r=new Headers;if(t&&r.set("Content-Type",t),r.set("Accept-Ranges","bytes"),!s)return n instanceof Blob&&r.set("Content-Length",String(n.size)),new Response(n,{status:200,headers:r});const e=ke(s);if(e.kind==="missing"||e.kind==="multi")return n instanceof Blob&&r.set("Content-Length",String(n.size)),new Response(n,{status:200,headers:r});const i=Oe(n),o=i.size;if(e.kind==="invalid")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${o}`}});let a=e.start,d=e.end;if(a===void 0&&d===void 0)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${o}`}});if(a===void 0){const p=Math.min(d??0,o);a=Math.max(0,o-p),d=o-1}else(d===void 0||d>=o)&&(d=o-1);if(a<0||d<0||a>=o||d>=o||a>d)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${o}`}});const u=i.slice(a,d+1);return r.set("Content-Length",String(u.length)),r.set("Content-Range",`bytes ${a}-${d}/${o}`),new Response(u.content,{status:206,headers:r})};class X{constructor({onError:t,onManifestSuccess:s,...r}){this.onError=e=>(console.error(e),new Response(String(e),{status:500})),this.archiveLoader=Ne(r),this.onManifestSuccess=s??(({manifest:e})=>Promise.resolve(e)),this.onError=t??this.onError}prune(){this.archiveLoader.purge()}accessArchive(t){return this.lastAccessedKey!==void 0&&this.lastAccessedKey!==t&&this.archiveLoader.purge(),this.lastAccessedKey=t,this.archiveLoader.access(t)}accessArchiveWithoutLock(t){return this.accessArchive(t).pipe(c.map(({archive:s,release:r})=>(r(),s)))}withArchiveResponse({key:t,getResponse:s}){const r=this.accessArchive(t).pipe(c.mergeMap(({archive:e,release:i})=>c.from(s(e)).pipe(c.finalize(()=>{i()}))),c.catchError(e=>c.of(this.onError(e))));return c.lastValueFrom(r)}fetchManifest({key:t,baseUrl:s}){return this.withArchiveResponse({key:t,getResponse:r=>c.from(z(r,{baseUrl:s})).pipe(c.switchMap(i=>c.from(this.onManifestSuccess({manifest:i,archive:r}))),c.map(i=>new Response(JSON.stringify(i),{status:200})))})}fetchResource({key:t,resourcePath:s,request:r}){return this.withArchiveResponse({key:t,getResponse:e=>{const i=s.replaceAll("file://","");return c.from(D(e,i)).pipe(c.map(a=>We({body:a.body??"",contentType:a.params.contentType,rangeHeader:r?.headers.get("range")})))}})}}class Pe extends X{constructor({getUriInfo:t,...s}){super(s),this.getUriInfo=t,this.fetchEventListener=this.fetchEventListener.bind(this)}fetchEventListener(t){try{const s=this.getUriInfo(t);if(!s)return;const r=E(s.baseUrl),e=t.request.url.substring(r.length+1),[i=""]=e.split("/"),o=decodeURIComponent(E(e.substring(i.length+1)));e.endsWith("/manifest")?t.respondWith(this.fetchManifest({key:i,baseUrl:`${r}/${i}/`})):t.respondWith(this.fetchResource({key:i,resourcePath:o,request:t.request}))}catch(s){t.respondWith(new Response(String(s),{status:500}))}}}m.ServiceWorkerStreamer=Pe,m.Streamer=X,m.configure=Y,m.createArchiveFromArrayBufferList=V,m.createArchiveFromJszip=G,m.createArchiveFromLibArchive=H,m.createArchiveFromText=J,m.createArchiveFromUrls=K,m.generateManifestFromArchive=z,m.generateResourceFromArchive=D,m.getArchiveOpfInfo=L,m.getUriBasePath=C,m.getUriBasename=w,m.removeTrailingSlash=E,m.sortByTitleComparator=S,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
34
+ `,r=e.map(o=>({dir:!1,basename:w(o),encodingFormat:m.detectMimeTypeFromName(o),uri:o,size:100/e.length,blob:async()=>(await fetch(o)).blob(),string:async()=>""}));return{filename:"",records:[{dir:!1,basename:"content.opf",uri:"content.opf",size:0,blob:async()=>new Blob,string:async()=>i},...r],close:()=>Promise.resolve()}},ae=({enableReport:e}={})=>{h.enable(!!e)},R=e=>{const i=Object.values(e.records).filter(r=>!r.dir).find(r=>r.uri.endsWith(".opf"));return{data:i,basePath:i?.uri.substring(0,i.uri.lastIndexOf("/"))||""}},C=e=>e.toLowerCase().endsWith(".opf"),W=e=>e.records.some(t=>!t.dir&&(C(t.basename)||C(t.uri))),N=({baseUrl:e="",resourcePath:t})=>{if(!e&&/^https?:\/\//.test(t))return encodeURI(t);const i=e?`${e}${e.endsWith("/")?"":"/"}`:"file://";return encodeURI(`${i}${t}`)},ce=2e3,O=e=>{const t=Number.parseInt(e,10);if(Number.isFinite(t)&&!(t<0||t>ce))return t},de=e=>{const t=/(?:^|[\s._(-]|\[)p\s*(\d{1,5})\s*[-_]\s*(?:p\s*)?(\d{1,5})(?=$|[^\d])/i.exec(e);return t||/(?:^|[\s._(]|\[)(0\d{1,4})\s*[-_]\s*(0\d{1,4})(?=$|[^\d])/i.exec(e)},le=e=>{const t=e.replace(/\.[^.]+$/,""),i=de(t);if(!i)return;const[,r,n]=i;if(r===void 0||n===void 0)return;const o=O(r),s=O(n);if(!(o===void 0||s===void 0)&&s===o+1)return{firstPageLabel:r,secondPageLabel:n}},k="__prose-reader__/page-spread",_="application/xhtml+xml",pe=new Set(["image/jpg","image/jpeg","image/png","image/webp"]),B=e=>e===void 0?!1:pe.has(e),ue=e=>encodeURIComponent(e),me=({cropSide:e,originalUri:t})=>`${k}/${ue(t)}/${e}.xhtml`,fe=e=>e==="left"?{pageSpreadLeft:!0,pageSpreadRight:void 0}:{pageSpreadLeft:void 0,pageSpreadRight:!0},he=e=>e==="rtl"?["right","left"]:["left","right"],U=({baseUrl:e,cropSide:t,label:i,originalSpineItem:r,originalUri:n,progressionWeight:o})=>{const s=me({cropSide:t,originalUri:n});return{...r,id:`${r.id}.${i}`,href:N({baseUrl:e,resourcePath:s}),mediaType:_,progressionWeight:o,renditionLayout:"pre-paginated",...fe(t)}},z=({href:e,id:t,mediaType:i})=>({href:e,id:t,mediaType:i}),ge=({archive:e,baseUrl:t,spineItem:i})=>{const r=[i.href,ye(i.href)],n=new Set(r.flatMap(o=>be(o,t)));return e.records.find(o=>!o.dir&&n.has(o.uri))},ye=e=>{try{return decodeURI(e)}catch{return e}},ve=e=>e.endsWith("/")?e:`${e}/`,be=(e,t)=>{const i=[e];if(e.startsWith("file://")&&i.push(e.slice(7)),t){const r=ve(t);e.startsWith(r)&&i.push(e.slice(r.length))}return i},we=e=>m.parseContentType(e?.encodingFormat??"")||m.detectMimeTypeFromName(e?.basename??""),$e=e=>m.detectMimeTypeFromName(e.uri)||m.detectMimeTypeFromName(e.basename),Se=e=>{if(e===void 0||e.dir)return!1;const t=$e(e);return B(t)?B(we(e)):!1},Fe=({archive:e,baseUrl:t})=>async i=>{if(W(e))return i;const r=[],n=i.spineItems.flatMap(o=>{const s=ge({archive:e,baseUrl:t,spineItem:o});if(!Se(s))return[o];const a=le(s.basename);if(a===void 0)return[o];const[d,p]=he(i.readingDirection),u=o.progressionWeight!==void 0?o.progressionWeight/2:void 0,g=U({baseUrl:t,cropSide:d,label:a.firstPageLabel,originalSpineItem:o,originalUri:s.uri,progressionWeight:u}),v=U({baseUrl:t,cropSide:p,label:a.secondPageLabel,originalSpineItem:o,originalUri:s.uri,progressionWeight:u});return r.push(z(g),z(v)),[g,v]});return r.length===0?i:{...i,spineItems:n.map((o,s)=>({...o,index:s})),items:[...i.items,...r]}};async function D(e){const{data:t,basePath:i}=R(e)||{};if(!t||t.dir)return;const r=await t.string();return{opf:y.parseOpf(r),basePath:i}}const Ae=y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),Te=({archive:e})=>async t=>{const i=e.records.find(n=>!n.dir&&n.basename.toLowerCase()===Ae);if(!i||i.dir)return t;const r=await i.string();try{const n=y.parseAppleDisplayOptionsXml(r),{renditionLayout:o}=y.resolveArchiveMetadata(n);return{...t,renditionLayout:t.renditionLayout??o}}catch(n){return console.error(`Unable to parse ${y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME} for content
35
+ `,r),console.error(n),t}},x=y.COMIC_INFO_FILENAME.toLowerCase(),Ie=({archive:e})=>async t=>{const i=e.records.find(o=>o.basename.toLowerCase()===x&&!o.dir);if(!i||i.dir)return t;const r={...t,spineItems:t.spineItems.filter(o=>!o.id.toLowerCase().endsWith(x)).map((o,s,a)=>({...o,progressionWeight:1/a.length}))},n=await i.string();try{const o=y.parseComicInfo(n),s=y.resolveArchiveMetadata(o);return{...r,readingDirection:s.readingDirection??"ltr"}}catch(o){return console.error(`Unable to parse ${y.COMIC_INFO_FILENAME} for content
36
+ `,n),console.error(o),r}},Re=({archive:e,baseUrl:t})=>async()=>{const i=Object.values(e.records).filter(r=>!r.dir);return{filename:e.filename,title:e.records.find(({dir:r})=>r)?.basename.replace(/\/$/,"")||e.filename,renditionLayout:void 0,renditionSpread:"auto",readingDirection:"ltr",spineItems:i.filter(r=>!r.basename.endsWith(".db")).map((r,n)=>({id:`${n}.${r.basename}`,index:n,href:N({baseUrl:t,resourcePath:r.uri}),renditionLayout:void 0,progressionWeight:1/i.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:r.encodingFormat})),items:i.map((r,n)=>({id:`${n}.${r.basename}`,href:encodeURI(`${t}${r.uri}`)}))}},X=async({archive:e,archiveOpf:t})=>{if(!t)return[];const{opf:i,basePath:r}=t,{spineRows:n}=i;return e.records.filter(s=>n.find(a=>r?`${r}/${a.href}`===s.uri:`${a.href}`===s.uri))},V=(e,t,i)=>{const{basePath:r}=R(t)||{};return e.map(n=>{const o=n.href,s=i?.(o)??"";return{href:r?`${s}${r}/${o}`:`${s}${o}`,id:n.id,mediaType:n.mediaType}})},Le=e=>{const t=e?.trim();return t==="scrolled-continuous"||t==="scrolled-doc"||t==="paginated"||t==="auto"?t:"auto"},Ee=e=>{const t=e?.trim();if(t==="none"||t==="landscape"||t==="portrait"||t==="both"||t==="auto")return t},Pe=e=>{const t=e?.trim();if(t==="cover"||t==="title-page"||t==="copyright-page"||t==="text")return t},Me=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(!i)return r;const{opf:n,basePath:o}=i,s=y.resolveArchiveMetadata(n);h.groupCollapsed(...h.getGroupArgs("OPF parsed")),h.log("opf",n),h.groupEnd();const a=n.renditionLayoutMeta?.trim(),d=a==="reflowable"||a==="pre-paginated"?a:s.renditionLayout,p=n.title?.trim()||e.records.find(({dir:l})=>l)?.basename||"",u=s.readingDirection??"ltr",v=(await X({archive:e,archiveOpf:i})).reduce((l,F)=>F.size+l,0),$=n.guide,S=[];for(const l of $){const F=Pe(l.type);F!==void 0&&S.push({href:l.href,title:l.title,type:F})}return{filename:e.filename,renditionLayout:d,renditionFlow:Le(n.renditionFlowMeta),renditionSpread:Ee(n.renditionSpreadMeta),title:p,readingDirection:u,spineItems:n.spineRows.map((l,F)=>{const b=e.records.find(P=>P.uri.endsWith(l.href))?.size||0,A=t||(/^https?:\/\//.test(l.href)?"":"file://");return{id:l.id,index:F,href:l.href.startsWith("https://")?l.href:o?`${A}${o}/${l.href}`:`${A}${l.href}`,renditionLayout:l.renditionLayout??d,progressionWeight:b/v,pageSpreadLeft:l.pageSpreadLeft,pageSpreadRight:l.pageSpreadRight,mediaType:l.mediaType}}),items:V(n.manifestItems,e,l=>/^https?:\/\//.test(l)?"":t||"file://"),guide:S.length>0?S:void 0}},Ce=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="viewport");return!!(t&&t.attr.name==="viewport")},We=e=>e.reduce(async(t,i)=>{if(!await t||!m.isXmlBasedMimeType({mimeType:i.encodingFormat,uri:i.uri}))return!1;const n=i.dir?null:await i.string();return n?Ce(new T.XmlDocument(n)):!1},Promise.resolve(!0)),Ne=({archive:e,archiveOpf:t})=>async i=>{if(i.renditionLayout==="reflowable"&&i.spineItems.every(n=>n.renditionLayout==="reflowable")){const n=await X({archive:e,archiveOpf:t});if(await We(n))return{...i,spineItems:i.spineItems.map(s=>({...s,renditionLayout:"pre-paginated"})),renditionLayout:"pre-paginated"}}return i},Oe=async e=>{let t;return await Promise.all(e.records.map(async i=>{if(i.dir||!i.uri.endsWith(y.KOBO_DISPLAY_OPTIONS_FILENAME))return;const r=await i.string();try{const{renditionLayout:n}=y.parseKoboXml(r);n&&(t=n)}catch(n){console.error(`Unable to parse ${y.KOBO_DISPLAY_OPTIONS_FILENAME} for content
37
+ `,r),console.error(n)}})),{kind:"kobo",...t!==void 0?{renditionLayout:t}:{}}},ke=({archive:e})=>async t=>{const i=await Oe(e),{renditionLayout:r}=y.resolveArchiveMetadata(i);return{...t,renditionLayout:t.renditionLayout??r}},_e=({archive:e})=>async t=>W(e)?t:{...t,spineItems:t.spineItems.map(r=>{const n=e.records.find(s=>decodeURI(r.href).endsWith(s.uri)),o=m.parseContentType(n?.encodingFormat??"")||m.detectMimeTypeFromName(n?.basename??"");return{...r,renditionLayout:o&&m.isMediaContentMimeType(o)?"pre-paginated":r.renditionLayout}})},H=e=>e?e.children.map(t=>t instanceof T.XmlTextNode?t.text:t instanceof T.XmlElement?H(t):"").join("").trim():"",Be=e=>y.tokenizeXmlSpaceSeparatedList(e.properties).includes("nav"),G=(e,{basePath:t,baseUrl:i})=>{const r={contents:[],path:"",href:"",title:""};let n=e.childNamed("span")||e.childNamed("a");r.title=(n?.attr.title||n?.val.trim()||H(n))??"";let o=n?.name;o!=="a"&&(n=e.descendantWithPath(`${o}.a`),n&&(o=n.name.toLowerCase())),o==="a"&&n?.attr.href&&(r.path=m.urlJoin(t,n.attr.href),r.href=m.urlJoin(i,t,n.attr.href));const s=e.childNamed("ol");if(s){const a=s.childrenNamed("li");a&&a.length>0&&(r.contents=a.map(d=>G(d,{basePath:t,baseUrl:i})))}return r},Ue=(e,{basePath:t,baseUrl:i})=>{const r=[];let n;return e.descendantWithPath("body.nav.ol")?n=e.descendantWithPath("body.nav.ol")?.children:e.descendantWithPath("body.section.nav.ol")&&(n=e.descendantWithPath("body.section.nav.ol")?.children),n&&n.length>0&&n.filter(o=>o.name==="li").forEach(o=>{r.push(G(o,{basePath:t,baseUrl:i}))}),r},ze=async(e,t,{baseUrl:i})=>{const r=e.manifestItems.find(Be);if(r?.href){const n=Object.values(t.records).find(o=>o.uri.endsWith(r.href));if(n&&!n.dir){const o=new T.XmlDocument(await n.string()),s=M(n.uri);return Ue(o,{basePath:s,baseUrl:i})}}},q=(e,{opfBasePath:t,baseUrl:i,prefix:r})=>{const n=e?.childNamed(`${r}content`)?.attr.src||"",o={title:e?.descendantWithPath(`${r}navLabel.${r}text`)?.val||"",path:m.urlJoin(t,n),href:m.urlJoin(i,t,n),contents:[]},s=e.childrenNamed(`${r}navPoint`);return s&&s.length>0&&(o.contents=s.map(a=>q(a,{opfBasePath:t,baseUrl:i,prefix:r}))),o},De=(e,{opfBasePath:t,baseUrl:i})=>{const r=[],n=e.name;let o="";return n.indexOf(":")!==-1&&(o=`${n.split(":")[0]}:`),e.childNamed(`${o}navMap`)?.childrenNamed(`${o}navPoint`).forEach(s=>{r.push(q(s,{opfBasePath:t,baseUrl:i,prefix:o}))}),r},xe=async({opf:e,opfBasePath:t,baseUrl:i,archive:r})=>{const n=e.spineTocIdref;if(n){const o=e.manifestItems.find(s=>s.id===n);if(o){const s=`${t}${t===""?"":"/"}${o.href}`,a=Object.values(r.records).find(d=>d.uri.endsWith(s));if(a&&!a.dir){const d=new T.XmlDocument(await a.string());return De(d,{opfBasePath:t,baseUrl:i})}}}},Xe=async(e,t,{baseUrl:i})=>{const{basePath:r}=R(t)||{},n=await ze(e,t,{baseUrl:i});if(n)return n;const o=await xe({opf:e,opfBasePath:r??"",archive:t,baseUrl:i});if(o)return o},Ve=e=>e.replace(/\.[^.]+$/,"").replace(/[_-]/g," ").replace(/\s+/g," ").trim(),He=(e,t)=>{if(!(e.spineItems.length===0||!e.spineItems.every(r=>(m.parseContentType(r.mediaType??"")||m.detectMimeTypeFromName(r.href))?.startsWith("audio/"))))return e.spineItems.map(r=>{const n=t.records.find(o=>!o.dir&&decodeURI(r.href).endsWith(o.uri));return{title:Ve(n?.basename??r.href),href:r.href,path:n?.uri??r.href,contents:[]}})},Ge=(e,{baseUrl:t})=>{const i=[...e.records].sort((n,o)=>I(n.uri,o.uri)),r=(n,o,s,a,d)=>{const p=n.find(v=>v.title===o),[u,...g]=s;return p?u?[...n.filter($=>$!==p),{...p,contents:[...p.contents,...r(p.contents,u,g,a,d)]}]:p.path.split("/").length>d.split("/").length?[...n.filter($=>$!==p),{...p,path:d,href:a}]:n:u?[...n,{contents:r([],u,g,a,d),href:a,path:d,title:o}]:[...n,{contents:[],href:a,path:d,title:o}]};return i.reduce((n,o)=>{if(o.dir)return n;const s=o.uri.split("/").slice(0,-1),[a,...d]=s;if(!a)return n;const p=m.urlJoin(t,encodeURI(o.uri)).replace(/\/$/,""),u=o.uri.replace(/\/$/,"");return r(n,a,d,p,u)},[])},qe=async(e,t,{baseUrl:i,archiveOpf:r})=>{if(r)return await Xe(r.opf,e,{baseUrl:i})||[];const n=He(t,e);if(n)return n;const o=Ge(e,{baseUrl:i});if(o.length!==0)return o},Je=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(r.nav)return r;const n=await qe(e,r,{baseUrl:t,archiveOpf:i});return n?{...r,nav:{toc:n}}:r},Ke=e=>e?e.endsWith("/")?e:`${e}/`:"",J=async(e,{baseUrl:t=""}={})=>{const i=await D(e),r=Ke(t),n=[Me({archive:e,baseUrl:r,archiveOpf:i}),Ie({archive:e}),Te({archive:e}),_e({archive:e}),Fe({archive:e,baseUrl:r}),Ne({archive:e,archiveOpf:i}),ke({archive:e}),Je({archive:e,baseUrl:r,archiveOpf:i})];try{const o=Re({archive:e,baseUrl:r})(),s=await n.reduce(async(a,d)=>await d(await a),o);if(h.log("Generated manifest",s),process.env.NODE_ENV==="development"&&h.isEnabled()){const a=JSON.stringify(s,null,2);h.groupCollapsed(...h.getGroupArgs("Generated manifest")),h.log(`
38
+ ${a}`),h.groupEnd()}return s}catch(o){throw h.error(o),o}},E=new WeakMap,Ye=e=>{try{return decodeURIComponent(e)}catch{return}},Qe=e=>{const t=e.indexOf(`${k}/`);if(t<0)return;const r=e.slice(t).split("/"),n=r[2],o=r[3];if(r.length!==4||r[0]!=="__prose-reader__"||r[1]!=="page-spread"||n===void 0||o===void 0)return;const s=o.split(".")[0];if(s!=="left"&&s!=="right")return;const a=Ye(n);if(a!==void 0)return{originalUri:a,cropSide:s}},Ze=({cropSide:e,imageHeight:t,imageWidth:i})=>{const r=Math.floor(i/2),n=i-r;return e==="left"?{x:0,width:r,height:t}:{x:r,width:n,height:t}},je=e=>/^https?:\/\//.test(e)?e:`../../../${encodeURI(e)}`,et=async e=>{if(typeof createImageBitmap!="function")throw new Error("Page spread XHTML generation requires createImageBitmap");const t=await createImageBitmap(e);try{return{height:t.height,width:t.width}}finally{t.close()}},tt=({cropSide:e,imageDimensions:t,originalUri:i})=>{if(t.width<2)throw new Error("Page spread image is too narrow to split");const r=Ze({cropSide:e,imageHeight:t.height,imageWidth:t.width});return`<?xml version="1.0" encoding="UTF-8"?>
39
+ <html xmlns="http://www.w3.org/1999/xhtml">
40
+ <head>
41
+ <meta name="viewport" content="width=${r.width}, height=${r.height}" />
42
+ <style>
43
+ html,
44
+ body {
45
+ width: ${r.width}px;
46
+ height: ${r.height}px;
47
+ margin: 0;
48
+ overflow: hidden;
49
+ }
50
+
51
+ img {
52
+ display: block;
53
+ width: ${t.width}px;
54
+ height: ${t.height}px;
55
+ max-width: none;
56
+ transform: translateX(-${r.x}px);
57
+ user-select: none;
58
+ -webkit-user-drag: none;
59
+ }
60
+ </style>
61
+ </head>
62
+ <body>
63
+ <img src="${m.escapeXmlAttributeValue(je(i))}" alt="" />
64
+ </body>
65
+ </html>`},nt=async({archive:e,resourcePath:t})=>{const i=Qe(t);if(i===void 0)return;const r=e.records.find(a=>a.uri===i.originalUri&&!a.dir);if(r===void 0||r.dir)throw new Error(`no source file found for virtual page spread resourcePath:${t}`);const n=E.get(e)??new Map;E.has(e)||E.set(e,n);const o=n.get(i.originalUri)??await et(await r.blob());return n.set(i.originalUri,o),{body:tt({cropSide:i.cropSide,imageDimensions:o,originalUri:i.originalUri}),params:{contentType:_}}},rt=({archive:e,resourcePath:t})=>async i=>{const r=await nt({archive:e,resourcePath:t});return r===void 0?i:{...i,...r,params:{...i.params,...r.params}}},it=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="calibre:cover");return!!(t&&t.attr.name==="calibre:cover")},ot=e=>e.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(t=>t.attr.width==="100%"&&t.attr.preserveAspectRatio==="none"),st=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const n=typeof i.body=="string"?i.body:await r.string(),o=new T.XmlDocument(n);if(it(o)){const s=ot(o);return s&&delete s.attr.preserveAspectRatio,{...i,body:o?.toString()}}}return i},at=({archive:e,resourcePath:t})=>async i=>st({archive:e,resourcePath:t})(i),ct=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".css")){const o=(typeof i.body=="string"?i.body:await r.string()).replaceAll("-webkit-writing-mode","writing-mode");return{...i,body:o}}return i},dt=async(e,t)=>{const i=await D(e);if(i){const{opf:r}=i,n=V(r.manifestItems,e,()=>"");if(n.find(s=>t.endsWith(s.href))?.mediaType)return{mediaType:n.find(s=>t.endsWith(s.href))?.mediaType}}return{mediaType:lt(t)}},lt=e=>{if(e.endsWith(".css"))return"text/css; charset=UTF-8";if(e.endsWith(".jpg"))return"image/jpg";if(e.endsWith(".xhtml"))return"application/xhtml+xml";if(e.endsWith(".mp4"))return"video/mp4";if(e.endsWith(".svg"))return"image/svg+xml"},pt=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(o=>o.uri===t&&!o.dir);if(!r||r.dir)return i;const n=await dt(e,t);return{...i,params:{...i.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...n.mediaType&&{contentType:n.mediaType}}}},K=["div","span","p","a","li","ul","ol","h1","h2","h3","h4","h5","h6","table","tr","td","th","thead","tbody","tfoot","section","article","header","footer","nav","aside","main","figure","figcaption","blockquote","pre","code","form","textarea","select","option","button","label","fieldset","legend","caption","dl","dt","dd","iframe","video","audio","canvas","script","style"],ut=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const n=typeof i.body=="string"?i.body:await r.string();if(!new RegExp(`<(${K.join("|")})[\\s/>]`,"i").test(n))return i;const s=new RegExp(`<(${K.join("|")})(\\s[^>]*)?\\s*/>`,"gi"),a=n.replace(s,(d,p,u="")=>`<${p} ${u.trim()}></${p}>`);return{...i,body:a}}return i},Y=async(e,t)=>{const i={params:{}},r=[rt({archive:e,resourcePath:t}),pt({archive:e,resourcePath:t}),ut({archive:e,resourcePath:t}),ct({archive:e,resourcePath:t}),at({archive:e,resourcePath:t})];try{const n=await r.reduce(async(s,a)=>await a(await s),Promise.resolve(i));if(h.log("Generated resource",t,n),n.body!==void 0)return n;const o=Object.values(e.records).find(s=>s.uri===t&&!s.dir);if(!o||o.dir)throw new Error(`no file found for resourcePath:${t}`);return{...n,body:await o.blob()}}catch(n){throw h.error(n),n}};class mt{constructor(t){this.cleanArchiveAfter=t,this.state$=new c.BehaviorSubject({status:"idle",locks:0})}update(t){this.state$.next({...this.state$.getValue(),...t})}get locks$(){return this.state$.pipe(c.map(({locks:t})=>t))}get state(){return this.state$.getValue()}get isUnlocked$(){return this.locks$.pipe(c.map(t=>t<=0),c.distinctUntilChanged(),c.shareReplay())}get overTTL$(){return this.isUnlocked$.pipe(c.switchMap(t=>t?this.cleanArchiveAfter===1/0?c.NEVER:c.timer(this.cleanArchiveAfter):c.NEVER))}}const ft=({getArchive:e,cleanArchiveAfter:t=300*1e3})=>{const i=new c.Subject,r=new c.Subject,n=new c.Subject,o={},s=i.pipe(c.mergeMap(p=>{const u=o[p];if(!u||u.state.status!=="idle")return c.EMPTY;let g=!1;const v=b=>{h.debug(`Cleaning up archive with key: ${b}`);const A=o[b];delete o[b],g||(A?.state.archive?.close(),g=!0)};u.update({status:"loading"});const $=u.locks$,S=u.isUnlocked$,l=$.pipe(c.pairwise(),c.filter(([b,A])=>A>b),c.startWith(!0));return c.from(e(p)).pipe(c.tap(b=>{u.update({archive:b,status:"success"})}),c.catchError(b=>(v(p),u.update({status:"error",error:b}),c.EMPTY)),c.switchMap(()=>{const b=l.pipe(c.switchMap(()=>n),c.switchMap(()=>S),c.filter(P=>P));return c.merge(b,u.overTTL$).pipe(c.first(),c.tap(()=>{v(p)}))}))}),c.takeUntil(r)),a=p=>{let u=!1;const g=o[p]??new mt(t);o[p]=g,g.update({locks:g.state.locks+1});const v=()=>{u||(u=!0,g.update({locks:g.state.locks-1}))};i.next(p);const $=g.state$.pipe(c.map(({archive:l})=>l),c.filter(l=>!!l)),S=g.state$.pipe(c.tap(({error:l})=>{if(l)throw l}),c.ignoreElements());return c.merge($,S).pipe(c.first(),c.map(l=>({archive:l,release:v})),c.catchError(l=>{throw v(),l}))},d=()=>{n.next()};return s.subscribe(),{access:a,purge:d,_archives:o}},Q=e=>e?/^\d+$/.test(e)?{valid:!0,value:Number.parseInt(e,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},ht=e=>{if(!e.toLowerCase().startsWith("bytes="))return{kind:"missing"};const t=e.slice(6).trim();if(!t)return{kind:"invalid"};if(t.includes(","))return{kind:"multi"};const i=/^(\d*)-(\d*)$/.exec(t);if(!i)return{kind:"invalid"};const[,r="",n=""]=i,o=Q(r.trim()),s=Q(n.trim());return!o.valid||!s.valid?{kind:"invalid"}:{kind:"single",start:o.value,end:s.value}},gt=e=>{if(e instanceof Blob)return{size:e.size,slice:(i,r)=>{const n=e.slice(i,r);return{content:n,length:n.size}}};const t=new TextEncoder().encode(e);return{size:t.byteLength,slice:(i,r)=>{const n=t.slice(i,r);return{content:n,length:n.byteLength}}}},yt=({body:e,contentType:t,rangeHeader:i})=>{const r=new Headers;if(t&&r.set("Content-Type",t),r.set("Accept-Ranges","bytes"),!i)return e instanceof Blob&&r.set("Content-Length",String(e.size)),new Response(e,{status:200,headers:r});const n=ht(i);if(n.kind==="missing"||n.kind==="multi")return e instanceof Blob&&r.set("Content-Length",String(e.size)),new Response(e,{status:200,headers:r});const o=gt(e),s=o.size;if(n.kind==="invalid")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});let a=n.start,d=n.end;if(a===void 0&&d===void 0)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});if(a===void 0){const u=Math.min(d??0,s);a=Math.max(0,s-u),d=s-1}else(d===void 0||d>=s)&&(d=s-1);if(a<0||d<0||a>=s||d>=s||a>d)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});const p=o.slice(a,d+1);return r.set("Content-Length",String(p.length)),r.set("Content-Range",`bytes ${a}-${d}/${s}`),new Response(p.content,{status:206,headers:r})},Z="file://",vt=/^https?:\/\//,bt=e=>{try{return decodeURIComponent(e)}catch{return e}},j=e=>e.startsWith(Z)?e.slice(Z.length):e,wt=e=>{const t=j(e);return vt.test(t)?t:j(bt(t))};class ee{constructor({onError:t,onManifestSuccess:i,...r}){this.onError=n=>(console.error(n),new Response(String(n),{status:500})),this.archiveLoader=ft(r),this.onManifestSuccess=i??(({manifest:n})=>Promise.resolve(n)),this.onError=t??this.onError}prune(){this.archiveLoader.purge()}accessArchive(t){return this.lastAccessedKey!==void 0&&this.lastAccessedKey!==t&&this.archiveLoader.purge(),this.lastAccessedKey=t,this.archiveLoader.access(t)}accessArchiveWithoutLock(t){return this.accessArchive(t).pipe(c.map(({archive:i,release:r})=>(r(),i)))}withArchiveResponse({key:t,getResponse:i}){const r=this.accessArchive(t).pipe(c.mergeMap(({archive:n,release:o})=>c.from(i(n)).pipe(c.finalize(()=>{o()}))),c.catchError(n=>c.of(this.onError(n))));return c.lastValueFrom(r)}fetchManifest({key:t,baseUrl:i}){return this.withArchiveResponse({key:t,getResponse:r=>c.from(J(r,{baseUrl:i})).pipe(c.switchMap(o=>c.from(this.onManifestSuccess({manifest:o,archive:r}))),c.map(o=>new Response(JSON.stringify(o),{status:200})))})}fetchResource({key:t,resourcePath:i,request:r}){return this.withArchiveResponse({key:t,getResponse:n=>{const o=wt(i);return c.from(Y(n,o)).pipe(c.map(a=>yt({body:a.body??"",contentType:a.params.contentType,rangeHeader:r?.headers.get("range")})))}})}}class $t extends ee{constructor({getUriInfo:t,...i}){super(i),this.getUriInfo=t,this.fetchEventListener=this.fetchEventListener.bind(this)}fetchEventListener(t){try{const i=this.getUriInfo(t);if(!i)return;const r=L(i.baseUrl),n=t.request.url.substring(r.length+1),[o=""]=n.split("/"),s=L(n.substring(o.length+1));n.endsWith("/manifest")?t.respondWith(this.fetchManifest({key:o,baseUrl:`${r}/${o}/`})):t.respondWith(this.fetchResource({key:o,resourcePath:s,request:t.request}))}catch(i){t.respondWith(new Response(String(i),{status:500}))}}}f.ServiceWorkerStreamer=$t,f.Streamer=ee,f.configure=ae,f.createArchiveFromArrayBufferList=te,f.createArchiveFromJszip=re,f.createArchiveFromLibArchive=ie,f.createArchiveFromText=oe,f.createArchiveFromUrls=se,f.generateManifestFromArchive=J,f.generateResourceFromArchive=Y,f.getArchiveOpfInfo=R,f.getUriBasePath=M,f.getUriBasename=w,f.removeTrailingSlash=L,f.sortByTitleComparator=I,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
39
66
  //# sourceMappingURL=index.umd.cjs.map