@prose-reader/streamer 1.281.0 → 1.283.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.
package/dist/index.js CHANGED
@@ -1,99 +1,120 @@
1
- import { Report as se, detectMimeTypeFromName as j, isXmlBasedMimeType as ie, parseContentType as ae, urlJoin as I } from "@prose-reader/shared";
2
- import { XmlDocument as y, XmlTextNode as ce, XmlElement as de } from "xmldoc";
3
- import { Subject as C, mergeMap as O, EMPTY as B, pairwise as le, filter as R, startWith as pe, from as T, tap as P, catchError as W, switchMap as A, merge as X, first as V, takeUntil as me, map as v, ignoreElements as fe, BehaviorSubject as ue, distinctUntilChanged as he, shareReplay as ge, NEVER as H, timer as ye, finalize as _, of as G, lastValueFrom as q } from "rxjs";
4
- const D = (n, e) => {
5
- const s = n.split(/(\d+)/), r = e.split(/(\d+)/);
6
- for (let t = 0, o = s.length; t < o; t++)
7
- if (s[t] !== r[t])
8
- return s[t]?.match(/\d/) ? +(s[t] || "") - +(r[t] || "") : (s[t] || "").localeCompare(r[t] || "");
1
+ import { detectMimeTypeFromName as x, Report as re, isXmlBasedMimeType as se, parseContentType as ie, urlJoin as S } from "@prose-reader/shared";
2
+ import { XmlDocument as y, XmlTextNode as oe, XmlElement as ae } from "xmldoc";
3
+ import { Subject as L, mergeMap as q, EMPTY as M, pairwise as ce, filter as C, startWith as de, from as A, tap as P, catchError as j, switchMap as I, merge as U, first as V, takeUntil as le, map as $, ignoreElements as pe, BehaviorSubject as me, distinctUntilChanged as ue, shareReplay as fe, NEVER as X, timer as he, finalize as ge, of as ye, lastValueFrom as be } from "rxjs";
4
+ const O = (t, e) => {
5
+ const i = t.split(/(\d+)/), s = e.split(/(\d+)/);
6
+ for (let n = 0, r = i.length; n < r; n++)
7
+ if (i[n] !== s[n])
8
+ return i[n]?.match(/\d/) ? +(i[n] || "") - +(s[n] || "") : (i[n] || "").localeCompare(s[n] || "");
9
9
  return 1;
10
- }, $ = (n) => n.substring(n.lastIndexOf("/") + 1) || n, J = (n) => n.endsWith("/") ? n.slice(0, -1) : n, be = (n) => {
11
- const e = n.lastIndexOf("/");
12
- return e >= 0 ? n.substring(0, e) : "";
13
- }, it = async (n, { orderByAlpha: e, name: s } = {}) => {
14
- let r = n;
15
- return e && (r = r.slice().sort((t, o) => D(t.name, o.name))), {
16
- filename: s || "",
17
- records: r.map((t) => ({
18
- dir: t.isDir,
19
- basename: $(t.name),
20
- uri: t.name,
21
- blob: async () => new Blob([await t.data()]),
22
- string: async () => {
23
- const o = await t.data();
24
- return String.fromCharCode.apply(
25
- null,
26
- Array.from(new Uint16Array(o))
27
- );
28
- },
29
- size: t.size
30
- })),
10
+ }, w = (t) => t.substring(t.lastIndexOf("/") + 1) || t, H = (t) => t.endsWith("/") ? t.slice(0, -1) : t, we = (t) => {
11
+ const e = t.lastIndexOf("/");
12
+ return e >= 0 ? t.substring(0, e) : "";
13
+ }, dt = async (t, { orderByAlpha: e, name: i } = {}) => {
14
+ let s = t;
15
+ return e && (s = s.slice().sort((n, r) => O(n.name, r.name))), {
16
+ filename: i || "",
17
+ records: s.map((n) => {
18
+ const r = n.size, o = w(n.name);
19
+ return n.isDir ? {
20
+ dir: !0,
21
+ basename: o,
22
+ uri: n.name,
23
+ size: r
24
+ } : {
25
+ dir: n.isDir,
26
+ basename: o,
27
+ encodingFormat: x(n.name),
28
+ uri: n.name,
29
+ blob: async () => new Blob([await n.data()], {
30
+ type: x(n.name) ?? ""
31
+ }),
32
+ string: async () => {
33
+ const a = await n.data();
34
+ return String.fromCharCode.apply(
35
+ null,
36
+ Array.from(new Uint16Array(a))
37
+ );
38
+ },
39
+ size: r
40
+ };
41
+ }),
31
42
  close: () => Promise.resolve()
32
43
  };
33
- }, we = "@prose-reader/streamer", m = se.namespace(we, !1, {
44
+ }, ve = "@prose-reader/streamer", m = re.namespace(ve, !1, {
34
45
  color: "#ffae42"
35
- }), ve = (n) => {
46
+ }), $e = (t) => {
36
47
  const e = {};
37
- for (const r of n) {
38
- const t = r.split("/");
39
- let o = e;
40
- for (let i = 0; i < t.length; i++) {
41
- const a = t[i];
42
- a !== void 0 && (o[a] || (o[a] = {}), o = o[a]);
48
+ for (const s of t) {
49
+ const n = s.split("/");
50
+ let r = e;
51
+ for (let o = 0; o < n.length; o++) {
52
+ const a = n[o];
53
+ a !== void 0 && (r[a] || (r[a] = {}), r = r[a]);
43
54
  }
44
55
  }
45
- const s = (r, t = "") => Object.keys(r).sort().map((o, i, a) => {
46
- const l = i === a.length - 1, c = t + (l ? "└── " : "├── "), d = t + (l ? " " : "│ "), p = r[o];
47
- return p && Object.keys(p).length > 0 ? `${c}${o}/
48
- ${s(p, d)}` : `${c}${o}`;
56
+ const i = (s, n = "") => Object.keys(s).sort().map((r, o, a) => {
57
+ const c = o === a.length - 1, d = n + (c ? "└── " : "├── "), l = n + (c ? " " : "│ "), p = s[r];
58
+ return p && Object.keys(p).length > 0 ? `${d}${r}/
59
+ ${i(p, l)}` : `${d}${r}`;
49
60
  }).join(`
50
61
  `);
51
- return s(e);
52
- }, at = async (n, { orderByAlpha: e, name: s } = {}) => {
53
- let r = Object.values(n.files);
54
- e && (r = r.slice().sort((o, i) => D(o.name, i.name)));
55
- const t = {
56
- filename: s || "",
57
- records: r.map((o) => ({
58
- dir: o.dir,
59
- basename: $(o.name),
60
- uri: o.name,
61
- blob: () => o.async("blob"),
62
- string: () => o.async("string"),
63
- ...o.internalStream && {
64
- stream: o.internalStream
65
- },
66
- // this is private API
67
- // @ts-expect-error
68
- size: o._data.uncompressedSize
69
- })),
62
+ return i(e);
63
+ }, lt = async (t, { orderByAlpha: e, name: i } = {}) => {
64
+ let s = Object.values(t.files);
65
+ e && (s = s.slice().sort((r, o) => O(r.name, o.name)));
66
+ const n = {
67
+ filename: i || "",
68
+ records: s.map((r) => {
69
+ const o = r._data.uncompressedSize, a = w(r.name);
70
+ return r.dir ? {
71
+ dir: !0,
72
+ basename: a,
73
+ uri: r.name,
74
+ size: o
75
+ } : {
76
+ dir: !1,
77
+ basename: w(r.name),
78
+ uri: r.name,
79
+ encodingFormat: x(r.name),
80
+ blob: () => r.async("blob"),
81
+ string: () => r.async("string"),
82
+ ...r.internalStream && {
83
+ stream: r.internalStream
84
+ },
85
+ // this is private API
86
+ // @ts-expect-error
87
+ size: r._data.uncompressedSize
88
+ };
89
+ }),
70
90
  close: () => Promise.resolve()
71
91
  };
72
- if (m.log("Generated archive", t), process.env.NODE_ENV === "development" && m.isEnabled()) {
73
- const o = ve(r.map((i) => i.name));
92
+ if (m.log("Generated archive", n), process.env.NODE_ENV === "development" && m.isEnabled()) {
93
+ const r = $e(s.map((o) => o.name));
74
94
  m.groupCollapsed(...m.getGroupArgs("Archive folder structure")), m.log(`
75
- ${o}`), m.groupEnd();
95
+ ${r}`), m.groupEnd();
76
96
  }
77
- return t;
78
- }, ct = async (n, { name: e } = {}) => {
79
- const s = await n.getFilesArray(), r = {
80
- close: () => n.close(),
97
+ return n;
98
+ }, pt = async (t, { name: e } = {}) => {
99
+ const i = await t.getFilesArray(), s = {
100
+ close: () => t.close(),
81
101
  filename: e ?? "",
82
- records: s.map((t) => ({
102
+ records: i.map((n) => ({
83
103
  dir: !1,
84
- basename: t.file.name,
85
- size: t.file.size,
86
- uri: `${t.path}${t.file.name}`,
87
- blob: async () => await t.file.extract(),
88
- string: async () => (await t.file.extract()).text()
104
+ basename: n.file.name,
105
+ encodingFormat: x(n.file.name),
106
+ size: n.file.size,
107
+ uri: `${n.path}${n.file.name}`,
108
+ blob: async () => await n.file.extract(),
109
+ string: async () => (await n.file.extract()).text()
89
110
  }))
90
111
  };
91
- return m.log("Generated archive", r), r;
92
- }, dt = async (n, {
112
+ return m.log("Generated archive", s), s;
113
+ }, mt = async (t, {
93
114
  mimeType: e,
94
- direction: s
115
+ direction: i
95
116
  } = { mimeType: "text/plain" }) => {
96
- const r = `
117
+ const s = `
97
118
  <?xml version="1.0" encoding="UTF-8"?>
98
119
  <package xmlns="http://www.idpf.org/2007/opf" version="3.0" xml:lang="ja" prefix="rendition: http://www.idpf.org/vocab/rendition/#"
99
120
  unique-identifier="ootuya-id">
@@ -104,7 +125,7 @@ ${o}`), m.groupEnd();
104
125
  <manifest>
105
126
  <item id="p01" href="p01.txt" media-type="text/plain"/>
106
127
  </manifest>
107
- <spine page-progression-direction="${s ?? "ltr"}">
128
+ <spine page-progression-direction="${i ?? "ltr"}">
108
129
  <itemref idref="p01" />
109
130
  </spine>
110
131
  </package>
@@ -114,49 +135,49 @@ ${o}`), m.groupEnd();
114
135
  records: [
115
136
  {
116
137
  dir: !1,
117
- basename: $("generated.opf"),
138
+ basename: w("generated.opf"),
118
139
  uri: "generated.opf",
119
- blob: async () => new Blob([r]),
120
- string: async () => r,
140
+ blob: async () => new Blob([s]),
141
+ string: async () => s,
121
142
  size: 0
122
143
  },
123
144
  {
124
145
  dir: !1,
125
- basename: $("p01.txt"),
146
+ basename: w("p01.txt"),
126
147
  uri: "p01.txt",
127
- blob: async () => typeof n == "string" ? new Blob([n]) : n,
128
- string: async () => typeof n == "string" ? n : n.text(),
129
- size: typeof n == "string" ? n.length : n.size,
148
+ blob: async () => typeof t == "string" ? new Blob([t]) : t,
149
+ string: async () => typeof t == "string" ? t : t.text(),
150
+ size: typeof t == "string" ? t.length : t.size,
130
151
  encodingFormat: e
131
152
  }
132
153
  ],
133
154
  close: () => Promise.resolve()
134
155
  };
135
- }, lt = async (n, e) => {
136
- const s = `
156
+ }, ut = async (t, e) => {
157
+ const i = `
137
158
  <?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="bookid">
138
159
  <metadata>
139
160
  <meta property="rendition:layout">${e?.useRenditionFlow ? "reflowable" : "pre-paginated"}</meta>
140
161
  ${e?.useRenditionFlow ? '<meta property="rendition:flow">scrolled-continuous</meta>' : ""}
141
162
  </metadata>
142
163
  <manifest>
143
- ${n.map(
144
- (o) => `<item id="${$(o)}" href="${o}" media-type="${j(o)}"/>`
164
+ ${t.map(
165
+ (r) => `<item id="${w(r)}" href="${r}" media-type="${x(r)}"/>`
145
166
  ).join(`
146
167
  `)}
147
168
  </manifest>
148
169
  <spine>
149
- ${n.map((o) => `<itemref idref="${$(o)}" />`).join(`
170
+ ${t.map((r) => `<itemref idref="${w(r)}" />`).join(`
150
171
  `)}
151
172
  </spine>
152
173
  </package>
153
- `, r = n.map((o) => ({
174
+ `, s = t.map((r) => ({
154
175
  dir: !1,
155
- basename: $(o),
156
- encodingFormat: j(o),
157
- uri: o,
158
- size: 100 / n.length,
159
- blob: async () => (await fetch(o)).blob(),
176
+ basename: w(r),
177
+ encodingFormat: x(r),
178
+ uri: r,
179
+ size: 100 / t.length,
180
+ blob: async () => (await fetch(r)).blob(),
160
181
  string: async () => ""
161
182
  }));
162
183
  return {
@@ -167,487 +188,487 @@ ${o}`), m.groupEnd();
167
188
  uri: "content.opf",
168
189
  size: 0,
169
190
  blob: async () => new Blob(),
170
- string: async () => s
171
- }, ...r],
191
+ string: async () => i
192
+ }, ...s],
172
193
  close: () => Promise.resolve()
173
194
  };
174
- }, pt = ({
175
- enableReport: n
195
+ }, ft = ({
196
+ enableReport: t
176
197
  } = {}) => {
177
- m.enable(!!n);
178
- }, F = (n) => {
179
- const s = Object.values(n.records).filter(
180
- (r) => !r.dir
181
- ).find((r) => r.uri.endsWith(".opf"));
198
+ m.enable(!!t);
199
+ }, E = (t) => {
200
+ const i = Object.values(t.records).filter(
201
+ (s) => !s.dir
202
+ ).find((s) => s.uri.endsWith(".opf"));
182
203
  return {
183
- data: s,
184
- basePath: s?.uri.substring(0, s.uri.lastIndexOf("/")) || ""
204
+ data: i,
205
+ basePath: i?.uri.substring(0, i.uri.lastIndexOf("/")) || ""
185
206
  };
186
- }, $e = ({ archive: n }) => async (e) => {
187
- const s = n.records.find(
188
- (t) => t.basename.toLowerCase() === "com.apple.ibooks.display-options.xml"
207
+ }, xe = ({ archive: t }) => async (e) => {
208
+ const i = t.records.find(
209
+ (n) => n.basename.toLowerCase() === "com.apple.ibooks.display-options.xml"
189
210
  );
190
- if (!s || s.dir)
211
+ if (!i || i.dir)
191
212
  return e;
192
- const r = await (await s.blob()).text();
213
+ const s = await (await i.blob()).text();
193
214
  try {
194
- const i = new y(r).childNamed("platform")?.childrenNamed("option")?.find((a) => a.attr.name === "fixed-layout")?.val || "false";
215
+ const o = new y(s).childNamed("platform")?.childrenNamed("option")?.find((a) => a.attr.name === "fixed-layout")?.val || "false";
195
216
  return {
196
217
  ...e,
197
- renditionLayout: i === "true" ? "pre-paginated" : e.renditionLayout
218
+ renditionLayout: o === "true" ? "pre-paginated" : e.renditionLayout
198
219
  };
199
- } catch (t) {
220
+ } catch (n) {
200
221
  return console.error(
201
222
  `Unable to parse com.apple.ibooks.display-options.xml for content
202
223
  `,
203
- r
204
- ), console.error(t), e;
224
+ s
225
+ ), console.error(n), e;
205
226
  }
206
- }, xe = async (n) => {
227
+ }, Fe = async (t) => {
207
228
  const e = {
208
229
  renditionLayout: void 0
209
230
  };
210
231
  return await Promise.all(
211
- n.records.map(async (s) => {
212
- if (s.uri.endsWith("com.kobobooks.display-options.xml") && !s.dir) {
213
- const t = new y(await s.string()).childNamed("platform")?.childNamed("option");
214
- t?.attr?.name === "fixed-layout" && t.val === "true" && (e.renditionLayout = "pre-paginated");
232
+ t.records.map(async (i) => {
233
+ if (i.uri.endsWith("com.kobobooks.display-options.xml") && !i.dir) {
234
+ const n = new y(await i.string()).childNamed("platform")?.childNamed("option");
235
+ n?.attr?.name === "fixed-layout" && n.val === "true" && (e.renditionLayout = "pre-paginated");
215
236
  }
216
237
  })
217
238
  ), e;
218
- }, Fe = ({ archive: n }) => async (e) => {
219
- const s = await xe(n);
239
+ }, Ee = ({ archive: t }) => async (e) => {
240
+ const i = await Fe(t);
220
241
  return {
221
242
  ...e,
222
- renditionLayout: e.renditionLayout ?? s.renditionLayout
243
+ renditionLayout: e.renditionLayout ?? i.renditionLayout
223
244
  };
224
- }, Ee = ({ archive: n, baseUrl: e }) => async () => {
225
- const s = Object.values(n.records).filter((r) => !r.dir);
245
+ }, Re = ({ archive: t, baseUrl: e }) => async () => {
246
+ const i = Object.values(t.records).filter((s) => !s.dir);
226
247
  return {
227
- filename: n.filename,
228
- title: n.records.find(({ dir: r }) => r)?.basename.replace(/\/$/, "") || n.filename,
248
+ filename: t.filename,
249
+ title: t.records.find(({ dir: s }) => s)?.basename.replace(/\/$/, "") || t.filename,
229
250
  renditionLayout: void 0,
230
251
  renditionSpread: "auto",
231
252
  readingDirection: "ltr",
232
- spineItems: s.filter((r) => !r.basename.endsWith(".db")).map((r, t) => {
233
- const o = e || (/^https?:\/\//.test(r.uri) ? "" : "file://");
253
+ spineItems: i.filter((s) => !s.basename.endsWith(".db")).map((s, n) => {
254
+ const r = e || (/^https?:\/\//.test(s.uri) ? "" : "file://");
234
255
  return {
235
256
  // some books such as cbz can have same basename inside different sub folder
236
257
  // we need to make sure to have unique index
237
258
  // /chap01/01.png, /chap02/01.png, etc
238
- id: `${t}.${r.basename}`,
239
- index: t,
240
- href: encodeURI(`${o}${r.uri}`),
259
+ id: `${n}.${s.basename}`,
260
+ index: n,
261
+ href: encodeURI(`${r}${s.uri}`),
241
262
  renditionLayout: void 0,
242
- progressionWeight: 1 / s.length,
263
+ progressionWeight: 1 / i.length,
243
264
  pageSpreadLeft: void 0,
244
265
  pageSpreadRight: void 0,
245
- mediaType: r.encodingFormat
266
+ mediaType: s.encodingFormat
246
267
  };
247
268
  }),
248
- items: s.map((r, t) => ({
249
- id: `${t}.${r.basename}`,
250
- href: encodeURI(`${e}${r.uri}`)
269
+ items: i.map((s, n) => ({
270
+ id: `${n}.${s.basename}`,
271
+ href: encodeURI(`${e}${s.uri}`)
251
272
  }))
252
273
  };
253
- }, Y = async ({
254
- archive: n
274
+ }, J = async ({
275
+ archive: t
255
276
  }) => {
256
- const { data: e, basePath: s } = F(n) || {}, r = await e?.string();
257
- if (!r) return [];
258
- const t = new y(r), o = t.childNamed("manifest"), a = t.childNamed("spine")?.childrenNamed("itemref").map((d) => d.attr.idref), l = o?.childrenNamed("item").filter((d) => a.includes(d.attr.id || "")) || [];
259
- return n.records.filter((d) => l.find((p) => s ? `${s}/${p.attr.href}` === d.uri : `${p.attr.href}` === d.uri));
260
- }, Ne = (n) => {
261
- const e = n.attr.properties?.split(" ") || [];
262
- let s;
263
- return e.find((r) => r === "rendition:layout-reflowable") && (s = "reflowable"), e.find((r) => r === "rendition:layout-pre-paginated") && (s = "pre-paginated"), {
264
- renditionLayout: s,
265
- pageSpreadLeft: e.some((r) => r === "page-spread-left") || void 0,
266
- pageSpreadRight: e.some((r) => r === "page-spread-right") || void 0
277
+ const { data: e, basePath: i } = E(t) || {}, s = await e?.string();
278
+ if (!s) return [];
279
+ const n = new y(s), r = n.childNamed("manifest"), a = n.childNamed("spine")?.childrenNamed("itemref").map((l) => l.attr.idref), c = r?.childrenNamed("item").filter((l) => a.includes(l.attr.id || "")) || [];
280
+ return t.records.filter((l) => c.find((p) => i ? `${i}/${p.attr.href}` === l.uri : `${p.attr.href}` === l.uri));
281
+ }, Ne = (t) => {
282
+ const e = t.attr.properties?.split(" ") || [];
283
+ let i;
284
+ return e.find((s) => s === "rendition:layout-reflowable") && (i = "reflowable"), e.find((s) => s === "rendition:layout-pre-paginated") && (i = "pre-paginated"), {
285
+ renditionLayout: i,
286
+ pageSpreadLeft: e.some((s) => s === "page-spread-left") || void 0,
287
+ pageSpreadRight: e.some((s) => s === "page-spread-right") || void 0
267
288
  };
268
- }, Ae = (n, e, s) => {
269
- const r = n.attr.href || "", t = s?.(n);
289
+ }, Ae = (t, e, i) => {
290
+ const s = t.attr.href || "", n = i?.(t);
270
291
  return {
271
- href: e ? `${t}${e}/${r}` : `${t}${r}`,
272
- id: n.attr.id || "",
273
- mediaType: n.attr["media-type"]
292
+ href: e ? `${n}${e}/${s}` : `${n}${s}`,
293
+ id: t.attr.id || "",
294
+ mediaType: t.attr["media-type"]
274
295
  };
275
- }, Q = (n, e, s) => {
276
- const r = n.childNamed("manifest"), { basePath: t } = F(e) || {};
277
- return r?.childrenNamed("item")?.map((o) => Ae(o, t, s)) || [];
278
- }, Ie = ({ archive: n, baseUrl: e }) => async (s) => {
279
- const { data: r, basePath: t } = F(n) || {};
280
- if (!r)
281
- return s;
282
- const o = await r.string();
283
- m.groupCollapsed(...m.getGroupArgs("OPF data")), m.log("data", o), m.groupEnd();
284
- const i = new y(o), a = i.childNamed("metadata"), l = i.childNamed("manifest"), c = i.childNamed("spine"), d = i.childNamed("guide"), p = a?.childNamed("dc:title"), g = a?.childrenNamed("meta") || [], b = g.find(
285
- (f) => f.attr.property === "rendition:layout"
286
- ), E = g.find(
287
- (f) => f.attr.property === "rendition:flow"
288
- ), u = g.find(
289
- (f) => f.attr.property === "rendition:spread"
290
- ), L = b?.val, h = E?.val, x = u?.val, S = p?.val || n.records.find(({ dir: f }) => f)?.basename || "", ne = c?.attr["page-progression-direction"], re = (await Y({ archive: n })).reduce(
291
- (f, N) => N.size + f,
296
+ }, K = (t, e, i) => {
297
+ const s = t.childNamed("manifest"), { basePath: n } = E(e) || {};
298
+ return s?.childrenNamed("item")?.map((r) => Ae(r, n, i)) || [];
299
+ }, Ie = ({ archive: t, baseUrl: e }) => async (i) => {
300
+ const { data: s, basePath: n } = E(t) || {};
301
+ if (!s)
302
+ return i;
303
+ const r = await s.string();
304
+ m.groupCollapsed(...m.getGroupArgs("OPF data")), m.log("data", r), m.groupEnd();
305
+ const o = new y(r), a = o.childNamed("metadata"), c = o.childNamed("manifest"), d = o.childNamed("spine"), l = o.childNamed("guide"), p = a?.childNamed("dc:title"), g = a?.childrenNamed("meta") || [], b = g.find(
306
+ (u) => u.attr.property === "rendition:layout"
307
+ ), R = g.find(
308
+ (u) => u.attr.property === "rendition:flow"
309
+ ), f = g.find(
310
+ (u) => u.attr.property === "rendition:spread"
311
+ ), T = b?.val, h = R?.val, F = f?.val, W = p?.val || t.records.find(({ dir: u }) => u)?.basename || "", ee = d?.attr["page-progression-direction"], te = (await J({ archive: t })).reduce(
312
+ (u, N) => N.size + u,
292
313
  0
293
314
  );
294
315
  return {
295
- filename: n.filename,
296
- renditionLayout: L,
316
+ filename: t.filename,
317
+ renditionLayout: T,
297
318
  renditionFlow: h || "auto",
298
- renditionSpread: x,
299
- title: S,
300
- readingDirection: ne || "ltr",
319
+ renditionSpread: F,
320
+ title: W,
321
+ readingDirection: ee || "ltr",
301
322
  /**
302
323
  * @see https://www.w3.org/TR/epub/#sec-itemref-elem
303
324
  */
304
- spineItems: c?.childrenNamed("itemref").map((f, N) => {
305
- const w = l?.childrenNamed("item").find((k) => k.attr.id === f?.attr.idref), M = w?.attr.href || "", oe = n.records.find((k) => k.uri.endsWith(M))?.size || 0, U = e || (/^https?:\/\//.test(M) ? "" : "file://"), z = Ne(f);
325
+ spineItems: d?.childrenNamed("itemref").map((u, N) => {
326
+ const v = c?.childrenNamed("item").find((k) => k.attr.id === u?.attr.idref), z = v?.attr.href || "", ne = t.records.find((k) => k.uri.endsWith(z))?.size || 0, B = e || (/^https?:\/\//.test(z) ? "" : "file://"), D = Ne(u);
306
327
  return {
307
- ...z,
308
- id: w?.attr.id || "",
328
+ ...D,
329
+ id: v?.attr.id || "",
309
330
  index: N,
310
- href: w?.attr.href?.startsWith("https://") ? w?.attr.href : t ? `${U}${t}/${w?.attr.href}` : `${U}${w?.attr.href}`,
311
- renditionLayout: z.renditionLayout ?? L,
312
- progressionWeight: oe / re,
331
+ href: v?.attr.href?.startsWith("https://") ? v?.attr.href : n ? `${B}${n}/${v?.attr.href}` : `${B}${v?.attr.href}`,
332
+ renditionLayout: D.renditionLayout ?? T,
333
+ progressionWeight: ne / te,
313
334
  // size: itemSize
314
- mediaType: w?.attr["media-type"]
335
+ mediaType: v?.attr["media-type"]
315
336
  };
316
337
  }) || [],
317
- items: Q(i, n, (f) => {
318
- const N = f.attr.href || "";
338
+ items: K(o, t, (u) => {
339
+ const N = u.attr.href || "";
319
340
  return /^https?:\/\//.test(N) ? "" : e || "file://";
320
341
  }),
321
- guide: d?.childrenNamed("reference").map((f) => ({
322
- href: f.attr.href || "",
323
- title: f.attr.title || "",
324
- type: f.attr.type
342
+ guide: l?.childrenNamed("reference").map((u) => ({
343
+ href: u.attr.href || "",
344
+ title: u.attr.title || "",
345
+ type: u.attr.type
325
346
  }))
326
347
  };
327
- }, Te = (n) => {
328
- const e = n.descendantWithPath("head")?.childrenNamed("meta").find((s) => s.attr.name === "viewport");
348
+ }, Se = (t) => {
349
+ const e = t.descendantWithPath("head")?.childrenNamed("meta").find((i) => i.attr.name === "viewport");
329
350
  return !!(e && e.attr.name === "viewport");
330
- }, We = (n) => n.reduce(async (e, s) => {
331
- if (!await e || !ie({
332
- mimeType: s.encodingFormat,
333
- uri: s.uri
351
+ }, Te = (t) => t.reduce(async (e, i) => {
352
+ if (!await e || !se({
353
+ mimeType: i.encodingFormat,
354
+ uri: i.uri
334
355
  }))
335
356
  return !1;
336
- const t = s.dir ? null : await s.string();
337
- return t ? Te(new y(t)) : !1;
338
- }, Promise.resolve(!0)), Le = ({ archive: n }) => async (e) => {
339
- if (e.renditionLayout === "reflowable" && e.spineItems.every((r) => r.renditionLayout === "reflowable")) {
340
- const r = await Y({ archive: n });
341
- if (await We(r))
357
+ const n = i.dir ? null : await i.string();
358
+ return n ? Se(new y(n)) : !1;
359
+ }, Promise.resolve(!0)), We = ({ archive: t }) => async (e) => {
360
+ if (e.renditionLayout === "reflowable" && e.spineItems.every((s) => s.renditionLayout === "reflowable")) {
361
+ const s = await J({ archive: t });
362
+ if (await Te(s))
342
363
  return {
343
364
  ...e,
344
- spineItems: e.spineItems.map((o) => ({
345
- ...o,
365
+ spineItems: e.spineItems.map((r) => ({
366
+ ...r,
346
367
  renditionLayout: "pre-paginated"
347
368
  })),
348
369
  renditionLayout: "pre-paginated"
349
370
  };
350
371
  }
351
372
  return e;
352
- }, Se = ({ archive: n }) => async (e) => {
353
- const s = n.records.find(
354
- (o) => o.basename.toLowerCase() === "comicinfo.xml" && !o.dir
373
+ }, ke = ({ archive: t }) => async (e) => {
374
+ const i = t.records.find(
375
+ (r) => r.basename.toLowerCase() === "comicinfo.xml" && !r.dir
355
376
  );
356
- if (!s || s.dir)
377
+ if (!i || i.dir)
357
378
  return e;
358
- const r = {
379
+ const s = {
359
380
  ...e,
360
- spineItems: e.spineItems.filter((o) => !o.id.toLowerCase().endsWith("comicinfo.xml")).map((o, i, a) => ({
361
- ...o,
381
+ spineItems: e.spineItems.filter((r) => !r.id.toLowerCase().endsWith("comicinfo.xml")).map((r, o, a) => ({
382
+ ...r,
362
383
  progressionWeight: 1 / a.length
363
384
  }))
364
- }, t = await s.string();
385
+ }, n = await i.string();
365
386
  try {
366
- const i = new y(t).childNamed("Manga")?.val || "unknown";
387
+ const o = new y(n).childNamed("Manga")?.val || "unknown";
367
388
  return {
368
- ...r,
369
- readingDirection: i === "YesAndRightToLeft" ? "rtl" : "ltr"
389
+ ...s,
390
+ readingDirection: o === "YesAndRightToLeft" ? "rtl" : "ltr"
370
391
  };
371
- } catch (o) {
392
+ } catch (r) {
372
393
  return console.error(`Unable to parse comicinfo.xml for content
373
- `, t), console.error(o), r;
394
+ `, n), console.error(r), s;
374
395
  }
375
- }, ke = (n) => n.records.some((e) => e.basename.endsWith(".opf")), Ce = ({ archive: n }) => async (e) => ke(n) ? e : {
396
+ }, Le = (t) => t.records.some((e) => e.basename.endsWith(".opf")), Ce = ({ archive: t }) => async (e) => Le(t) ? e : {
376
397
  ...e,
377
- spineItems: e.spineItems.map((r) => {
378
- const t = n.records.find(
379
- (i) => decodeURI(r.href).endsWith(i.uri)
380
- ), o = ae(t?.encodingFormat ?? "") ?? j(t?.basename ?? "");
398
+ spineItems: e.spineItems.map((s) => {
399
+ const n = t.records.find(
400
+ (o) => decodeURI(s.href).endsWith(o.uri)
401
+ ), r = ie(n?.encodingFormat ?? "") || x(n?.basename ?? "");
381
402
  return {
382
- ...r,
383
- renditionLayout: o?.startsWith("image/") ? "pre-paginated" : r.renditionLayout
403
+ ...s,
404
+ renditionLayout: r?.startsWith("image/") ? "pre-paginated" : s.renditionLayout
384
405
  };
385
406
  })
386
- }, Z = (n) => n ? n.children.map((e) => e instanceof ce ? e.text : e instanceof de ? Z(e) : "").join("").trim() : "", ee = (n, { basePath: e, baseUrl: s }) => {
387
- const r = {
407
+ }, Y = (t) => t ? t.children.map((e) => e instanceof oe ? e.text : e instanceof ae ? Y(e) : "").join("").trim() : "", Q = (t, { basePath: e, baseUrl: i }) => {
408
+ const s = {
388
409
  contents: [],
389
410
  path: "",
390
411
  href: "",
391
412
  title: ""
392
413
  };
393
- let t = n.childNamed("span") || n.childNamed("a");
394
- r.title = (t?.attr.title || t?.val.trim() || Z(t)) ?? "";
395
- let o = t?.name;
396
- o !== "a" && (t = n.descendantWithPath(`${o}.a`), t && (o = t.name.toLowerCase())), o === "a" && t?.attr.href && (r.path = I(e, t.attr.href), r.href = I(s, e, t.attr.href));
397
- const i = n.childNamed("ol");
398
- if (i) {
399
- const a = i.childrenNamed("li");
400
- a && a.length > 0 && (r.contents = a.map(
401
- (l) => ee(l, { basePath: e, baseUrl: s })
414
+ let n = t.childNamed("span") || t.childNamed("a");
415
+ s.title = (n?.attr.title || n?.val.trim() || Y(n)) ?? "";
416
+ let r = n?.name;
417
+ r !== "a" && (n = t.descendantWithPath(`${r}.a`), n && (r = n.name.toLowerCase())), r === "a" && n?.attr.href && (s.path = S(e, n.attr.href), s.href = S(i, e, n.attr.href));
418
+ const o = t.childNamed("ol");
419
+ if (o) {
420
+ const a = o.childrenNamed("li");
421
+ a && a.length > 0 && (s.contents = a.map(
422
+ (c) => Q(c, { basePath: e, baseUrl: i })
402
423
  ));
403
424
  }
404
- return r;
405
- }, Re = (n, { basePath: e, baseUrl: s }) => {
406
- const r = [];
407
- let t;
408
- return n.descendantWithPath("body.nav.ol") ? t = n.descendantWithPath("body.nav.ol")?.children : n.descendantWithPath("body.section.nav.ol") && (t = n.descendantWithPath("body.section.nav.ol")?.children), t && t.length > 0 && t.filter((o) => o.name === "li").forEach((o) => {
409
- r.push(ee(o, { basePath: e, baseUrl: s }));
410
- }), r;
411
- }, Pe = async (n, e, { baseUrl: s }) => {
412
- const r = n.childNamed("manifest")?.childrenNamed("item").find((t) => t.attr.properties === "nav");
413
- if (r) {
414
- const t = Object.values(e.records).find(
415
- (o) => o.uri.endsWith(r.attr.href || "")
425
+ return s;
426
+ }, Pe = (t, { basePath: e, baseUrl: i }) => {
427
+ const s = [];
428
+ let n;
429
+ return t.descendantWithPath("body.nav.ol") ? n = t.descendantWithPath("body.nav.ol")?.children : t.descendantWithPath("body.section.nav.ol") && (n = t.descendantWithPath("body.section.nav.ol")?.children), n && n.length > 0 && n.filter((r) => r.name === "li").forEach((r) => {
430
+ s.push(Q(r, { basePath: e, baseUrl: i }));
431
+ }), s;
432
+ }, je = async (t, e, { baseUrl: i }) => {
433
+ const s = t.childNamed("manifest")?.childrenNamed("item").find((n) => n.attr.properties === "nav");
434
+ if (s) {
435
+ const n = Object.values(e.records).find(
436
+ (r) => r.uri.endsWith(s.attr.href || "")
416
437
  );
417
- if (t && !t.dir) {
418
- const o = new y(await t.string()), i = be(t.uri);
419
- return Re(o, { basePath: i, baseUrl: s });
438
+ if (n && !n.dir) {
439
+ const r = new y(await n.string()), o = we(n.uri);
440
+ return Pe(r, { basePath: o, baseUrl: i });
420
441
  }
421
442
  }
422
- }, te = (n, {
443
+ }, Z = (t, {
423
444
  opfBasePath: e,
424
- baseUrl: s,
425
- prefix: r
445
+ baseUrl: i,
446
+ prefix: s
426
447
  }) => {
427
- const t = n?.childNamed(`${r}content`)?.attr.src || "", o = {
428
- title: n?.descendantWithPath(`${r}navLabel.${r}text`)?.val || "",
429
- path: I(e, t),
430
- href: I(s, e, t),
448
+ const n = t?.childNamed(`${s}content`)?.attr.src || "", r = {
449
+ title: t?.descendantWithPath(`${s}navLabel.${s}text`)?.val || "",
450
+ path: S(e, n),
451
+ href: S(i, e, n),
431
452
  contents: []
432
- }, i = n.childrenNamed(`${r}navPoint`);
433
- return i && i.length > 0 && (o.contents = i.map(
434
- (a) => te(a, { opfBasePath: e, baseUrl: s, prefix: r })
435
- )), o;
436
- }, je = (n, { opfBasePath: e, baseUrl: s }) => {
437
- const r = [], t = n.name;
438
- let o = "";
439
- return t.indexOf(":") !== -1 && (o = `${t.split(":")[0]}:`), n.childNamed(`${o}navMap`)?.childrenNamed(`${o}navPoint`).forEach((i) => {
440
- r.push(te(i, { opfBasePath: e, baseUrl: s, prefix: o }));
441
- }), r;
442
- }, Oe = async ({
443
- opfData: n,
453
+ }, o = t.childrenNamed(`${s}navPoint`);
454
+ return o && o.length > 0 && (r.contents = o.map(
455
+ (a) => Z(a, { opfBasePath: e, baseUrl: i, prefix: s })
456
+ )), r;
457
+ }, Oe = (t, { opfBasePath: e, baseUrl: i }) => {
458
+ const s = [], n = t.name;
459
+ let r = "";
460
+ return n.indexOf(":") !== -1 && (r = `${n.split(":")[0]}:`), t.childNamed(`${r}navMap`)?.childrenNamed(`${r}navPoint`).forEach((o) => {
461
+ s.push(Z(o, { opfBasePath: e, baseUrl: i, prefix: r }));
462
+ }), s;
463
+ }, ze = async ({
464
+ opfData: t,
444
465
  opfBasePath: e,
445
- baseUrl: s,
446
- archive: r
466
+ baseUrl: i,
467
+ archive: s
447
468
  }) => {
448
- const o = n.childNamed("spine")?.attr.toc;
449
- if (o) {
450
- const i = n.childNamed("manifest")?.childrenNamed("item").find((a) => a.attr.id === o);
451
- if (i) {
452
- const a = `${e}${e === "" ? "" : "/"}${i.attr.href}`, l = Object.values(r.records).find(
453
- (c) => c.uri.endsWith(a)
469
+ const r = t.childNamed("spine")?.attr.toc;
470
+ if (r) {
471
+ const o = t.childNamed("manifest")?.childrenNamed("item").find((a) => a.attr.id === r);
472
+ if (o) {
473
+ const a = `${e}${e === "" ? "" : "/"}${o.attr.href}`, c = Object.values(s.records).find(
474
+ (d) => d.uri.endsWith(a)
454
475
  );
455
- if (l && !l.dir) {
456
- const c = new y(await l.string());
457
- return je(c, { opfBasePath: e, baseUrl: s });
476
+ if (c && !c.dir) {
477
+ const d = new y(await c.string());
478
+ return Oe(d, { opfBasePath: e, baseUrl: i });
458
479
  }
459
480
  }
460
481
  }
461
- }, De = async (n, e, { baseUrl: s }) => {
462
- const { basePath: r } = F(e) || {}, t = await Pe(n, e, {
463
- baseUrl: s
482
+ }, Be = async (t, e, { baseUrl: i }) => {
483
+ const { basePath: s } = E(e) || {}, n = await je(t, e, {
484
+ baseUrl: i
464
485
  });
465
- if (t)
466
- return t;
467
- const o = await Oe({
468
- opfData: n,
469
- opfBasePath: r,
486
+ if (n)
487
+ return n;
488
+ const r = await ze({
489
+ opfData: t,
490
+ opfBasePath: s,
470
491
  archive: e,
471
- baseUrl: s
492
+ baseUrl: i
472
493
  });
473
- if (o)
474
- return o;
475
- }, Me = (n, { baseUrl: e }) => {
476
- const s = [...n.records].sort(
477
- (t, o) => D(t.uri, o.uri)
478
- ), r = (t, o, i, a, l) => {
479
- const c = t.find((g) => g.title === o), [d, ...p] = i;
480
- return c ? d ? [
481
- ...t.filter((b) => b !== c),
494
+ if (r)
495
+ return r;
496
+ }, De = (t, { baseUrl: e }) => {
497
+ const i = [...t.records].sort(
498
+ (n, r) => O(n.uri, r.uri)
499
+ ), s = (n, r, o, a, c) => {
500
+ const d = n.find((g) => g.title === r), [l, ...p] = o;
501
+ return d ? l ? [
502
+ ...n.filter((b) => b !== d),
482
503
  {
483
- ...c,
504
+ ...d,
484
505
  contents: [
485
- ...c.contents,
486
- ...r(
487
- c.contents,
488
- d,
506
+ ...d.contents,
507
+ ...s(
508
+ d.contents,
509
+ l,
489
510
  p,
490
511
  a,
491
- l
512
+ c
492
513
  )
493
514
  ]
494
515
  }
495
- ] : c.path.split("/").length > l.split("/").length ? [
496
- ...t.filter((b) => b !== c),
516
+ ] : d.path.split("/").length > c.split("/").length ? [
517
+ ...n.filter((b) => b !== d),
497
518
  {
498
- ...c,
499
- path: l,
519
+ ...d,
520
+ path: c,
500
521
  href: a
501
522
  }
502
- ] : t : d ? [
503
- ...t,
523
+ ] : n : l ? [
524
+ ...n,
504
525
  {
505
- contents: r(
526
+ contents: s(
506
527
  [],
507
- d,
528
+ l,
508
529
  p,
509
530
  a,
510
- l
531
+ c
511
532
  ),
512
533
  href: a,
513
- path: l,
514
- title: o
534
+ path: c,
535
+ title: r
515
536
  }
516
537
  ] : [
517
- ...t,
538
+ ...n,
518
539
  {
519
540
  contents: [],
520
541
  href: a,
521
- path: l,
522
- title: o
542
+ path: c,
543
+ title: r
523
544
  }
524
545
  ];
525
546
  };
526
- return s.reduce((t, o) => {
527
- if (o.dir) return t;
528
- const i = o.uri.split("/").slice(0, -1), [a, ...l] = i;
529
- if (!a) return t;
530
- const c = I(e, encodeURI(o.uri)).replace(/\/$/, ""), d = o.uri.replace(/\/$/, "");
531
- return r(t, a, l, c, d);
547
+ return i.reduce((n, r) => {
548
+ if (r.dir) return n;
549
+ const o = r.uri.split("/").slice(0, -1), [a, ...c] = o;
550
+ if (!a) return n;
551
+ const d = S(e, encodeURI(r.uri)).replace(/\/$/, ""), l = r.uri.replace(/\/$/, "");
552
+ return s(n, a, c, d, l);
532
553
  }, []);
533
- }, Ue = async (n, { baseUrl: e }) => {
534
- const { data: s } = F(n) || {};
535
- if (s && !s.dir) {
536
- const t = new y(await s.string());
537
- return await De(t, n, { baseUrl: e }) || [];
554
+ }, Me = async (t, { baseUrl: e }) => {
555
+ const { data: i } = E(t) || {};
556
+ if (i && !i.dir) {
557
+ const n = new y(await i.string());
558
+ return await Be(n, t, { baseUrl: e }) || [];
538
559
  }
539
- const r = Me(n, { baseUrl: e });
540
- if (r.length !== 0)
541
- return r;
542
- }, ze = ({ archive: n, baseUrl: e }) => async (s) => {
543
- if (s.nav) return s;
544
- const r = await Ue(n, { baseUrl: e });
545
- return r ? {
546
- ...s,
560
+ const s = De(t, { baseUrl: e });
561
+ if (s.length !== 0)
562
+ return s;
563
+ }, Ue = ({ archive: t, baseUrl: e }) => async (i) => {
564
+ if (i.nav) return i;
565
+ const s = await Me(t, { baseUrl: e });
566
+ return s ? {
567
+ ...i,
547
568
  nav: {
548
- toc: r
569
+ toc: s
549
570
  }
550
- } : s;
551
- }, Be = async (n, { baseUrl: e = "" } = {}) => {
552
- const s = [
553
- Ie({ archive: n, baseUrl: e }),
554
- Se({ archive: n }),
555
- $e({ archive: n }),
556
- Ce({ archive: n }),
557
- Le({ archive: n }),
558
- Fe({ archive: n }),
559
- ze({ archive: n, baseUrl: e })
571
+ } : i;
572
+ }, Ve = async (t, { baseUrl: e = "" } = {}) => {
573
+ const i = [
574
+ Ie({ archive: t, baseUrl: e }),
575
+ ke({ archive: t }),
576
+ xe({ archive: t }),
577
+ Ce({ archive: t }),
578
+ We({ archive: t }),
579
+ Ee({ archive: t }),
580
+ Ue({ archive: t, baseUrl: e })
560
581
  ];
561
582
  try {
562
- const r = Ee({ archive: n, baseUrl: e })(), t = await s.reduce(async (o, i) => await i(await o), r);
563
- if (m.log("Generated manifest", t), process.env.NODE_ENV === "development" && m.isEnabled()) {
564
- const o = JSON.stringify(t, null, 2);
583
+ const s = Re({ archive: t, baseUrl: e })(), n = await i.reduce(async (r, o) => await o(await r), s);
584
+ if (m.log("Generated manifest", n), process.env.NODE_ENV === "development" && m.isEnabled()) {
585
+ const r = JSON.stringify(n, null, 2);
565
586
  m.groupCollapsed(...m.getGroupArgs("Generated manifest")), m.log(`
566
- ${o}`), m.groupEnd();
587
+ ${r}`), m.groupEnd();
567
588
  }
568
- return t;
569
- } catch (r) {
570
- throw m.error(r), r;
589
+ return n;
590
+ } catch (s) {
591
+ throw m.error(s), s;
571
592
  }
572
- }, Xe = (n) => {
573
- const e = n.descendantWithPath("head")?.childrenNamed("meta").find((s) => s.attr.name === "calibre:cover");
593
+ }, Xe = (t) => {
594
+ const e = t.descendantWithPath("head")?.childrenNamed("meta").find((i) => i.attr.name === "calibre:cover");
574
595
  return !!(e && e.attr.name === "calibre:cover");
575
- }, Ve = (n) => n.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(
596
+ }, He = (t) => t.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(
576
597
  (e) => e.attr.width === "100%" && e.attr.preserveAspectRatio === "none"
577
- ), He = ({ archive: n, resourcePath: e }) => async (s) => {
578
- const r = Object.values(n.records).find(
579
- (t) => t.uri === e && !t.dir
598
+ ), _e = ({ archive: t, resourcePath: e }) => async (i) => {
599
+ const s = Object.values(t.records).find(
600
+ (n) => n.uri === e && !n.dir
580
601
  );
581
- if (r && !r.dir && r.basename.endsWith(".xhtml")) {
582
- const t = s.body ?? await r.string(), o = new y(t);
583
- if (Xe(o)) {
584
- const i = Ve(o);
585
- return i && delete i.attr.preserveAspectRatio, {
586
- ...s,
587
- body: o?.toString()
602
+ if (s && !s.dir && s.basename.endsWith(".xhtml")) {
603
+ const n = i.body ?? await s.string(), r = new y(n);
604
+ if (Xe(r)) {
605
+ const o = He(r);
606
+ return o && delete o.attr.preserveAspectRatio, {
607
+ ...i,
608
+ body: r?.toString()
588
609
  };
589
610
  }
590
611
  }
591
- return s;
592
- }, _e = ({ archive: n, resourcePath: e }) => async (s) => He({ archive: n, resourcePath: e })(s), Ge = ({ archive: n, resourcePath: e }) => async (s) => {
593
- const r = Object.values(n.records).find(
594
- (t) => t.uri === e && !t.dir
612
+ return i;
613
+ }, Ge = ({ archive: t, resourcePath: e }) => async (i) => _e({ archive: t, resourcePath: e })(i), qe = ({ archive: t, resourcePath: e }) => async (i) => {
614
+ const s = Object.values(t.records).find(
615
+ (n) => n.uri === e && !n.dir
595
616
  );
596
- if (r && !r.dir && r.basename.endsWith(".css")) {
597
- const o = (s.body ?? await r.string()).replaceAll(
617
+ if (s && !s.dir && s.basename.endsWith(".css")) {
618
+ const r = (i.body ?? await s.string()).replaceAll(
598
619
  "-webkit-writing-mode",
599
620
  "writing-mode"
600
621
  );
601
622
  return {
602
- ...s,
603
- body: o
623
+ ...i,
624
+ body: r
604
625
  };
605
626
  }
606
- return s;
607
- }, qe = async (n, e) => {
608
- const r = await F(n).data?.string();
609
- if (r) {
610
- const t = new y(r), o = Q(t, n, () => "");
611
- if (o.find(
627
+ return i;
628
+ }, Je = async (t, e) => {
629
+ const s = await E(t).data?.string();
630
+ if (s) {
631
+ const n = new y(s), r = K(n, t, () => "");
632
+ if (r.find(
612
633
  (a) => e.endsWith(a.href)
613
634
  )?.mediaType)
614
635
  return {
615
- mediaType: o.find((a) => e.endsWith(a.href))?.mediaType
636
+ mediaType: r.find((a) => e.endsWith(a.href))?.mediaType
616
637
  };
617
638
  }
618
639
  return {
619
- mediaType: Je(e)
640
+ mediaType: Ke(e)
620
641
  };
621
- }, Je = (n) => {
622
- if (n.endsWith(".css"))
642
+ }, Ke = (t) => {
643
+ if (t.endsWith(".css"))
623
644
  return "text/css; charset=UTF-8";
624
- if (n.endsWith(".jpg"))
645
+ if (t.endsWith(".jpg"))
625
646
  return "image/jpg";
626
- if (n.endsWith(".xhtml"))
647
+ if (t.endsWith(".xhtml"))
627
648
  return "application/xhtml+xml";
628
- if (n.endsWith(".mp4"))
649
+ if (t.endsWith(".mp4"))
629
650
  return "video/mp4";
630
- if (n.endsWith(".svg"))
651
+ if (t.endsWith(".svg"))
631
652
  return "image/svg+xml";
632
- }, Ke = ({ archive: n, resourcePath: e }) => async (s) => {
633
- const r = Object.values(n.records).find(
634
- (o) => o.uri === e && !o.dir
653
+ }, Ye = ({ archive: t, resourcePath: e }) => async (i) => {
654
+ const s = Object.values(t.records).find(
655
+ (r) => r.uri === e && !r.dir
635
656
  );
636
- if (!r || r.dir) return s;
637
- const t = await qe(n, e);
657
+ if (!s || s.dir) return i;
658
+ const n = await Je(t, e);
638
659
  return {
639
- ...s,
660
+ ...i,
640
661
  params: {
641
- ...s.params,
642
- ...r?.encodingFormat && {
643
- contentType: r.encodingFormat
662
+ ...i.params,
663
+ ...s?.encodingFormat && {
664
+ contentType: s.encodingFormat
644
665
  },
645
- ...t.mediaType && {
646
- contentType: t.mediaType
666
+ ...n.mediaType && {
667
+ contentType: n.mediaType
647
668
  }
648
669
  }
649
670
  };
650
- }, K = [
671
+ }, _ = [
651
672
  "div",
652
673
  "span",
653
674
  "p",
@@ -698,57 +719,57 @@ ${o}`), m.groupEnd();
698
719
  "canvas",
699
720
  "script",
700
721
  "style"
701
- ], Ye = ({ archive: n, resourcePath: e }) => async (s) => {
702
- const r = Object.values(n.records).find(
703
- (t) => t.uri === e && !t.dir
722
+ ], Qe = ({ archive: t, resourcePath: e }) => async (i) => {
723
+ const s = Object.values(t.records).find(
724
+ (n) => n.uri === e && !n.dir
704
725
  );
705
- if (r && !r.dir && r.basename.endsWith(".xhtml")) {
706
- const t = s.body ?? await r.string();
726
+ if (s && !s.dir && s.basename.endsWith(".xhtml")) {
727
+ const n = i.body ?? await s.string();
707
728
  if (!new RegExp(
708
- `<(${K.join("|")})[\\s/>]`,
729
+ `<(${_.join("|")})[\\s/>]`,
709
730
  "i"
710
- ).test(t))
711
- return s;
712
- const i = new RegExp(
713
- `<(${K.join("|")})(\\s[^>]*)?\\s*/>`,
731
+ ).test(n))
732
+ return i;
733
+ const o = new RegExp(
734
+ `<(${_.join("|")})(\\s[^>]*)?\\s*/>`,
714
735
  "gi"
715
- ), a = t.replace(
716
- i,
717
- (l, c, d = "") => `<${c} ${d.trim()}></${c}>`
736
+ ), a = n.replace(
737
+ o,
738
+ (c, d, l = "") => `<${d} ${l.trim()}></${d}>`
718
739
  );
719
740
  return {
720
- ...s,
741
+ ...i,
721
742
  body: a
722
743
  };
723
744
  }
724
- return s;
725
- }, Qe = async (n, e) => {
726
- const s = Object.values(n.records).find(
727
- (o) => o.uri === e && !o.dir
745
+ return i;
746
+ }, Ze = async (t, e) => {
747
+ const i = Object.values(t.records).find(
748
+ (r) => r.uri === e && !r.dir
728
749
  );
729
- if (!s || s.dir)
750
+ if (!i || i.dir)
730
751
  throw new Error(`no file found for resourcePath:${e}`);
731
- const r = {
752
+ const s = {
732
753
  params: {}
733
- }, t = [
734
- Ke({ archive: n, resourcePath: e }),
735
- Ye({ archive: n, resourcePath: e }),
736
- Ge({ archive: n, resourcePath: e }),
737
- _e({ archive: n, resourcePath: e })
754
+ }, n = [
755
+ Ye({ archive: t, resourcePath: e }),
756
+ Qe({ archive: t, resourcePath: e }),
757
+ qe({ archive: t, resourcePath: e }),
758
+ Ge({ archive: t, resourcePath: e })
738
759
  ];
739
760
  try {
740
- const o = await t.reduce(async (i, a) => await a(await i), Promise.resolve(r));
741
- return m.log("Generated resource", e, o), {
742
- ...o,
743
- body: o.body ?? await s.blob()
761
+ const r = await n.reduce(async (o, a) => await a(await o), Promise.resolve(s));
762
+ return m.log("Generated resource", e, r), {
763
+ ...r,
764
+ body: r.body ?? await i.blob()
744
765
  };
745
- } catch (o) {
746
- throw m.error(o), o;
766
+ } catch (r) {
767
+ throw m.error(r), r;
747
768
  }
748
769
  };
749
- class Ze {
770
+ class et {
750
771
  constructor(e) {
751
- this.cleanArchiveAfter = e, this.state$ = new ue({
772
+ this.cleanArchiveAfter = e, this.state$ = new me({
752
773
  status: "idle",
753
774
  locks: 0
754
775
  });
@@ -757,121 +778,205 @@ class Ze {
757
778
  this.state$.next({ ...this.state$.getValue(), ...e });
758
779
  }
759
780
  get locks$() {
760
- return this.state$.pipe(v(({ locks: e }) => e));
781
+ return this.state$.pipe($(({ locks: e }) => e));
761
782
  }
762
783
  get state() {
763
784
  return this.state$.getValue();
764
785
  }
765
786
  get isUnlocked$() {
766
787
  return this.locks$.pipe(
767
- v((e) => e <= 0),
768
- he(),
769
- ge()
788
+ $((e) => e <= 0),
789
+ ue(),
790
+ fe()
770
791
  );
771
792
  }
772
793
  get overTTL$() {
773
794
  return this.isUnlocked$.pipe(
774
- A(
775
- (e) => e ? this.cleanArchiveAfter === 1 / 0 ? H : ye(this.cleanArchiveAfter) : H
795
+ I(
796
+ (e) => e ? this.cleanArchiveAfter === 1 / 0 ? X : he(this.cleanArchiveAfter) : X
776
797
  )
777
798
  );
778
799
  }
779
800
  }
780
- const et = ({
781
- getArchive: n,
801
+ const tt = ({
802
+ getArchive: t,
782
803
  cleanArchiveAfter: e = 300 * 1e3
783
804
  // 5mn
784
805
  }) => {
785
- const s = new C(), r = new C(), t = new C(), o = {}, i = s.pipe(
786
- O((c) => {
787
- const d = o[c];
788
- if (!d || d.state.status !== "idle") return B;
806
+ const i = new L(), s = new L(), n = new L(), r = {}, o = i.pipe(
807
+ q((d) => {
808
+ const l = r[d];
809
+ if (!l || l.state.status !== "idle") return M;
789
810
  let p = !1;
790
811
  const g = (h) => {
791
812
  m.debug(`Cleaning up archive with key: ${h}`);
792
- const x = o[h];
793
- delete o[h], p || (x?.state.archive?.close(), p = !0);
813
+ const F = r[h];
814
+ delete r[h], p || (F?.state.archive?.close(), p = !0);
794
815
  };
795
- d.update({
816
+ l.update({
796
817
  status: "loading"
797
818
  });
798
- const b = d.locks$, E = d.isUnlocked$, u = b.pipe(
799
- le(),
800
- R(([h, x]) => x > h),
801
- pe(!0)
819
+ const b = l.locks$, R = l.isUnlocked$, f = b.pipe(
820
+ ce(),
821
+ C(([h, F]) => F > h),
822
+ de(!0)
802
823
  );
803
- return T(n(c)).pipe(
824
+ return A(t(d)).pipe(
804
825
  P((h) => {
805
- d.update({
826
+ l.update({
806
827
  archive: h,
807
828
  status: "success"
808
829
  });
809
830
  }),
810
- W((h) => (g(c), d.update({
831
+ j((h) => (g(d), l.update({
811
832
  status: "error",
812
833
  error: h
813
- }), B)),
814
- A(() => {
815
- const h = u.pipe(
816
- A(() => t),
817
- A(() => E),
818
- R((S) => S)
834
+ }), M)),
835
+ I(() => {
836
+ const h = f.pipe(
837
+ I(() => n),
838
+ I(() => R),
839
+ C((W) => W)
819
840
  );
820
- return X(h, d.overTTL$).pipe(
841
+ return U(h, l.overTTL$).pipe(
821
842
  V(),
822
843
  P(() => {
823
- g(c);
844
+ g(d);
824
845
  })
825
846
  );
826
847
  })
827
848
  );
828
849
  }),
829
- me(r)
830
- ), a = (c) => {
831
- let d = !1;
832
- const p = o[c] ?? new Ze(e);
833
- o[c] = p, p.update({
850
+ le(s)
851
+ ), a = (d) => {
852
+ let l = !1;
853
+ const p = r[d] ?? new et(e);
854
+ r[d] = p, p.update({
834
855
  locks: p.state.locks + 1
835
856
  });
836
857
  const g = () => {
837
- d || (d = !0, p.update({
858
+ l || (l = !0, p.update({
838
859
  locks: p.state.locks - 1
839
860
  }));
840
861
  };
841
- s.next(c);
862
+ i.next(d);
842
863
  const b = p.state$.pipe(
843
- v(({ archive: u }) => u),
844
- R((u) => !!u)
845
- ), E = p.state$.pipe(
846
- P(({ error: u }) => {
847
- if (u)
848
- throw u;
864
+ $(({ archive: f }) => f),
865
+ C((f) => !!f)
866
+ ), R = p.state$.pipe(
867
+ P(({ error: f }) => {
868
+ if (f)
869
+ throw f;
849
870
  }),
850
- fe()
871
+ pe()
851
872
  );
852
- return X(b, E).pipe(
873
+ return U(b, R).pipe(
853
874
  V(),
854
- v((u) => ({ archive: u, release: g })),
855
- W((u) => {
856
- throw g(), u;
875
+ $((f) => ({ archive: f, release: g })),
876
+ j((f) => {
877
+ throw g(), f;
857
878
  })
858
879
  );
859
- }, l = () => {
860
- t.next();
880
+ }, c = () => {
881
+ n.next();
861
882
  };
862
- return i.subscribe(), {
883
+ return o.subscribe(), {
863
884
  access: a,
864
- purge: l,
865
- _archives: o
885
+ purge: c,
886
+ _archives: r
866
887
  };
888
+ }, G = (t) => t ? /^\d+$/.test(t) ? {
889
+ valid: !0,
890
+ value: Number.parseInt(t, 10)
891
+ } : {
892
+ valid: !1,
893
+ value: void 0
894
+ } : {
895
+ valid: !0,
896
+ value: void 0
897
+ }, nt = (t) => {
898
+ if (!t.toLowerCase().startsWith("bytes="))
899
+ return {
900
+ kind: "missing"
901
+ };
902
+ const e = t.slice(6).trim();
903
+ if (!e)
904
+ return {
905
+ kind: "invalid"
906
+ };
907
+ if (e.includes(","))
908
+ return {
909
+ kind: "multi"
910
+ };
911
+ const i = /^(\d*)-(\d*)$/.exec(e);
912
+ if (!i)
913
+ return {
914
+ kind: "invalid"
915
+ };
916
+ const [, s = "", n = ""] = i, r = G(s.trim()), o = G(n.trim());
917
+ return !r.valid || !o.valid ? {
918
+ kind: "invalid"
919
+ } : {
920
+ kind: "single",
921
+ start: r.value,
922
+ end: o.value
923
+ };
924
+ }, rt = ({
925
+ body: t,
926
+ contentType: e,
927
+ rangeHeader: i
928
+ }) => {
929
+ const s = new Headers(), n = t instanceof Blob ? t : new Blob([t]), r = n.size;
930
+ if (e && s.set("Content-Type", e), s.set("Accept-Ranges", "bytes"), s.set("Content-Length", String(r)), !i)
931
+ return new Response(t, {
932
+ status: 200,
933
+ headers: s
934
+ });
935
+ const o = nt(i);
936
+ if (o.kind === "missing" || o.kind === "multi")
937
+ return new Response(t, {
938
+ status: 200,
939
+ headers: s
940
+ });
941
+ if (o.kind === "invalid")
942
+ return new Response(null, {
943
+ status: 416,
944
+ headers: {
945
+ "Content-Range": `bytes */${r}`
946
+ }
947
+ });
948
+ let a = o.start, c = o.end;
949
+ if (a === void 0 && c === void 0)
950
+ return new Response(null, {
951
+ status: 416,
952
+ headers: {
953
+ "Content-Range": `bytes */${r}`
954
+ }
955
+ });
956
+ if (a === void 0) {
957
+ const l = Math.min(c ?? 0, r);
958
+ a = Math.max(0, r - l), c = r - 1;
959
+ } else (c === void 0 || c >= r) && (c = r - 1);
960
+ if (a < 0 || c < 0 || a >= r || c >= r || a > c)
961
+ return new Response(null, {
962
+ status: 416,
963
+ headers: {
964
+ "Content-Range": `bytes */${r}`
965
+ }
966
+ });
967
+ const d = n.slice(a, c + 1);
968
+ return s.set("Content-Length", String(d.size)), s.set("Content-Range", `bytes ${a}-${c}/${r}`), new Response(d, {
969
+ status: 206,
970
+ headers: s
971
+ });
867
972
  };
868
- class tt {
973
+ class st {
869
974
  constructor({
870
975
  onError: e,
871
- onManifestSuccess: s,
872
- ...r
976
+ onManifestSuccess: i,
977
+ ...s
873
978
  }) {
874
- this.onError = (t) => (console.error(t), new Response(String(t), { status: 500 })), this.epubLoader = et(r), this.onManifestSuccess = s ?? (({ manifest: t }) => Promise.resolve(t)), this.onError = e ?? this.onError;
979
+ this.onError = (n) => (console.error(n), new Response(String(n), { status: 500 })), this.epubLoader = tt(s), this.onManifestSuccess = i ?? (({ manifest: n }) => Promise.resolve(n)), this.onError = e ?? this.onError;
875
980
  }
876
981
  prune() {
877
982
  this.epubLoader.purge();
@@ -881,99 +986,111 @@ class tt {
881
986
  }
882
987
  accessArchiveWithoutLock(e) {
883
988
  return this.accessArchive(e).pipe(
884
- v(({ archive: s, release: r }) => (r(), s))
989
+ $(({ archive: i, release: s }) => (s(), i))
885
990
  );
886
991
  }
887
- fetchManifest({ key: e, baseUrl: s }) {
888
- const r = this.accessArchive(e).pipe(
889
- O(({ archive: t, release: o }) => T(
890
- Be(t, { baseUrl: s })
992
+ withArchiveResponse({
993
+ key: e,
994
+ getResponse: i
995
+ }) {
996
+ const s = this.accessArchive(e).pipe(
997
+ q(
998
+ ({ archive: n, release: r }) => A(i(n)).pipe(
999
+ ge(() => {
1000
+ r();
1001
+ })
1002
+ )
1003
+ ),
1004
+ j((n) => ye(this.onError(n)))
1005
+ );
1006
+ return be(s);
1007
+ }
1008
+ fetchManifest({ key: e, baseUrl: i }) {
1009
+ return this.withArchiveResponse({
1010
+ key: e,
1011
+ getResponse: (s) => A(
1012
+ Ve(s, { baseUrl: i })
891
1013
  ).pipe(
892
- A(
893
- (a) => T(this.onManifestSuccess({ manifest: a, archive: t }))
1014
+ I(
1015
+ (r) => A(this.onManifestSuccess({ manifest: r, archive: s }))
894
1016
  ),
895
- v(
896
- (a) => new Response(JSON.stringify(a), {
1017
+ $(
1018
+ (r) => new Response(JSON.stringify(r), {
897
1019
  status: 200
898
1020
  })
899
- ),
900
- _(() => {
901
- o();
902
- })
903
- )),
904
- W((t) => G(this.onError(t)))
905
- );
906
- return q(r);
1021
+ )
1022
+ )
1023
+ });
907
1024
  }
908
1025
  fetchResource({
909
1026
  key: e,
910
- resourcePath: s
1027
+ resourcePath: i,
1028
+ request: s
911
1029
  }) {
912
- const r = this.accessArchive(e).pipe(
913
- O(({ archive: t, release: o }) => {
914
- const i = s.replaceAll("file://", "");
915
- return T(
916
- Qe(t, i)
1030
+ return this.withArchiveResponse({
1031
+ key: e,
1032
+ getResponse: (n) => {
1033
+ const r = i.replaceAll("file://", "");
1034
+ return A(
1035
+ Ze(n, r)
917
1036
  ).pipe(
918
- v(
919
- (l) => new Response(l.body, {
920
- status: 200,
921
- headers: {
922
- ...l.params.contentType && {
923
- "Content-Type": l.params.contentType
924
- }
925
- }
1037
+ $(
1038
+ (a) => rt({
1039
+ body: a.body ?? "",
1040
+ contentType: a.params.contentType,
1041
+ rangeHeader: s?.headers.get("range")
926
1042
  })
927
- ),
928
- _(() => {
929
- o();
930
- })
1043
+ )
931
1044
  );
932
- }),
933
- W((t) => G(this.onError(t)))
934
- );
935
- return q(r);
1045
+ }
1046
+ });
936
1047
  }
937
1048
  }
938
- class mt extends tt {
1049
+ class ht extends st {
939
1050
  constructor({
940
1051
  getUriInfo: e,
941
- ...s
1052
+ ...i
942
1053
  }) {
943
- super(s), this.getUriInfo = e, this.fetchEventListener = this.fetchEventListener.bind(this);
1054
+ super(i), this.getUriInfo = e, this.fetchEventListener = this.fetchEventListener.bind(this);
944
1055
  }
945
1056
  fetchEventListener(e) {
946
1057
  try {
947
- const s = this.getUriInfo(e);
948
- if (!s) return;
949
- const r = J(s.baseUrl), t = e.request.url.substring(
950
- r.length + 1
951
- ), [o = ""] = t.split("/"), i = decodeURIComponent(
952
- J(t.substring(o.length + 1))
1058
+ const i = this.getUriInfo(e);
1059
+ if (!i) return;
1060
+ const s = H(i.baseUrl), n = e.request.url.substring(
1061
+ s.length + 1
1062
+ ), [r = ""] = n.split("/"), o = decodeURIComponent(
1063
+ H(n.substring(r.length + 1))
1064
+ );
1065
+ n.endsWith("/manifest") ? e.respondWith(
1066
+ this.fetchManifest({ key: r, baseUrl: `${s}/${r}/` })
1067
+ ) : e.respondWith(
1068
+ this.fetchResource({
1069
+ key: r,
1070
+ resourcePath: o,
1071
+ request: e.request
1072
+ })
953
1073
  );
954
- t.endsWith("/manifest") ? e.respondWith(
955
- this.fetchManifest({ key: o, baseUrl: `${r}/${o}/` })
956
- ) : e.respondWith(this.fetchResource({ key: o, resourcePath: i }));
957
- } catch (s) {
958
- e.respondWith(new Response(String(s), { status: 500 }));
1074
+ } catch (i) {
1075
+ e.respondWith(new Response(String(i), { status: 500 }));
959
1076
  }
960
1077
  }
961
1078
  }
962
1079
  export {
963
- mt as ServiceWorkerStreamer,
964
- tt as Streamer,
965
- pt as configure,
966
- it as createArchiveFromArrayBufferList,
967
- at as createArchiveFromJszip,
968
- ct as createArchiveFromLibArchive,
969
- dt as createArchiveFromText,
970
- lt as createArchiveFromUrls,
971
- Be as generateManifestFromArchive,
972
- Qe as generateResourceFromArchive,
973
- F as getArchiveOpfInfo,
974
- be as getUriBasePath,
975
- $ as getUriBasename,
976
- J as removeTrailingSlash,
977
- D as sortByTitleComparator
1080
+ ht as ServiceWorkerStreamer,
1081
+ st as Streamer,
1082
+ ft as configure,
1083
+ dt as createArchiveFromArrayBufferList,
1084
+ lt as createArchiveFromJszip,
1085
+ pt as createArchiveFromLibArchive,
1086
+ mt as createArchiveFromText,
1087
+ ut as createArchiveFromUrls,
1088
+ Ve as generateManifestFromArchive,
1089
+ Ze as generateResourceFromArchive,
1090
+ E as getArchiveOpfInfo,
1091
+ we as getUriBasePath,
1092
+ w as getUriBasename,
1093
+ H as removeTrailingSlash,
1094
+ O as sortByTitleComparator
978
1095
  };
979
1096
  //# sourceMappingURL=index.js.map