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