@prose-reader/streamer 1.303.0 → 1.305.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,5 @@
1
- (function(p,h){typeof exports=="object"&&typeof module<"u"?h(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"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p["prose-streamer"]={},p.shared,p.archiveParser,p.xmldoc,p.rxjs))})(this,(function(p,h,y,T,c){"use strict";const S=(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},A=e=>e.substring(e.lastIndexOf("/")+1)||e,E=e=>e.endsWith("/")?e.slice(0,-1):e,M=e=>{const t=e.lastIndexOf("/");return t>=0?e.substring(0,t):""},Z=async(e,{orderByAlpha:t,name:i,encodingFormat:r}={})=>{let n=e;return t&&(n=n.slice().sort((o,s)=>S(o.name,s.name))),{filename:i||"",encodingFormat:r,records:n.map(o=>{const s=o.size,a=A(o.name);return o.isDir?{dir:!0,basename:a,uri:o.name,size:s}:{dir:o.isDir,basename:a,encodingFormat:h.detectMimeTypeFromName(o.name),uri:o.name,blob:async()=>new Blob([await o.data()],{type:h.detectMimeTypeFromName(o.name)??""}),string:async()=>{const d=await o.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(d)))},size:s}}),close:()=>Promise.resolve()}},g=h.Report.namespace("@prose-reader/streamer",!1,{color:"#ffae42"}),Q=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,l=n+(d?"└── ":"├── "),f=n+(d?" ":"│ "),m=r[o];return m&&Object.keys(m).length>0?`${l}${o}/
2
- ${i(m,f)}`:`${l}${o}`}).join(`
3
- `);return i(t)},j=async(e,{orderByAlpha:t,name:i,encodingFormat:r}={})=>{let n=Object.values(e.files);t&&(n=n.slice().sort((s,a)=>S(s.name,a.name)));const o={filename:i||"",encodingFormat:r,records:n.map(s=>{const a=s._data.uncompressedSize,d=A(s.name);return s.dir?{dir:!0,basename:d,uri:s.name,size:a}:{dir:!1,basename:A(s.name),uri:s.name,encodingFormat:h.detectMimeTypeFromName(s.name),blob:()=>s.async("blob"),string:()=>s.async("string"),...s.internalStream&&{stream:s.internalStream},size:s._data.uncompressedSize}}),close:()=>Promise.resolve()};if(g.log("Generated archive",o),process.env.NODE_ENV==="development"&&g.isEnabled()){const s=Q(n.map(a=>a.name));g.groupCollapsed(...g.getGroupArgs("Archive folder structure")),g.log(`
4
- ${s}`),g.groupEnd()}return o},ee=async(e,{name:t,encodingFormat:i}={})=>{const r=await e.getFilesArray(),n={close:()=>e.close(),filename:t??"",encodingFormat:i,records:r.map(o=>({dir:!1,basename:o.file.name,encodingFormat:h.detectMimeTypeFromName(o.file.name),size:o.file.size,uri:`${o.path}${o.file.name}`,blob:async()=>await o.file.extract(),string:async()=>(await o.file.extract()).text()}))};return g.log("Generated archive",n),n},te=async(e,{mimeType:t,direction:i}={mimeType:"text/plain"})=>{const r=`
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(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`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`prose-reader-streamer`]={},e._prose_reader_shared,e._prose_reader_archive_parser,e.xmldoc,e.rxjs))})(this,function(e,t,n,r,i){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var a=(e,t)=>{let n=e.split(/(\d+)/),r=t.split(/(\d+)/);for(let e=0,t=n.length;e<t;e++)if(n[e]!==r[e])return n[e]?.match(/\d/)?(n[e]||``)-+(r[e]||``):(n[e]||``).localeCompare(r[e]||``);return 1},o=e=>e.substring(e.lastIndexOf(`/`)+1)||e,s=e=>e.endsWith(`/`)?e.slice(0,-1):e,c=e=>{let t=e.lastIndexOf(`/`);return t>=0?e.substring(0,t):``},l=async(e,{orderByAlpha:n,name:r,encodingFormat:i}={})=>{let s=e;return n&&(s=s.slice().sort((e,t)=>a(e.name,t.name))),{filename:r||``,encodingFormat:i,records:s.map(e=>{let n=e.size,r=o(e.name);return e.isDir?{dir:!0,basename:r,uri:e.name,size:n}:{dir:e.isDir,basename:r,encodingFormat:(0,t.detectMimeTypeFromName)(e.name),uri:e.name,blob:async()=>new Blob([await e.data()],{type:(0,t.detectMimeTypeFromName)(e.name)??``}),string:async()=>{let t=await e.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(t)))},size:n}}),close:()=>Promise.resolve()}},u=t.Report.namespace(`@prose-reader/streamer`,!1,{color:`#ffae42`}),d=e=>{let t={};for(let n of e){let e=n.split(`/`),r=t;for(let t=0;t<e.length;t++){let n=e[t];n!==void 0&&(r[n]||(r[n]={}),r=r[n])}}let n=(e,t=``)=>Object.keys(e).sort().map((r,i,a)=>{let o=i===a.length-1,s=t+(o?`└── `:`├── `),c=t+(o?` `:`│ `),l=e[r];return l&&Object.keys(l).length>0?`${s}${r}/\n${n(l,c)}`:`${s}${r}`}).join(`
2
+ `);return n(t)},f=async(e,{orderByAlpha:n,name:r,encodingFormat:i}={})=>{let s=Object.values(e.files);n&&(s=s.slice().sort((e,t)=>a(e.name,t.name)));let c={filename:r||``,encodingFormat:i,records:s.map(e=>{let n=e._data.uncompressedSize,r=o(e.name);return e.dir?{dir:!0,basename:r,uri:e.name,size:n}:{dir:!1,basename:o(e.name),uri:e.name,encodingFormat:(0,t.detectMimeTypeFromName)(e.name),blob:()=>e.async(`blob`),string:()=>e.async(`string`),...e.internalStream&&{stream:e.internalStream},size:e._data.uncompressedSize}}),close:()=>Promise.resolve()};if(u.log(`Generated archive`,c),process.env.NODE_ENV===`development`&&u.isEnabled()){let e=d(s.map(e=>e.name));u.groupCollapsed(...u.getGroupArgs(`Archive folder structure`)),u.log(`\n${e}`),u.groupEnd()}return c},p=async(e,{name:n,encodingFormat:r}={})=>{let i=await e.getFilesArray(),a={close:()=>e.close(),filename:n??``,encodingFormat:r,records:i.map(e=>({dir:!1,basename:e.file.name,encodingFormat:(0,t.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 u.log(`Generated archive`,a),a},m=async(e,{mimeType:t,direction:n}={mimeType:`text/plain`})=>{let r=`
5
3
  <?xml version="1.0" encoding="UTF-8"?>
6
4
  <package xmlns="http://www.idpf.org/2007/opf" version="3.0" xml:lang="ja" prefix="rendition: http://www.idpf.org/vocab/rendition/#"
7
5
  unique-identifier="ootuya-id">
@@ -12,28 +10,24 @@ ${s}`),g.groupEnd()}return o},ee=async(e,{name:t,encodingFormat:i}={})=>{const r
12
10
  <manifest>
13
11
  <item id="p01" href="p01.txt" media-type="text/plain"/>
14
12
  </manifest>
15
- <spine page-progression-direction="${i??"ltr"}">
13
+ <spine page-progression-direction="${n??`ltr`}">
16
14
  <itemref idref="p01" />
17
15
  </spine>
18
16
  </package>
19
- `;return{filename:"content.txt",encodingFormat:t,records:[{dir:!1,basename:A("generated.opf"),uri:"generated.opf",blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:A("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()}},ne=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,re=/^[A-Za-z0-9_]/,k=/^xml/i,oe=/[^A-Za-z0-9_.-]+/g,N="_",ie=e=>e.replace(/^_+|_+$/g,""),se=e=>ie(e.trim().replaceAll("/","_").replace(oe,"_")),_=e=>{if(ne.test(e)&&!k.test(e))return e;const t=se(e),i=t&&!k.test(t)?t:`${N}${t}`;return re.test(i)?i:`${N}${i}`},W=(e,t)=>{const i=_(e);if(!t.has(i))return t.add(i),i;let r=2,n=`${i}-${r}`;for(;t.has(n);)r+=1,n=`${i}-${r}`;return t.add(n),n},R=()=>{const e=new Set;return t=>W(t,e)},ae=async(e,t)=>{const i=R(),r=e.map(a=>({id:i(a),url:a})),n=`
17
+ `;return{filename:`content.txt`,encodingFormat:t,records:[{dir:!1,basename:o(`generated.opf`),uri:`generated.opf`,blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:o(`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()}},h=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,ee=/^[A-Za-z0-9_]/,g=/^xml/i,te=/[^A-Za-z0-9_.-]+/g,_=`_`,ne=e=>e.replace(/^_+|_+$/g,``),re=e=>ne(e.trim().replaceAll(`/`,`_`).replace(te,`_`)),v=e=>{if(h.test(e)&&!g.test(e))return e;let t=re(e),n=t&&!g.test(t)?t:`${_}${t}`;return ee.test(n)?n:`${_}${n}`},y=(e,t)=>{let n=v(e);if(!t.has(n))return t.add(n),n;let r=2,i=`${n}-${r}`;for(;t.has(i);)r+=1,i=`${n}-${r}`;return t.add(i),i},b=()=>{let e=new Set;return t=>y(t,e)},x=async(e,n)=>{let r=b(),i=e.map(e=>({id:r(e),url:e})),a=`
20
18
  <?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="bookid">
21
19
  <metadata>
22
- <meta property="rendition:layout">${t?.useRenditionFlow?"reflowable":"pre-paginated"}</meta>
23
- ${t?.useRenditionFlow?'<meta property="rendition:flow">scrolled-continuous</meta>':""}
20
+ <meta property="rendition:layout">${n?.useRenditionFlow?`reflowable`:`pre-paginated`}</meta>
21
+ ${n?.useRenditionFlow?`<meta property="rendition:flow">scrolled-continuous</meta>`:``}
24
22
  </metadata>
25
23
  <manifest>
26
- ${r.map(({id:a,url:d})=>{const l=h.detectMimeTypeFromName(d);return`<item id="${a}" href="${h.escapeXmlAttributeValue(d)}" media-type="${h.escapeXmlAttributeValue(l??"")}"/>`}).join(`
24
+ ${i.map(({id:e,url:n})=>{let r=(0,t.detectMimeTypeFromName)(n);return`<item id="${e}" href="${(0,t.escapeXmlAttributeValue)(n)}" media-type="${(0,t.escapeXmlAttributeValue)(r??``)}"/>`}).join(`
27
25
  `)}
28
26
  </manifest>
29
27
  <spine>
30
- ${r.map(({id:a})=>`<itemref idref="${a}" />`).join(`
28
+ ${i.map(({id:e})=>`<itemref idref="${e}" />`).join(`
31
29
  `)}
32
30
  </spine>
33
31
  </package>
34
- `,o=e.map(a=>({dir:!1,basename:A(a),encodingFormat:h.detectMimeTypeFromName(a),uri:a,size:100/e.length,blob:async()=>(await fetch(a)).blob(),string:async()=>""}));return{filename:"",records:[{dir:!1,basename:"content.opf",uri:"content.opf",size:0,blob:async()=>new Blob,string:async()=>n},...o],close:()=>Promise.resolve()}},ce=e=>!e.dir,de=y.COMIC_INFO_FILENAME.toLowerCase(),O=e=>e.records.find(t=>ce(t)&&t.basename.toLowerCase()===de),le=({enableReport:e}={})=>{g.enable(!!e)},L=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("/"))||""}};async function P(e){const{data:t,basePath:i}=L(e)||{};if(!t||t.dir)return;const r=await t.string();return{opf:y.parseOpf(r),basePath:i}}const ue=y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),pe=({archive:e})=>async t=>{const i=e.records.find(n=>!n.dir&&n.basename.toLowerCase()===ue);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}},fe=y.COMIC_INFO_FILENAME.toLowerCase(),me=({archive:e})=>async t=>{const i=O(e);if(!i)return t;const r={...t,spineItems:t.spineItems.filter(o=>!o.id.toLowerCase().endsWith(fe)).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??r.readingDirection}}catch(o){return console.error(`Unable to parse ${y.COMIC_INFO_FILENAME} for content
36
- `,n),console.error(o),r}},he=({baseUrl:e="",resourcePath:t})=>{if(!e&&/^https?:\/\//.test(t))return encodeURI(t);const i=e?`${e}${e.endsWith("/")?"":"/"}`:"file://";return encodeURI(`${i}${t}`)},ge=({archive:e,baseUrl:t})=>async()=>{const i=Object.values(e.records).filter(o=>!o.dir),r=R(),n=i.map(o=>({file:o,id:r(o.uri)}));return{filename:e.filename,title:e.records.find(({dir:o})=>o)?.basename.replace(/\/$/,"")||e.filename,renditionLayout:void 0,renditionSpread:"auto",readingDirection:void 0,spineItems:n.filter(({file:o})=>!o.basename.endsWith(".db")).map(({file:o,id:s},a)=>({id:s,index:a,href:he({baseUrl:t,resourcePath:o.uri}),renditionLayout:void 0,progressionWeight:1/i.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:o.encodingFormat})),items:n.map(({file:o,id:s})=>({id:s,href:encodeURI(`${t}${o.uri}`)}))}},z=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))},B=(e,t,i)=>{const{basePath:r}=L(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}})},ye=e=>{const t=e?.trim();return t==="scrolled-continuous"||t==="scrolled-doc"||t==="paginated"||t==="auto"?t:"auto"},be=e=>{const t=e?.trim();if(t==="none"||t==="landscape"||t==="portrait"||t==="both"||t==="auto")return t},ve=e=>{const t=e?.trim();if(t==="cover"||t==="title-page"||t==="copyright-page"||t==="text")return t},we=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(!i)return r;const{opf:n,basePath:o}=i,s=y.resolveArchiveMetadata(n);g.groupCollapsed(...g.getGroupArgs("OPF parsed")),g.log("opf",n),g.groupEnd();const a=n.renditionLayoutMeta?.trim(),d=a==="reflowable"||a==="pre-paginated"?a:s.renditionLayout,l=n.title?.trim()||e.records.find(({dir:u})=>u)?.basename||"",f=s.readingDirection??r.readingDirection,b=(await z({archive:e,archiveOpf:i})).reduce((u,F)=>F.size+u,0),v=n.guide,$=[];for(const u of v){const F=ve(u.type);F!==void 0&&$.push({href:u.href,title:u.title,type:F})}return{filename:e.filename,renditionLayout:d,renditionFlow:ye(n.renditionFlowMeta),renditionSpread:be(n.renditionSpreadMeta),title:l,readingDirection:f,spineItems:n.spineRows.map((u,F)=>{const w=e.records.find(C=>C.uri.endsWith(u.href))?.size||0,I=t||(/^https?:\/\//.test(u.href)?"":"file://");return{id:u.id,index:F,href:u.href.startsWith("https://")?u.href:o?`${I}${o}/${u.href}`:`${I}${u.href}`,renditionLayout:u.renditionLayout??d,...u.renditionFlow!==void 0?{renditionFlow:u.renditionFlow}:{},progressionWeight:w/b,pageSpreadLeft:u.pageSpreadLeft,pageSpreadRight:u.pageSpreadRight,mediaType:u.mediaType}}),items:B(n.manifestItems,e,u=>/^https?:\/\//.test(u)?"":t||"file://"),guide:$.length>0?$:void 0}},$e=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="viewport");return!!(t&&t.attr.name==="viewport")},Ae=e=>e.reduce(async(t,i)=>{if(!await t||!h.isXmlBasedMimeType({mimeType:i.encodingFormat,uri:i.uri}))return!1;const n=i.dir?null:await i.string();return n?$e(new T.XmlDocument(n)):!1},Promise.resolve(!0)),Fe=({archive:e,archiveOpf:t})=>async i=>{if(i.renditionLayout==="reflowable"&&i.spineItems.every(n=>n.renditionLayout==="reflowable")){const n=await z({archive:e,archiveOpf:t});if(await Ae(n))return{...i,spineItems:i.spineItems.map(s=>({...s,renditionLayout:"pre-paginated"})),renditionLayout:"pre-paginated"}}return i},Ie=()=>e=>({...e,readingDirection:e.readingDirection??"ltr"}),Te=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}:{}}},Se=({archive:e})=>async t=>{const i=await Te(e),{renditionLayout:r}=y.resolveArchiveMetadata(i);return{...t,renditionLayout:t.renditionLayout??r}},D=e=>e.toLowerCase().endsWith(".opf"),Le=e=>e.records.some(t=>!t.dir&&(D(t.basename)||D(t.uri))),Ee=({archive:e})=>async t=>Le(e)?t:{...t,spineItems:t.spineItems.map(r=>{const n=e.records.find(s=>decodeURI(r.href).endsWith(s.uri)),o=h.parseContentType(n?.encodingFormat??"")||h.detectMimeTypeFromName(n?.basename??"");return{...r,renditionLayout:o&&h.isMediaContentMimeType(o)?"pre-paginated":r.renditionLayout}})},U=e=>e?e.children.map(t=>t instanceof T.XmlTextNode?t.text:t instanceof T.XmlElement?U(t):"").join("").trim():"",Re=e=>y.tokenizeXmlSpaceSeparatedList(e.properties).includes("nav"),X=(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()||U(n))??"";let o=n?.name;o!=="a"&&(n=e.descendantWithPath(`${o}.a`),n&&(o=n.name.toLowerCase())),o==="a"&&n?.attr.href&&(r.path=h.urlJoin(t,n.attr.href),r.href=h.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=>X(d,{basePath:t,baseUrl:i})))}return r},Ce=(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(X(o,{basePath:t,baseUrl:i}))}),r},Me=async(e,t,{baseUrl:i})=>{const r=e.manifestItems.find(Re);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 Ce(o,{basePath:s,baseUrl:i})}}},H=(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:h.urlJoin(t,n),href:h.urlJoin(i,t,n),contents:[]},s=e.childrenNamed(`${r}navPoint`);return s&&s.length>0&&(o.contents=s.map(a=>H(a,{opfBasePath:t,baseUrl:i,prefix:r}))),o},ke=(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(H(s,{opfBasePath:t,baseUrl:i,prefix:o}))}),r},Ne=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 ke(d,{opfBasePath:t,baseUrl:i})}}}},_e=async(e,t,{baseUrl:i})=>{const{basePath:r}=L(t)||{},n=await Me(e,t,{baseUrl:i});if(n)return n;const o=await Ne({opf:e,opfBasePath:r??"",archive:t,baseUrl:i});if(o)return o},We=e=>e.replace(/\.[^.]+$/,"").replace(/[_-]/g," ").replace(/\s+/g," ").trim(),Oe=(e,t)=>{if(!(e.spineItems.length===0||!e.spineItems.every(r=>(h.parseContentType(r.mediaType??"")||h.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:We(n?.basename??r.href),href:r.href,path:n?.uri??r.href,contents:[]}})},Pe=(e,{baseUrl:t})=>{const i=[...e.records].sort((n,o)=>S(n.uri,o.uri)),r=(n,o,s,a,d)=>{const l=n.find(b=>b.title===o),[f,...m]=s;return l?f?[...n.filter(v=>v!==l),{...l,contents:[...l.contents,...r(l.contents,f,m,a,d)]}]:l.path.split("/").length>d.split("/").length?[...n.filter(v=>v!==l),{...l,path:d,href:a}]:n:f?[...n,{contents:r([],f,m,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 l=h.urlJoin(t,encodeURI(o.uri)).replace(/\/$/,""),f=o.uri.replace(/\/$/,"");return r(n,a,d,l,f)},[])},ze=async(e,t,{baseUrl:i,archiveOpf:r})=>{if(r)return await _e(r.opf,e,{baseUrl:i})||[];const n=Oe(t,e);if(n)return n;const o=Pe(e,{baseUrl:i});if(o.length!==0)return o},Be=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(r.nav)return r;const n=await ze(e,r,{baseUrl:t,archiveOpf:i});return n?{...r,nav:{toc:n}}:r},De=e=>e?e.endsWith("/")?e:`${e}/`:"",V=async(e,{baseUrl:t="",hooks:i={}}={})=>{g.log("Generating manifest from archive",e);const r=await P(e),n=De(t),o=m=>(m??[]).map(b=>b({archive:e,baseUrl:n})),s=[we({archive:e,baseUrl:n,archiveOpf:r}),me({archive:e}),pe({archive:e}),Ee({archive:e}),...o(i.content)],a=o(i.spine),d=[Fe({archive:e,archiveOpf:r}),Se({archive:e}),...o(i.presentation)],l=[Be({archive:e,baseUrl:n,archiveOpf:r}),...o(i.navigation)],f=[...s,...a,...d,...l,Ie()];try{const m=ge({archive:e,baseUrl:n})(),b=await f.reduce(async(v,$)=>await $(await v),m);if(g.log("Generated manifest",b),process.env.NODE_ENV==="development"&&g.isEnabled()){const v=JSON.stringify(b,null,2);g.groupCollapsed(...g.getGroupArgs("Generated manifest")),g.log(`
38
- ${v}`),g.groupEnd()}return b}catch(m){throw g.error(m),m}},Ue=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="calibre:cover");return!!(t&&t.attr.name==="calibre:cover")},Xe=e=>e.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(t=>t.attr.width==="100%"&&t.attr.preserveAspectRatio==="none"),He=({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(Ue(o)){const s=Xe(o);return s&&delete s.attr.preserveAspectRatio,{...i,body:o?.toString()}}}return i},Ve=({archive:e,resourcePath:t})=>async i=>He({archive:e,resourcePath:t})(i),qe=({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},Ge=async(e,t)=>{const i=await P(e);if(i){const{opf:r}=i,n=B(r.manifestItems,e,()=>"");if(n.find(s=>t.endsWith(s.href))?.mediaType)return{mediaType:n.find(s=>t.endsWith(s.href))?.mediaType}}return{mediaType:Ke(t)}},Ke=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"},Je=({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 Ge(e,t);return{...i,params:{...i.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...n.mediaType&&{contentType:n.mediaType}}}},q=["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"],xe=({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(`<(${q.join("|")})[\\s/>]`,"i").test(n))return i;const s=new RegExp(`<(${q.join("|")})(\\s[^>]*)?\\s*/>`,"gi"),a=n.replace(s,(d,l,f="")=>`<${l} ${f.trim()}></${l}>`);return{...i,body:a}}return i},G=async(e,t,{hooks:i=[]}={})=>{const r={params:{}},o=[...i.map(s=>s({archive:e,resourcePath:t})),Je({archive:e,resourcePath:t}),xe({archive:e,resourcePath:t}),qe({archive:e,resourcePath:t}),Ve({archive:e,resourcePath:t})];try{const s=await o.reduce(async(d,l)=>await l(await d),Promise.resolve(r));if(g.log("Generated resource",t,s),s.body!==void 0)return s;const a=Object.values(e.records).find(d=>d.uri===t&&!d.dir);if(!a||a.dir)throw new Error(`no file found for resourcePath:${t}`);return{...s,body:await a.blob()}}catch(s){throw g.error(s),s}};class Ye{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 Ze=({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(l=>{const f=o[l];if(!f||f.state.status!=="idle")return c.EMPTY;let m=!1;const b=w=>{g.debug(`Cleaning up archive with key: ${w}`);const I=o[w];delete o[w],m||(I?.state.archive?.close(),m=!0)};f.update({status:"loading"});const v=f.locks$,$=f.isUnlocked$,u=v.pipe(c.pairwise(),c.filter(([w,I])=>I>w),c.startWith(!0));return c.from(e(l)).pipe(c.tap(w=>{f.update({archive:w,status:"success"})}),c.catchError(w=>(b(l),f.update({status:"error",error:w}),c.EMPTY)),c.switchMap(()=>{const w=u.pipe(c.switchMap(()=>n),c.switchMap(()=>$),c.filter(C=>C));return c.merge(w,f.overTTL$).pipe(c.first(),c.tap(()=>{b(l)}))}))}),c.takeUntil(r)),a=l=>{let f=!1;const m=o[l]??new Ye(t);o[l]=m,m.update({locks:m.state.locks+1});const b=()=>{f||(f=!0,m.update({locks:m.state.locks-1}))};i.next(l);const v=m.state$.pipe(c.map(({archive:u})=>u),c.filter(u=>!!u)),$=m.state$.pipe(c.tap(({error:u})=>{if(u)throw u}),c.ignoreElements());return c.merge(v,$).pipe(c.first(),c.map(u=>({archive:u,release:b})),c.catchError(u=>{throw b(),u}))},d=()=>{n.next()};return s.subscribe(),{access:a,purge:d,_archives:o}},K=e=>e?/^\d+$/.test(e)?{valid:!0,value:Number.parseInt(e,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},Qe=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=K(r.trim()),s=K(n.trim());return!o.valid||!s.valid?{kind:"invalid"}:{kind:"single",start:o.value,end:s.value}},je=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}}}},et=({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=Qe(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=je(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 f=Math.min(d??0,s);a=Math.max(0,s-f),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 l=o.slice(a,d+1);return r.set("Content-Length",String(l.length)),r.set("Content-Range",`bytes ${a}-${d}/${s}`),new Response(l.content,{status:206,headers:r})},J="file://",tt=/^https?:\/\//,nt=e=>{try{return decodeURIComponent(e)}catch{return e}},x=e=>e.startsWith(J)?e.slice(J.length):e,rt=e=>{const t=x(e);return tt.test(t)?t:x(nt(t))};class Y{constructor({hooks:t,onError:i,onManifestSuccess:r,...n}){this.onError=o=>(console.error(o),new Response(String(o),{status:500})),this.archiveLoader=Ze(n),this.hooks=t??{},this.onManifestSuccess=r??(({manifest:o})=>Promise.resolve(o)),this.onError=i??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(V(r,{baseUrl:i,hooks:this.hooks.manifest})).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=rt(i);return c.from(G(n,o,{hooks:this.hooks.resource})).pipe(c.map(a=>et({body:a.body??"",contentType:a.params.contentType,rangeHeader:r?.headers.get("range")})))}})}}class ot extends Y{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=E(i.baseUrl),n=t.request.url.substring(r.length+1),[o=""]=n.split("/"),s=E(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}))}}}p.ServiceWorkerStreamer=ot,p.Streamer=Y,p.configure=le,p.createArchiveFromArrayBufferList=Z,p.createArchiveFromJszip=j,p.createArchiveFromLibArchive=ee,p.createArchiveFromText=te,p.createArchiveFromUrls=ae,p.createUniqueXmlSafeId=W,p.createXmlSafeId=_,p.createXmlSafeIdFactory=R,p.generateManifestFromArchive=V,p.generateResourceFromArchive=G,p.getArchiveHasComicInfo=O,p.getArchiveOpfInfo=L,p.getUriBasePath=M,p.getUriBasename=A,p.removeTrailingSlash=E,p.sortByTitleComparator=S,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
39
- //# sourceMappingURL=index.umd.cjs.map
32
+ `;return{filename:``,records:[{dir:!1,basename:`content.opf`,uri:`content.opf`,size:0,blob:async()=>new Blob,string:async()=>a},...e.map(n=>({dir:!1,basename:o(n),encodingFormat:(0,t.detectMimeTypeFromName)(n),uri:n,size:100/e.length,blob:async()=>(await fetch(n)).blob(),string:async()=>``}))],close:()=>Promise.resolve()}},S=e=>!e.dir,C=n.COMIC_INFO_FILENAME.toLowerCase(),w=e=>e.records.find(e=>S(e)&&e.basename.toLowerCase()===C),ie=({enableReport:e}={})=>{u.enable(!!e)},T=e=>{let t=Object.values(e.records).filter(e=>!e.dir).find(e=>e.uri.endsWith(`.opf`));return{data:t,basePath:t?.uri.substring(0,t.uri.lastIndexOf(`/`))||``}};async function E(e){let{data:t,basePath:r}=T(e)||{};if(!(!t||t.dir))return{opf:(0,n.parseOpf)(await t.string()),basePath:r}}var ae=n.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),oe=({archive:e})=>async t=>{let r=e.records.find(e=>!e.dir&&e.basename.toLowerCase()===ae);if(!r||r.dir)return t;let i=await r.string();try{let{renditionLayout:e}=(0,n.resolveArchiveMetadata)((0,n.parseAppleDisplayOptionsXml)(i));return{...t,renditionLayout:t.renditionLayout??e}}catch(e){return console.error(`Unable to parse ${n.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME} for content\n`,i),console.error(e),t}},se=n.COMIC_INFO_FILENAME.toLowerCase(),ce=({archive:e})=>async t=>{let r=w(e);if(!r)return t;let i={...t,spineItems:t.spineItems.filter(e=>!e.id.toLowerCase().endsWith(se)).map((e,t,n)=>({...e,progressionWeight:1/n.length}))},a=await r.string();try{let e=(0,n.resolveArchiveMetadata)((0,n.parseComicInfo)(a));return{...i,readingDirection:e.readingDirection??i.readingDirection}}catch(e){return console.error(`Unable to parse ${n.COMIC_INFO_FILENAME} for content\n`,a),console.error(e),i}},le=({baseUrl:e=``,resourcePath:t})=>{if(!e&&/^https?:\/\//.test(t))return encodeURI(t);let n=e?`${e}${e.endsWith(`/`)?``:`/`}`:`file://`;return encodeURI(`${n}${t}`)},ue=({archive:e,baseUrl:t})=>async()=>{let n=Object.values(e.records).filter(e=>!e.dir),r=b(),i=n.map(e=>({file:e,id:r(e.uri)}));return{filename:e.filename,title:e.records.find(({dir:e})=>e)?.basename.replace(/\/$/,``)||e.filename,renditionLayout:void 0,renditionSpread:`auto`,readingDirection:void 0,spineItems:i.filter(({file:e})=>!e.basename.endsWith(`.db`)).map(({file:e,id:r},i)=>({id:r,index:i,href:le({baseUrl:t,resourcePath:e.uri}),renditionLayout:void 0,progressionWeight:1/n.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:e.encodingFormat})),items:i.map(({file:e,id:n})=>({id:n,href:encodeURI(`${t}${e.uri}`)}))}},D=async({archive:e,archiveOpf:t})=>{if(!t)return[];let{opf:n,basePath:r}=t,{spineRows:i}=n;return e.records.filter(e=>i.find(t=>r?`${r}/${t.href}`===e.uri:`${t.href}`===e.uri))},O=(e,t,n)=>{let{basePath:r}=T(t)||{};return e.map(e=>{let t=e.href,i=n?.(t)??``;return{href:r?`${i}${r}/${t}`:`${i}${t}`,id:e.id,mediaType:e.mediaType}})},k=e=>{let t=e?.trim();return t===`scrolled-continuous`||t===`scrolled-doc`||t===`paginated`||t===`auto`?t:`auto`},A=e=>{let t=e?.trim();if(t===`none`||t===`landscape`||t===`portrait`||t===`both`||t===`auto`)return t},j=e=>{let t=e?.trim();if(t===`cover`||t===`title-page`||t===`copyright-page`||t===`text`)return t},M=({archive:e,baseUrl:t,archiveOpf:r})=>async i=>{if(!r)return i;let{opf:a,basePath:o}=r,s=(0,n.resolveArchiveMetadata)(a);u.groupCollapsed(...u.getGroupArgs(`OPF parsed`)),u.log(`opf`,a),u.groupEnd();let c=a.renditionLayoutMeta?.trim(),l=c===`reflowable`||c===`pre-paginated`?c:s.renditionLayout,d=a.title?.trim()||e.records.find(({dir:e})=>e)?.basename||``,f=s.readingDirection??i.readingDirection,p=(await D({archive:e,archiveOpf:r})).reduce((e,t)=>t.size+e,0),m=a.guide,h=[];for(let e of m){let t=j(e.type);t!==void 0&&h.push({href:e.href,title:e.title,type:t})}return{filename:e.filename,renditionLayout:l,renditionFlow:k(a.renditionFlowMeta),renditionSpread:A(a.renditionSpreadMeta),title:d,readingDirection:f,spineItems:a.spineRows.map((n,r)=>{let i=e.records.find(e=>e.uri.endsWith(n.href))?.size||0,a=t||(/^https?:\/\//.test(n.href)?``:`file://`);return{id:n.id,index:r,href:n.href.startsWith(`https://`)?n.href:o?`${a}${o}/${n.href}`:`${a}${n.href}`,renditionLayout:n.renditionLayout??l,...n.renditionFlow===void 0?{}:{renditionFlow:n.renditionFlow},progressionWeight:i/p,pageSpreadLeft:n.pageSpreadLeft,pageSpreadRight:n.pageSpreadRight,mediaType:n.mediaType}}),items:O(a.manifestItems,e,e=>/^https?:\/\//.test(e)?``:t||`file://`),guide:h.length>0?h:void 0}},N=e=>{let t=e.descendantWithPath(`head`)?.childrenNamed(`meta`).find(e=>e.attr.name===`viewport`);return!!(t&&t.attr.name===`viewport`)},P=e=>e.reduce(async(e,n)=>{if(!await e||!(0,t.isXmlBasedMimeType)({mimeType:n.encodingFormat,uri:n.uri}))return!1;let i=n.dir?null:await n.string();return i?N(new r.XmlDocument(i)):!1},Promise.resolve(!0)),F=({archive:e,archiveOpf:t})=>async n=>n.renditionLayout===`reflowable`&&n.spineItems.every(e=>e.renditionLayout===`reflowable`)&&await P(await D({archive:e,archiveOpf:t}))?{...n,spineItems:n.spineItems.map(e=>({...e,renditionLayout:`pre-paginated`})),renditionLayout:`pre-paginated`}:n,I=()=>e=>({...e,readingDirection:e.readingDirection??`ltr`}),L=async e=>{let t;return await Promise.all(e.records.map(async e=>{if(e.dir||!e.uri.endsWith(n.KOBO_DISPLAY_OPTIONS_FILENAME))return;let r=await e.string();try{let{renditionLayout:e}=(0,n.parseKoboXml)(r);e&&(t=e)}catch(e){console.error(`Unable to parse ${n.KOBO_DISPLAY_OPTIONS_FILENAME} for content\n`,r),console.error(e)}})),{kind:`kobo`,...t===void 0?{}:{renditionLayout:t}}},R=({archive:e})=>async t=>{let{renditionLayout:r}=(0,n.resolveArchiveMetadata)(await L(e));return{...t,renditionLayout:t.renditionLayout??r}},z=e=>e.toLowerCase().endsWith(`.opf`),B=e=>e.records.some(e=>!e.dir&&(z(e.basename)||z(e.uri))),V=({archive:e})=>async n=>B(e)?n:{...n,spineItems:n.spineItems.map(n=>{let r=e.records.find(e=>decodeURI(n.href).endsWith(e.uri)),i=(0,t.parseContentType)(r?.encodingFormat??``)||(0,t.detectMimeTypeFromName)(r?.basename??``);return{...n,renditionLayout:i&&(0,t.isMediaContentMimeType)(i)?`pre-paginated`:n.renditionLayout}})},H=e=>e?e.children.map(e=>e instanceof r.XmlTextNode?e.text:e instanceof r.XmlElement?H(e):``).join(``).trim():``,U=e=>(0,n.tokenizeXmlSpaceSeparatedList)(e.properties).includes(`nav`),W=(e,{basePath:n,baseUrl:r})=>{let i={contents:[],path:``,href:``,title:``},a=e.childNamed(`span`)||e.childNamed(`a`);i.title=(a?.attr.title||a?.val.trim()||H(a))??``;let o=a?.name;o!==`a`&&(a=e.descendantWithPath(`${o}.a`),a&&(o=a.name.toLowerCase())),o===`a`&&a?.attr.href&&(i.path=(0,t.urlJoin)(n,a.attr.href),i.href=(0,t.urlJoin)(r,n,a.attr.href));let s=e.childNamed(`ol`);if(s){let e=s.childrenNamed(`li`);e&&e.length>0&&(i.contents=e.map(e=>W(e,{basePath:n,baseUrl:r})))}return i},de=(e,{basePath:t,baseUrl:n})=>{let r=[],i;return e.descendantWithPath(`body.nav.ol`)?i=e.descendantWithPath(`body.nav.ol`)?.children:e.descendantWithPath(`body.section.nav.ol`)&&(i=e.descendantWithPath(`body.section.nav.ol`)?.children),i&&i.length>0&&i.filter(e=>e.name===`li`).forEach(e=>{r.push(W(e,{basePath:t,baseUrl:n}))}),r},fe=async(e,t,{baseUrl:n})=>{let i=e.manifestItems.find(U);if(i?.href){let e=Object.values(t.records).find(e=>e.uri.endsWith(i.href));if(e&&!e.dir)return de(new r.XmlDocument(await e.string()),{basePath:c(e.uri),baseUrl:n})}},G=(e,{opfBasePath:n,baseUrl:r,prefix:i})=>{let a=e?.childNamed(`${i}content`)?.attr.src||``,o={title:e?.descendantWithPath(`${i}navLabel.${i}text`)?.val||``,path:(0,t.urlJoin)(n,a),href:(0,t.urlJoin)(r,n,a),contents:[]},s=e.childrenNamed(`${i}navPoint`);return s&&s.length>0&&(o.contents=s.map(e=>G(e,{opfBasePath:n,baseUrl:r,prefix:i}))),o},pe=(e,{opfBasePath:t,baseUrl:n})=>{let r=[],i=e.name,a=``;return i.indexOf(`:`)!==-1&&(a=`${i.split(`:`)[0]}:`),e.childNamed(`${a}navMap`)?.childrenNamed(`${a}navPoint`).forEach(e=>{r.push(G(e,{opfBasePath:t,baseUrl:n,prefix:a}))}),r},me=async({opf:e,opfBasePath:t,baseUrl:n,archive:i})=>{let a=e.spineTocIdref;if(a){let o=e.manifestItems.find(e=>e.id===a);if(o){let e=`${t}${t===``?``:`/`}${o.href}`,a=Object.values(i.records).find(t=>t.uri.endsWith(e));if(a&&!a.dir)return pe(new r.XmlDocument(await a.string()),{opfBasePath:t,baseUrl:n})}}},he=async(e,t,{baseUrl:n})=>{let{basePath:r}=T(t)||{},i=await fe(e,t,{baseUrl:n});if(i)return i;let a=await me({opf:e,opfBasePath:r??``,archive:t,baseUrl:n});if(a)return a},ge=e=>e.replace(/\.[^.]+$/,``).replace(/[_-]/g,` `).replace(/\s+/g,` `).trim(),_e=(e,n)=>{if(e.spineItems.length!==0&&e.spineItems.every(e=>((0,t.parseContentType)(e.mediaType??``)||(0,t.detectMimeTypeFromName)(e.href))?.startsWith(`audio/`)))return e.spineItems.map(e=>{let t=n.records.find(t=>!t.dir&&decodeURI(e.href).endsWith(t.uri));return{title:ge(t?.basename??e.href),href:e.href,path:t?.uri??e.href,contents:[]}})},ve=(e,{baseUrl:n})=>{let r=[...e.records].sort((e,t)=>a(e.uri,t.uri)),i=(e,t,n,r,a)=>{let o=e.find(e=>e.title===t),[s,...c]=n;return o?s?[...e.filter(e=>e!==o),{...o,contents:[...o.contents,...i(o.contents,s,c,r,a)]}]:o.path.split(`/`).length>a.split(`/`).length?[...e.filter(e=>e!==o),{...o,path:a,href:r}]:e:s?[...e,{contents:i([],s,c,r,a),href:r,path:a,title:t}]:[...e,{contents:[],href:r,path:a,title:t}]};return r.reduce((e,r)=>{if(r.dir)return e;let[a,...o]=r.uri.split(`/`).slice(0,-1);return a?i(e,a,o,(0,t.urlJoin)(n,encodeURI(r.uri)).replace(/\/$/,``),r.uri.replace(/\/$/,``)):e},[])},ye=async(e,t,{baseUrl:n,archiveOpf:r})=>{if(r)return await he(r.opf,e,{baseUrl:n})||[];let i=_e(t,e);if(i)return i;let a=ve(e,{baseUrl:n});if(a.length!==0)return a},be=({archive:e,baseUrl:t,archiveOpf:n})=>async r=>{if(r.nav)return r;let i=await ye(e,r,{baseUrl:t,archiveOpf:n});return i?{...r,nav:{toc:i}}:r},xe=e=>e?e.endsWith(`/`)?e:`${e}/`:``,K=async(e,{baseUrl:t=``,hooks:n={}}={})=>{u.log(`Generating manifest from archive`,e);let r=await E(e),i=xe(t),a=t=>(t??[]).map(t=>t({archive:e,baseUrl:i})),o=[M({archive:e,baseUrl:i,archiveOpf:r}),ce({archive:e,baseUrl:i}),oe({archive:e,baseUrl:i}),V({archive:e,baseUrl:i}),...a(n.content)],s=a(n.spine),c=[F({archive:e,baseUrl:i,archiveOpf:r}),R({archive:e,baseUrl:i}),...a(n.presentation)],l=[be({archive:e,baseUrl:i,archiveOpf:r}),...a(n.navigation)],d=[...o,...s,...c,...l,I()];try{let t=ue({archive:e,baseUrl:i})(),n=await d.reduce(async(e,t)=>await t(await e),t);if(u.log(`Generated manifest`,n),process.env.NODE_ENV===`development`&&u.isEnabled()){let e=JSON.stringify(n,null,2);u.groupCollapsed(...u.getGroupArgs(`Generated manifest`)),u.log(`\n${e}`),u.groupEnd()}return n}catch(e){throw u.error(e),e}},Se=e=>{let t=e.descendantWithPath(`head`)?.childrenNamed(`meta`).find(e=>e.attr.name===`calibre:cover`);return!!(t&&t.attr.name===`calibre:cover`)},Ce=e=>e.descendantWithPath(`body`)?.descendantWithPath(`div`)?.childrenNamed(`svg`)?.find(e=>e.attr.width===`100%`&&e.attr.preserveAspectRatio===`none`),we=({archive:e,resourcePath:t})=>async n=>{let i=Object.values(e.records).find(e=>e.uri===t&&!e.dir);if(i&&!i.dir&&i.basename.endsWith(`.xhtml`)){let e=new r.XmlDocument(typeof n.body==`string`?n.body:await i.string());if(Se(e)){let t=Ce(e);return t&&delete t.attr.preserveAspectRatio,{...n,body:e?.toString()}}}return n},Te=({archive:e,resourcePath:t})=>async n=>we({archive:e,resourcePath:t})(n),Ee=({archive:e,resourcePath:t})=>async n=>{let r=Object.values(e.records).find(e=>e.uri===t&&!e.dir);if(r&&!r.dir&&r.basename.endsWith(`.css`)){let e=(typeof n.body==`string`?n.body:await r.string()).replaceAll(`-webkit-writing-mode`,`writing-mode`);return{...n,body:e}}return n},De=async(e,t)=>{let n=await E(e);if(n){let{opf:r}=n,i=O(r.manifestItems,e,()=>``);if(i.find(e=>t.endsWith(e.href))?.mediaType)return{mediaType:i.find(e=>t.endsWith(e.href))?.mediaType}}return{mediaType:Oe(t)}},Oe=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`},ke=({archive:e,resourcePath:t})=>async n=>{let r=Object.values(e.records).find(e=>e.uri===t&&!e.dir);if(!r||r.dir)return n;let i=await De(e,t);return{...n,params:{...n.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...i.mediaType&&{contentType:i.mediaType}}}},q=`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`.split(`.`),Ae=({archive:e,resourcePath:t})=>async n=>{let r=Object.values(e.records).find(e=>e.uri===t&&!e.dir);if(r&&!r.dir&&r.basename.endsWith(`.xhtml`)){let e=typeof n.body==`string`?n.body:await r.string();if(!RegExp(`<(${q.join(`|`)})[\\s/>]`,`i`).test(e))return n;let t=RegExp(`<(${q.join(`|`)})(\\s[^>]*)?\\s*/>`,`gi`),i=e.replace(t,(e,t,n=``)=>`<${t} ${n.trim()}></${t}>`);return{...n,body:i}}return n},J=async(e,t,{hooks:n=[]}={})=>{let r={params:{}},i=[...n.map(n=>n({archive:e,resourcePath:t})),ke({archive:e,resourcePath:t}),Ae({archive:e,resourcePath:t}),Ee({archive:e,resourcePath:t}),Te({archive:e,resourcePath:t})];try{let n=await i.reduce(async(e,t)=>await t(await e),Promise.resolve(r));if(u.log(`Generated resource`,t,n),n.body!==void 0)return n;let a=Object.values(e.records).find(e=>e.uri===t&&!e.dir);if(!a||a.dir)throw Error(`no file found for resourcePath:${t}`);return{...n,body:await a.blob()}}catch(e){throw u.error(e),e}},je=class{constructor(e){this.cleanArchiveAfter=e,this.state$=new i.BehaviorSubject({status:`idle`,locks:0})}update(e){this.state$.next({...this.state$.getValue(),...e})}get locks$(){return this.state$.pipe((0,i.map)(({locks:e})=>e))}get state(){return this.state$.getValue()}get isUnlocked$(){return this.locks$.pipe((0,i.map)(e=>e<=0),(0,i.distinctUntilChanged)(),(0,i.shareReplay)())}get overTTL$(){return this.isUnlocked$.pipe((0,i.switchMap)(e=>e?this.cleanArchiveAfter===1/0?i.NEVER:(0,i.timer)(this.cleanArchiveAfter):i.NEVER))}},Me=({getArchive:e,cleanArchiveAfter:t=300*1e3})=>{let n=new i.Subject,r=new i.Subject,a=new i.Subject,o={};return n.pipe((0,i.mergeMap)(t=>{let n=o[t];if(!n||n.state.status!==`idle`)return i.EMPTY;let r=!1,s=e=>{u.debug(`Cleaning up archive with key: ${e}`);let t=o[e];delete o[e],r||=(t?.state.archive?.close(),!0)};n.update({status:`loading`});let c=n.locks$,l=n.isUnlocked$,d=c.pipe((0,i.pairwise)(),(0,i.filter)(([e,t])=>t>e),(0,i.startWith)(!0));return(0,i.from)(e(t)).pipe((0,i.tap)(e=>{n.update({archive:e,status:`success`})}),(0,i.catchError)(e=>(s(t),n.update({status:`error`,error:e}),i.EMPTY)),(0,i.switchMap)(()=>(0,i.merge)(d.pipe((0,i.switchMap)(()=>a),(0,i.switchMap)(()=>l),(0,i.filter)(e=>e)),n.overTTL$).pipe((0,i.first)(),(0,i.tap)(()=>{s(t)}))))}),(0,i.takeUntil)(r)).subscribe(),{access:e=>{let r=!1,a=o[e]??new je(t);o[e]=a,a.update({locks:a.state.locks+1});let s=()=>{r||(r=!0,a.update({locks:a.state.locks-1}))};return n.next(e),(0,i.merge)(a.state$.pipe((0,i.map)(({archive:e})=>e),(0,i.filter)(e=>!!e)),a.state$.pipe((0,i.tap)(({error:e})=>{if(e)throw e}),(0,i.ignoreElements)())).pipe((0,i.first)(),(0,i.map)(e=>({archive:e,release:s})),(0,i.catchError)(e=>{throw s(),e}))},purge:()=>{a.next()},_archives:o}},Y=e=>e?/^\d+$/.test(e)?{valid:!0,value:Number.parseInt(e,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},Ne=e=>{if(!e.toLowerCase().startsWith(`bytes=`))return{kind:`missing`};let t=e.slice(6).trim();if(!t)return{kind:`invalid`};if(t.includes(`,`))return{kind:`multi`};let n=/^(\d*)-(\d*)$/.exec(t);if(!n)return{kind:`invalid`};let[,r=``,i=``]=n,a=Y(r.trim()),o=Y(i.trim());return!a.valid||!o.valid?{kind:`invalid`}:{kind:`single`,start:a.value,end:o.value}},X=e=>{if(e instanceof Blob)return{size:e.size,slice:(t,n)=>{let r=e.slice(t,n);return{content:r,length:r.size}}};let t=new TextEncoder().encode(e);return{size:t.byteLength,slice:(e,n)=>{let r=t.slice(e,n);return{content:r,length:r.byteLength}}}},Pe=({body:e,contentType:t,rangeHeader:n})=>{let r=new Headers;if(t&&r.set(`Content-Type`,t),r.set(`Accept-Ranges`,`bytes`),!n)return e instanceof Blob&&r.set(`Content-Length`,String(e.size)),new Response(e,{status:200,headers:r});let i=Ne(n);if(i.kind===`missing`||i.kind===`multi`)return e instanceof Blob&&r.set(`Content-Length`,String(e.size)),new Response(e,{status:200,headers:r});let a=X(e),o=a.size;if(i.kind===`invalid`)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${o}`}});let s=i.start,c=i.end;if(s===void 0&&c===void 0||(s===void 0?(s=Math.max(0,o-Math.min(c??0,o)),c=o-1):(c===void 0||c>=o)&&(c=o-1),s<0||c<0||s>=o||c>=o||s>c))return new Response(null,{status:416,headers:{"Content-Range":`bytes */${o}`}});let l=a.slice(s,c+1);return r.set(`Content-Length`,String(l.length)),r.set(`Content-Range`,`bytes ${s}-${c}/${o}`),new Response(l.content,{status:206,headers:r})},Z=`file://`,Fe=/^https?:\/\//,Ie=e=>{try{return decodeURIComponent(e)}catch{return e}},Q=e=>e.startsWith(Z)?e.slice(Z.length):e,Le=e=>{let t=Q(e);return Fe.test(t)?t:Q(Ie(t))},$=class{constructor({hooks:e,onError:t,onManifestSuccess:n,...r}){this.onError=e=>(console.error(e),new Response(String(e),{status:500})),this.archiveLoader=Me(r),this.hooks=e??{},this.onManifestSuccess=n??(({manifest:e})=>Promise.resolve(e)),this.onError=t??this.onError}prune(){this.archiveLoader.purge()}accessArchive(e){return this.lastAccessedKey!==void 0&&this.lastAccessedKey!==e&&this.archiveLoader.purge(),this.lastAccessedKey=e,this.archiveLoader.access(e)}accessArchiveWithoutLock(e){return this.accessArchive(e).pipe((0,i.map)(({archive:e,release:t})=>(t(),e)))}withArchiveResponse({key:e,getResponse:t}){return(0,i.lastValueFrom)(this.accessArchive(e).pipe((0,i.mergeMap)(({archive:e,release:n})=>(0,i.from)(t(e)).pipe((0,i.finalize)(()=>{n()}))),(0,i.catchError)(e=>(0,i.of)(this.onError(e)))))}fetchManifest({key:e,baseUrl:t}){return this.withArchiveResponse({key:e,getResponse:e=>(0,i.from)(K(e,{baseUrl:t,hooks:this.hooks.manifest})).pipe((0,i.switchMap)(t=>(0,i.from)(this.onManifestSuccess({manifest:t,archive:e}))),(0,i.map)(e=>new Response(JSON.stringify(e),{status:200})))})}fetchResource({key:e,resourcePath:t,request:n}){return this.withArchiveResponse({key:e,getResponse:e=>(0,i.from)(J(e,Le(t),{hooks:this.hooks.resource})).pipe((0,i.map)(e=>Pe({body:e.body??``,contentType:e.params.contentType,rangeHeader:n?.headers.get(`range`)})))})}};e.ServiceWorkerStreamer=class extends ${constructor({getUriInfo:e,...t}){super(t),this.getUriInfo=e,this.fetchEventListener=this.fetchEventListener.bind(this)}fetchEventListener(e){try{let t=this.getUriInfo(e);if(!t)return;let n=s(t.baseUrl),r=e.request.url.substring(n.length+1),[i=``]=r.split(`/`),a=s(r.substring(i.length+1));r.endsWith(`/manifest`)?e.respondWith(this.fetchManifest({key:i,baseUrl:`${n}/${i}/`})):e.respondWith(this.fetchResource({key:i,resourcePath:a,request:e.request}))}catch(t){e.respondWith(new Response(String(t),{status:500}))}}},e.Streamer=$,e.configure=ie,e.createArchiveFromArrayBufferList=l,e.createArchiveFromJszip=f,e.createArchiveFromLibArchive=p,e.createArchiveFromText=m,e.createArchiveFromUrls=x,e.createUniqueXmlSafeId=y,e.createXmlSafeId=v,e.createXmlSafeIdFactory=b,e.generateManifestFromArchive=K,e.generateResourceFromArchive=J,e.getArchiveHasComicInfo=w,e.getArchiveOpfInfo=T,e.getUriBasePath=c,e.getUriBasename=o,e.removeTrailingSlash=s,e.sortByTitleComparator=a});
33
+ //# sourceMappingURL=index.umd.cjs.map