react-book-reader 1.0.0 → 1.1.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.
@@ -0,0 +1,681 @@
1
+ import { f as z, p as V, t as X, a as W } from "./view-C6hqGjnD.js";
2
+ const b = {
3
+ CONTAINER: "urn:oasis:names:tc:opendocument:xmlns:container",
4
+ XHTML: "http://www.w3.org/1999/xhtml",
5
+ OPF: "http://www.idpf.org/2007/opf",
6
+ EPUB: "http://www.idpf.org/2007/ops",
7
+ DC: "http://purl.org/dc/elements/1.1/",
8
+ ENC: "http://www.w3.org/2001/04/xmlenc#",
9
+ NCX: "http://www.daisy.org/z3986/2005/ncx/",
10
+ XLINK: "http://www.w3.org/1999/xlink",
11
+ SMIL: "http://www.w3.org/ns/SMIL"
12
+ }, I = {
13
+ XML: "application/xml",
14
+ NCX: "application/x-dtbncx+xml",
15
+ XHTML: "application/xhtml+xml",
16
+ HTML: "text/html",
17
+ CSS: "text/css",
18
+ SVG: "image/svg+xml",
19
+ JS: /\/(x-)?(javascript|ecmascript)/
20
+ }, T = {
21
+ a11y: "http://www.idpf.org/epub/vocab/package/a11y/#",
22
+ dcterms: "http://purl.org/dc/terms/",
23
+ marc: "http://id.loc.gov/vocabulary/",
24
+ media: "http://www.idpf.org/epub/vocab/overlays/#",
25
+ onix: "http://www.editeur.org/ONIX/book/codelists/current.html#",
26
+ rendition: "http://www.idpf.org/vocab/rendition/#",
27
+ schema: "http://schema.org/",
28
+ xsd: "http://www.w3.org/2001/XMLSchema#",
29
+ msv: "http://www.idpf.org/epub/vocab/structure/magazine/#",
30
+ prism: "http://www.prismstandard.org/specifications/3.0/PRISM_CV_Spec_3.0.htm#"
31
+ }, G = {
32
+ art: "artist",
33
+ aut: "author",
34
+ clr: "colorist",
35
+ edt: "editor",
36
+ ill: "illustrator",
37
+ nrt: "narrator",
38
+ trl: "translator",
39
+ pbl: "publisher"
40
+ }, J = {
41
+ "02": "isbn",
42
+ "06": "doi",
43
+ 15: "isbn",
44
+ 26: "doi",
45
+ 34: "issn"
46
+ }, B = (i) => i.toLowerCase().replace(/[-:](.)/g, (t, e) => e.toUpperCase()), K = (i) => i ? i.replace(/[\t\n\f\r ]+/g, " ").replace(/^[\t\n\f\r ]+/, "").replace(/[\t\n\f\r ]+$/, "") : "", Q = (i, t, e) => e ? (s) => s.getAttribute(i)?.split(/\s/)?.includes(t) : typeof t == "function" ? (s) => t(s.getAttribute(i)) : (s) => s.getAttribute(i) === t, U = (...i) => (t) => t ? Object.fromEntries(i.map((e) => [B(e), t.getAttribute(e)])) : null, L = (i) => K(i?.textContent), x = (i, t) => {
47
+ const e = i.lookupNamespaceURI(null) === t || i.lookupPrefix(t), s = e ? (r, o) => (n) => n.namespaceURI === t && n.localName === o : (r, o) => (n) => n.localName === o;
48
+ return {
49
+ $: (r, o) => [...r.children].find(s(r, o)),
50
+ $$: (r, o) => [...r.children].filter(s(r, o)),
51
+ $$$: e ? (r, o) => [...r.getElementsByTagNameNS(t, o)] : (r, o) => [...r.getElementsByTagName(o)]
52
+ };
53
+ }, M = (i, t) => {
54
+ try {
55
+ if (t.includes(":")) return new URL(i, t);
56
+ const e = "https://invalid.invalid/", s = new URL(i, e + t);
57
+ return s.search = "", decodeURI(s.href.replace(e, ""));
58
+ } catch (e) {
59
+ return console.warn(e), i;
60
+ }
61
+ }, q = (i) => /^(?!blob)\w+:/i.test(i), Y = (i, t) => {
62
+ if (!i) return t;
63
+ const e = i.replace(/\/$/, "").split("/"), s = t.replace(/\/$/, "").split("/"), r = (e.length > s.length ? e : s).findIndex((o, n) => e[n] !== s[n]);
64
+ return r < 0 ? "" : Array(e.length - r).fill("..").concat(s.slice(r)).join("/");
65
+ }, Z = (i) => i.slice(0, i.lastIndexOf("/") + 1), R = async (i, t, e) => {
66
+ const s = [];
67
+ i.replace(t, (...o) => (s.push(o), null));
68
+ const r = [];
69
+ for (const o of s) r.push(await e(...o));
70
+ return i.replace(t, () => r.shift());
71
+ }, tt = (i) => i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), O = (i) => {
72
+ for (const [e, s] of Object.entries(i))
73
+ s == null ? delete i[e] : Array.isArray(s) ? (i[e] = s.filter((r) => r).map((r) => typeof r == "object" && !Array.isArray(r) ? O(r) : r), i[e].length ? i[e].length === 1 && (i[e] = i[e][0]) : delete i[e]) : typeof s == "object" && (i[e] = O(s), Object.keys(s).length || delete i[e]);
74
+ const t = Object.keys(i);
75
+ return t.length === 1 && t[0] === "name" ? i[t[0]] : i;
76
+ }, et = (i) => {
77
+ const t = new Map(Object.entries(T)), e = i.documentElement.getAttributeNS(b.EPUB, "prefix") || i.documentElement.getAttribute("prefix");
78
+ if (e) for (const [, s, r] of e.matchAll(/(.+): +(.+)[ \t\r\n]*/g)) t.set(s, r);
79
+ return t;
80
+ }, F = (i, t) => {
81
+ if (!i) return null;
82
+ const [e, s] = i.split(":"), r = s ? e : null, o = s || e, n = t.get(r);
83
+ return n ? n + o : null;
84
+ }, st = (i) => {
85
+ const { $: t } = x(i, b.OPF), e = t(i.documentElement, "metadata"), s = Object.groupBy(e.children, (a) => a.namespaceURI === b.DC ? "dc" : a.namespaceURI === b.OPF && a.localName === "meta" ? a.hasAttribute("name") ? "legacyMeta" : "meta" : ""), r = e.getAttribute("xml:lang") ?? i.documentElement.getAttribute("xml:lang") ?? "und", o = et(i), n = (a) => {
86
+ const f = a.getAttribute("property"), w = a.getAttribute("scheme");
87
+ return {
88
+ property: F(f, o) ?? f,
89
+ scheme: F(w, o) ?? w,
90
+ lang: a.getAttribute("xml:lang"),
91
+ value: L(a),
92
+ props: c(a),
93
+ // `opf:` attributes from EPUB 2 & EPUB 3.1 (removed in EPUB 3.2)
94
+ attrs: Object.fromEntries(Array.from(a.attributes).filter((v) => v.namespaceURI === b.OPF).map((v) => [v.localName, v.value]))
95
+ };
96
+ }, l = Map.groupBy(s.meta ?? [], (a) => a.getAttribute("refines")), c = (a) => {
97
+ const f = l.get(a ? "#" + a.getAttribute("id") : null);
98
+ return f ? Object.groupBy(f.map(n), (w) => w.property) : null;
99
+ }, u = Object.fromEntries(Object.entries(Object.groupBy(s.dc, (a) => a.localName)).map(([a, f]) => [a, f.map(n)])), d = c() ?? {}, h = Object.fromEntries(s.legacyMeta?.map((a) => [a.getAttribute("name"), a.getAttribute("content")]) ?? []), p = (a) => a?.[0]?.value, g = (a, f) => p(a?.props?.[f]), m = (a) => {
100
+ if (!a) return null;
101
+ const f = a.props?.["alternate-script"] ?? [], w = a.attrs["alt-rep"];
102
+ if (!f.length && (!a.lang || a.lang === r) && !w) return a.value;
103
+ const v = { [a.lang ?? r]: a.value };
104
+ w && (v[a.attrs["alt-rep-lang"]] = w);
105
+ for (const D of f) v[D.lang] ??= D.value;
106
+ return v;
107
+ }, y = (a) => a ? {
108
+ name: m(a),
109
+ sortAs: m(a.props?.["file-as"]?.[0]) ?? a.attrs["file-as"],
110
+ role: a.props?.role?.filter((f) => f.scheme === T.marc + "relators")?.map((f) => f.value) ?? [a.attrs.role],
111
+ code: g(a, "term") ?? a.attrs.term,
112
+ scheme: g(a, "authority") ?? a.attrs.authority
113
+ } : null, E = (a) => ({
114
+ name: m(a),
115
+ // NOTE: webpub requires number but EPUB allows values like "2.2.1"
116
+ position: p(a.props?.["group-position"])
117
+ }), S = (a) => {
118
+ const { value: f } = a;
119
+ if (/^urn:/i.test(f)) return f;
120
+ if (/^doi:/i.test(f)) return `urn:${f}`;
121
+ const w = a.props?.["identifier-type"];
122
+ if (!w) {
123
+ const v = a.attrs.scheme;
124
+ return v ? /^(doi|isbn|uuid)$/i.test(v) ? `urn:${v}:${f}` : { scheme: v, value: f } : f;
125
+ }
126
+ if (w.scheme === T.onix + "codelist5") {
127
+ const v = J[w.value];
128
+ if (v) return `urn:${v}:${f}`;
129
+ }
130
+ return f;
131
+ }, $ = Object.groupBy(
132
+ d["belongs-to-collection"] ?? [],
133
+ (a) => g(a, "collection-type") === "series" ? "series" : "collection"
134
+ ), C = u.title?.find((a) => g(a, "title-type") === "main") ?? u.title?.[0], A = {
135
+ identifier: _(i),
136
+ title: m(C),
137
+ sortAs: m(C?.props?.["file-as"]?.[0]) ?? C?.attrs?.["file-as"] ?? h?.["calibre:title_sort"],
138
+ subtitle: u.title?.find((a) => g(a, "title-type") === "subtitle")?.value,
139
+ language: u.language?.map((a) => a.value),
140
+ description: p(u.description),
141
+ publisher: y(u.publisher?.[0]),
142
+ published: u.date?.find((a) => a.attrs.event === "publication")?.value ?? p(u.date),
143
+ modified: p(d[T.dcterms + "modified"]) ?? u.date?.find((a) => a.attrs.event === "modification")?.value,
144
+ subject: u.subject?.map(y),
145
+ belongsTo: {
146
+ collection: $.collection?.map(E),
147
+ series: $.series?.map(E) ?? h?.["calibre:series"] ? {
148
+ name: h?.["calibre:series"],
149
+ position: parseFloat(h?.["calibre:series_index"])
150
+ } : null
151
+ },
152
+ altIdentifier: u.identifier?.map(S),
153
+ source: u.source?.map(S),
154
+ // NOTE: not in webpub schema
155
+ rights: p(u.rights)
156
+ // NOTE: not in webpub schema
157
+ }, P = (a) => (f) => {
158
+ const w = new Set(f.role?.map((v) => G[v] ?? a));
159
+ return [w.size ? w : [a], f];
160
+ };
161
+ for (const [a, f] of [].concat(
162
+ u.creator?.map(y)?.map(P("author")) ?? [],
163
+ u.contributor?.map(y)?.map(P("contributor")) ?? []
164
+ ))
165
+ for (const w of a)
166
+ A[w] ? A[w].push(f) : A[w] = [f];
167
+ O(A), A.altIdentifier === A.identifier && delete A.altIdentifier;
168
+ const H = {}, N = {};
169
+ for (const [a, f] of Object.entries(d))
170
+ a.startsWith(T.rendition) ? H[B(a.replace(T.rendition, ""))] = p(f) : a.startsWith(T.media) && (N[B(a.replace(T.media, ""))] = p(f));
171
+ return N.duration && (N.duration = k(N.duration)), { metadata: A, rendition: H, media: N };
172
+ }, rt = (i, t = (e) => e) => {
173
+ const { $: e, $$: s, $$$: r } = x(i, b.XHTML), o = (m) => m ? decodeURI(t(m)) : null, n = (m) => (y) => {
174
+ const E = e(y, "a") ?? e(y, "span"), S = e(y, "ol"), $ = o(E?.getAttribute("href")), A = { label: L(E) || E?.getAttribute("title"), href: $, subitems: l(S) };
175
+ return m && (A.type = E?.getAttributeNS(b.EPUB, "type")?.split(/\s/)), A;
176
+ }, l = (m, y) => m ? s(m, "li").map(n(y)) : null, c = (m, y) => l(e(m, "ol"), y), u = r(i, "nav");
177
+ let d = null, h = null, p = null, g = [];
178
+ for (const m of u) {
179
+ const y = m.getAttributeNS(b.EPUB, "type")?.split(/\s/) ?? [];
180
+ y.includes("toc") ? d ??= c(m) : y.includes("page-list") ? h ??= c(m) : y.includes("landmarks") ? p ??= c(m, !0) : g.push({
181
+ label: L(m.firstElementChild),
182
+ type: y,
183
+ list: c(m)
184
+ });
185
+ }
186
+ return { toc: d, pageList: h, landmarks: p, others: g };
187
+ }, it = (i, t = (e) => e) => {
188
+ const { $: e, $$: s } = x(i, b.NCX), r = (c) => c ? decodeURI(t(c)) : null, o = (c) => {
189
+ const u = e(c, "navLabel"), d = e(c, "content"), h = L(u), p = r(d.getAttribute("src"));
190
+ if (c.localName === "navPoint") {
191
+ const g = s(c, "navPoint");
192
+ return { label: h, href: p, subitems: g.length ? g.map(o) : null };
193
+ }
194
+ return { label: h, href: p };
195
+ }, n = (c, u) => s(c, u).map(o), l = (c, u) => {
196
+ const d = e(i.documentElement, c);
197
+ return d ? n(d, u) : null;
198
+ };
199
+ return {
200
+ toc: l("navMap", "navPoint"),
201
+ pageList: l("pageList", "pageTarget"),
202
+ others: s(i.documentElement, "navList").map((c) => ({
203
+ label: L(e(c, "navLabel")),
204
+ list: n(c, "navTarget")
205
+ }))
206
+ };
207
+ }, k = (i) => {
208
+ if (!i) return;
209
+ const t = i.split(":").map((n) => parseFloat(n));
210
+ if (t.length === 3) {
211
+ const [n, l, c] = t;
212
+ return n * 60 * 60 + l * 60 + c;
213
+ }
214
+ if (t.length === 2) {
215
+ const [n, l] = t;
216
+ return n * 60 + l;
217
+ }
218
+ const [e, s] = i.split(/(?=[^\d.])/);
219
+ return parseFloat(e) * (s === "h" ? 3600 : s === "min" ? 60 : s === "ms" ? 1e-3 : 1);
220
+ };
221
+ class nt extends EventTarget {
222
+ #e;
223
+ #s;
224
+ #t;
225
+ #n;
226
+ #i;
227
+ #r;
228
+ #d = 1;
229
+ #f = 1;
230
+ #l;
231
+ constructor(t, e) {
232
+ super(), this.book = t, this.loadXML = e;
233
+ }
234
+ async #g(t) {
235
+ if (this.#s === t) return;
236
+ const e = await this.loadXML(t.href), s = (n) => n ? M(n, t.href) : null, { $: r, $$$: o } = x(e, b.SMIL);
237
+ this.#n = -1, this.#i = -1, this.#e = o(e, "par").reduce((n, l) => {
238
+ const c = s(r(l, "text")?.getAttribute("src")), u = r(l, "audio");
239
+ if (!c || !u) return n;
240
+ const d = s(u.getAttribute("src")), h = k(u.getAttribute("clipBegin")), p = k(u.getAttribute("clipEnd")), g = n.at(-1);
241
+ return g?.src === d ? g.items.push({ text: c, begin: h, end: p }) : n.push({ src: d, items: [{ text: c, begin: h, end: p }] }), n;
242
+ }, []), this.#s = t;
243
+ }
244
+ get #h() {
245
+ return this.#e[this.#n];
246
+ }
247
+ get #a() {
248
+ return this.#h?.items?.[this.#i];
249
+ }
250
+ #o(t) {
251
+ console.error(t), this.dispatchEvent(new CustomEvent("error", { detail: t }));
252
+ }
253
+ #p() {
254
+ this.dispatchEvent(new CustomEvent("highlight", { detail: this.#a }));
255
+ }
256
+ #u() {
257
+ this.dispatchEvent(new CustomEvent("unhighlight", { detail: this.#a }));
258
+ }
259
+ async #c(t, e) {
260
+ this.#m(), this.#n = t, this.#i = e;
261
+ const s = this.#h?.src;
262
+ if (!s || !this.#a) return this.start(this.#t + 1);
263
+ const r = URL.createObjectURL(await this.book.loadBlob(s)), o = new Audio(r);
264
+ this.#r = o, o.volume = this.#d, o.playbackRate = this.#f, o.addEventListener("timeupdate", () => {
265
+ if (o.paused) return;
266
+ const n = o.currentTime, { items: l } = this.#h;
267
+ if (n > this.#a?.end && (this.#u(), this.#i === l.length - 1)) {
268
+ this.#c(this.#n + 1, 0).catch((u) => this.#o(u));
269
+ return;
270
+ }
271
+ const c = this.#i;
272
+ for (; l[this.#i + 1]?.begin <= n; ) this.#i++;
273
+ this.#i !== c && this.#p();
274
+ }), o.addEventListener("error", () => this.#o(new Error(`Failed to load ${s}`))), o.addEventListener("playing", () => this.#p()), o.addEventListener("ended", () => {
275
+ this.#u(), URL.revokeObjectURL(r), this.#r = null, this.#c(t + 1, 0).catch((n) => this.#o(n));
276
+ }), this.#l === "paused" ? (this.#p(), o.currentTime = this.#a.begin ?? 0) : o.addEventListener("canplaythrough", () => {
277
+ o.currentTime = this.#a.begin ?? 0, this.#l = "playing", o.play().catch((n) => this.#o(n));
278
+ }, { once: !0 });
279
+ }
280
+ async start(t, e = () => !0) {
281
+ this.#r?.pause();
282
+ const s = this.book.sections[t], r = s?.id;
283
+ if (!r) return;
284
+ const { mediaOverlay: o } = s;
285
+ if (!o) return this.start(t + 1);
286
+ this.#t = t, await this.#g(o);
287
+ for (let n = 0; n < this.#e.length; n++) {
288
+ const { items: l } = this.#e[n];
289
+ for (let c = 0; c < l.length; c++)
290
+ if (l[c].text.split("#")[0] === r && e(l[c], c, l))
291
+ return this.#c(n, c).catch((u) => this.#o(u));
292
+ }
293
+ }
294
+ pause() {
295
+ this.#l = "paused", this.#r?.pause();
296
+ }
297
+ resume() {
298
+ this.#l = "playing", this.#r?.play().catch((t) => this.#o(t));
299
+ }
300
+ #m() {
301
+ this.#r && (this.#r.pause(), URL.revokeObjectURL(this.#r.src), this.#r = null, this.#u());
302
+ }
303
+ stop() {
304
+ this.#l = "stopped", this.#m();
305
+ }
306
+ prev() {
307
+ this.#i > 0 ? this.#c(this.#n, this.#i - 1) : this.#n > 0 ? this.#c(
308
+ this.#n - 1,
309
+ this.#e[this.#n - 1].items.length - 1
310
+ ) : this.#t > 0 && this.start(this.#t - 1, (t, e, s) => e === s.length - 1);
311
+ }
312
+ next() {
313
+ this.#c(this.#n, this.#i + 1);
314
+ }
315
+ setVolume(t) {
316
+ this.#d = t, this.#r && (this.#r.volume = t);
317
+ }
318
+ setRate(t) {
319
+ this.#f = t, this.#r && (this.#r.playbackRate = t);
320
+ }
321
+ }
322
+ const at = /([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/, ot = (i) => {
323
+ for (const t of i.getElementsByTagNameNS(b.DC, "identifier")) {
324
+ const [e] = L(t).split(":").slice(-1);
325
+ if (at.test(e)) return e;
326
+ }
327
+ return "";
328
+ }, _ = (i) => L(
329
+ i.getElementById(i.documentElement.getAttribute("unique-identifier")) ?? i.getElementsByTagNameNS(b.DC, "identifier")[0]
330
+ ), j = async (i, t, e) => {
331
+ const s = new Uint8Array(await e.slice(0, t).arrayBuffer());
332
+ t = Math.min(t, s.length);
333
+ for (var r = 0; r < t; r++) s[r] = s[r] ^ i[r % i.length];
334
+ return new Blob([s, e.slice(t)], { type: e.type });
335
+ }, ct = async (i) => {
336
+ const t = new TextEncoder().encode(i), e = await globalThis.crypto.subtle.digest("SHA-1", t);
337
+ return new Uint8Array(e);
338
+ }, lt = (i = ct) => ({
339
+ "http://www.idpf.org/2008/embedding": {
340
+ key: (t) => i(_(t).replaceAll(/[\u0020\u0009\u000d\u000a]/g, "")),
341
+ decode: (t, e) => j(t, 1040, e)
342
+ },
343
+ "http://ns.adobe.com/pdf/enc#RC": {
344
+ key: (t) => {
345
+ const e = ot(t).replaceAll("-", "");
346
+ return Uint8Array.from({ length: 16 }, (s, r) => parseInt(e.slice(r * 2, r * 2 + 2), 16));
347
+ },
348
+ decode: (t, e) => j(t, 1024, e)
349
+ }
350
+ });
351
+ class ht {
352
+ #e = /* @__PURE__ */ new Map();
353
+ #s = /* @__PURE__ */ new Map();
354
+ #t;
355
+ constructor(t) {
356
+ this.#t = t;
357
+ }
358
+ async init(t, e) {
359
+ if (!t) return;
360
+ const s = Array.from(
361
+ t.getElementsByTagNameNS(b.ENC, "EncryptedData"),
362
+ (r) => ({
363
+ algorithm: r.getElementsByTagNameNS(b.ENC, "EncryptionMethod")[0]?.getAttribute("Algorithm"),
364
+ uri: r.getElementsByTagNameNS(b.ENC, "CipherReference")[0]?.getAttribute("URI")
365
+ })
366
+ );
367
+ for (const { algorithm: r, uri: o } of s) {
368
+ if (!this.#s.has(r)) {
369
+ const n = this.#t[r];
370
+ if (!n) {
371
+ console.warn("Unknown encryption algorithm");
372
+ continue;
373
+ }
374
+ const l = await n.key(e);
375
+ this.#s.set(r, (c) => n.decode(l, c));
376
+ }
377
+ this.#e.set(o, r);
378
+ }
379
+ }
380
+ getDecoder(t) {
381
+ return this.#s.get(this.#e.get(t)) ?? ((e) => e);
382
+ }
383
+ }
384
+ class pt {
385
+ constructor({ opf: t, resolveHref: e }) {
386
+ this.opf = t;
387
+ const { $: s, $$: r, $$$: o } = x(t, b.OPF), n = s(t.documentElement, "manifest"), l = s(t.documentElement, "spine"), c = r(l, "itemref");
388
+ this.manifest = r(n, "item").map(U("href", "id", "media-type", "properties", "media-overlay")).map((d) => (d.href = e(d.href), d.properties = d.properties?.split(/\s/), d)), this.manifestById = new Map(this.manifest.map((d) => [d.id, d])), this.spine = c.map(U("idref", "id", "linear", "properties")).map((d) => (d.properties = d.properties?.split(/\s/), d)), this.pageProgressionDirection = l.getAttribute("page-progression-direction"), this.navPath = this.getItemByProperty("nav")?.href, this.ncxPath = (this.getItemByID(l.getAttribute("toc")) ?? this.manifest.find((d) => d.mediaType === I.NCX))?.href;
389
+ const u = s(t.documentElement, "guide");
390
+ u && (this.guide = r(u, "reference").map(U("type", "title", "href")).map(({ type: d, title: h, href: p }) => ({
391
+ label: h,
392
+ type: d.split(/\s/),
393
+ href: e(p)
394
+ }))), this.cover = this.getItemByProperty("cover-image") ?? this.getItemByID(o(t, "meta").find(Q("name", "cover"))?.getAttribute("content")) ?? this.getItemByHref(this.guide?.find((d) => d.type.includes("cover"))?.href), this.cfis = z(c);
395
+ }
396
+ getItemByID(t) {
397
+ return this.manifestById.get(t);
398
+ }
399
+ getItemByHref(t) {
400
+ return this.manifest.find((e) => e.href === t);
401
+ }
402
+ getItemByProperty(t) {
403
+ return this.manifest.find((e) => e.properties?.includes(t));
404
+ }
405
+ resolveCFI(t) {
406
+ const e = V(t), s = (e.parent ?? e).shift();
407
+ let r = X(this.opf, s);
408
+ r && r.nodeName !== "idref" && (s.at(-1).id = null, r = X(this.opf, s));
409
+ const o = r?.getAttribute("idref");
410
+ return { index: this.spine.findIndex((c) => c.idref === o), anchor: (c) => W(c, e) };
411
+ }
412
+ }
413
+ class ut {
414
+ #e = /* @__PURE__ */ new Map();
415
+ #s = /* @__PURE__ */ new Map();
416
+ #t = /* @__PURE__ */ new Map();
417
+ eventTarget = new EventTarget();
418
+ constructor({ loadText: t, loadBlob: e, resources: s }) {
419
+ this.loadText = t, this.loadBlob = e, this.manifest = s.manifest, this.assets = s.manifest;
420
+ }
421
+ async createURL(t, e, s, r) {
422
+ if (!e) return "";
423
+ const o = { data: e, type: s };
424
+ Object.defineProperty(o, "name", { value: t });
425
+ const n = new CustomEvent("data", { detail: o });
426
+ this.eventTarget.dispatchEvent(n);
427
+ const l = await n.detail.data, c = await n.detail.type, u = URL.createObjectURL(new Blob([l], { type: c }));
428
+ if (this.#e.set(t, u), this.#t.set(t, 1), r) {
429
+ const d = this.#s.get(r);
430
+ d ? d.push(t) : this.#s.set(r, [t]);
431
+ }
432
+ return u;
433
+ }
434
+ ref(t, e) {
435
+ const s = this.#s.get(e);
436
+ return s?.includes(t) || (this.#t.set(t, this.#t.get(t) + 1), s ? s.push(t) : this.#s.set(e, [t])), this.#e.get(t);
437
+ }
438
+ unref(t) {
439
+ if (!this.#t.has(t)) return;
440
+ const e = this.#t.get(t) - 1;
441
+ if (e < 1) {
442
+ URL.revokeObjectURL(this.#e.get(t)), this.#e.delete(t), this.#t.delete(t);
443
+ const s = this.#s.get(t);
444
+ if (s) for (; s.length; ) this.unref(s.pop());
445
+ this.#s.delete(t);
446
+ } else this.#t.set(t, e);
447
+ }
448
+ // load manifest item, recursively loading all resources as needed
449
+ async loadItem(t, e = []) {
450
+ if (!t) return null;
451
+ const { href: s, mediaType: r } = t, o = I.JS.test(t.mediaType), n = { type: r, isScript: o, allow: !0 }, l = new CustomEvent("load", { detail: n });
452
+ if (this.eventTarget.dispatchEvent(l), !await l.detail.allow) return null;
453
+ const u = e.at(-1);
454
+ if (this.#e.has(s)) return this.ref(s, u);
455
+ if ((o || [I.XHTML, I.HTML, I.CSS, I.SVG].includes(r)) && e.every((p) => p !== s)) return this.loadReplaced(t, e);
456
+ const h = Promise.resolve().then(() => this.loadBlob(s));
457
+ return this.createURL(s, h, r, u);
458
+ }
459
+ async loadHref(t, e, s = []) {
460
+ if (q(t)) return t;
461
+ const r = M(t, e), o = this.manifest.find((n) => n.href === r);
462
+ return o ? this.loadItem(o, s.concat(e)) : t;
463
+ }
464
+ async loadReplaced(t, e = []) {
465
+ const { href: s, mediaType: r } = t, o = e.at(-1);
466
+ let n = "";
467
+ try {
468
+ n = await this.loadText(s);
469
+ } catch (c) {
470
+ return this.createURL(s, Promise.reject(c), r, o);
471
+ }
472
+ if (!n) return null;
473
+ if ([I.XHTML, I.HTML, I.SVG].includes(r)) {
474
+ let c = new DOMParser().parseFromString(n, r);
475
+ if (r === I.XHTML && (c.querySelector("parsererror") || !c.documentElement?.namespaceURI) && (console.warn(c.querySelector("parsererror")?.innerText ?? "Invalid XHTML"), t.mediaType = I.HTML, c = new DOMParser().parseFromString(n, t.mediaType)), [I.XHTML, I.SVG].includes(t.mediaType)) {
476
+ let h = c.firstChild;
477
+ for (; h instanceof ProcessingInstruction; ) {
478
+ if (h.data) {
479
+ const p = await R(
480
+ h.data,
481
+ /(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,
482
+ (g, m, y, E) => this.loadHref(y, s, e).then((S) => `${m}${S}${E}`)
483
+ );
484
+ h.replaceWith(c.createProcessingInstruction(
485
+ h.target,
486
+ p
487
+ ));
488
+ }
489
+ h = h.nextSibling;
490
+ }
491
+ }
492
+ const u = async (h, p) => h.setAttribute(
493
+ p,
494
+ await this.loadHref(h.getAttribute(p), s, e)
495
+ );
496
+ for (const h of c.querySelectorAll("link[href]")) await u(h, "href");
497
+ for (const h of c.querySelectorAll("[src]")) await u(h, "src");
498
+ for (const h of c.querySelectorAll("[poster]")) await u(h, "poster");
499
+ for (const h of c.querySelectorAll("object[data]")) await u(h, "data");
500
+ for (const h of c.querySelectorAll("[*|href]:not([href])"))
501
+ h.setAttributeNS(b.XLINK, "href", await this.loadHref(
502
+ h.getAttributeNS(b.XLINK, "href"),
503
+ s,
504
+ e
505
+ ));
506
+ for (const h of c.querySelectorAll("[srcset]"))
507
+ h.setAttribute("srcset", await R(
508
+ h.getAttribute("srcset"),
509
+ /(\s*)(.+?)\s*((?:\s[\d.]+[wx])+\s*(?:,|$)|,\s+|$)/g,
510
+ (p, g, m, y) => this.loadHref(m, s, e).then((E) => `${g}${E}${y}`)
511
+ ));
512
+ for (const h of c.querySelectorAll("style"))
513
+ h.textContent && (h.textContent = await this.replaceCSS(h.textContent, s, e));
514
+ for (const h of c.querySelectorAll("[style]"))
515
+ h.setAttribute(
516
+ "style",
517
+ await this.replaceCSS(h.getAttribute("style"), s, e)
518
+ );
519
+ const d = new XMLSerializer().serializeToString(c);
520
+ return this.createURL(s, d, t.mediaType, o);
521
+ }
522
+ const l = r === I.CSS ? await this.replaceCSS(n, s, e) : await this.replaceString(n, s, e);
523
+ return this.createURL(s, l, r, o);
524
+ }
525
+ async replaceCSS(t, e, s = []) {
526
+ const r = await R(
527
+ t,
528
+ /url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,
529
+ (o, n) => this.loadHref(n, e, s).then((l) => `url("${l}")`)
530
+ );
531
+ return R(
532
+ r,
533
+ /@import\s*["']([^"'\n]*?)["']/gi,
534
+ (o, n) => this.loadHref(n, e, s).then((l) => `@import "${l}"`)
535
+ );
536
+ }
537
+ // find & replace all possible relative paths for all assets without parsing
538
+ replaceString(t, e, s = []) {
539
+ const r = /* @__PURE__ */ new Map(), o = this.assets.map((l) => {
540
+ if (l.href === e) return;
541
+ const c = Y(Z(e), l.href), u = encodeURI(c), d = "/" + l.href, h = encodeURI(d), p = /* @__PURE__ */ new Set([c, u, d, h]);
542
+ for (const g of p) r.set(g, l);
543
+ return Array.from(p);
544
+ }).flat().filter((l) => l);
545
+ if (!o.length) return t;
546
+ const n = new RegExp(o.map(tt).join("|"), "g");
547
+ return R(t, n, async (l) => this.loadItem(
548
+ r.get(l.replace(/^\//, "")),
549
+ s.concat(e)
550
+ ));
551
+ }
552
+ unloadItem(t) {
553
+ this.unref(t?.href);
554
+ }
555
+ destroy() {
556
+ for (const t of this.#e.values()) URL.revokeObjectURL(t);
557
+ }
558
+ }
559
+ const dt = (i, t) => i.getElementById(t) ?? i.querySelector(`[name="${CSS.escape(t)}"]`), ft = (i) => {
560
+ for (const t of i) {
561
+ if (t === "page-spread-left" || t === "rendition:page-spread-left")
562
+ return "left";
563
+ if (t === "page-spread-right" || t === "rendition:page-spread-right")
564
+ return "right";
565
+ if (t === "rendition:page-spread-center") return "center";
566
+ }
567
+ }, mt = (i) => i ? {
568
+ fixedLayout: L(i.querySelector('option[name="fixed-layout"]')),
569
+ openToSpread: L(i.querySelector('option[name="open-to-spread"]'))
570
+ } : null;
571
+ class yt {
572
+ parser = new DOMParser();
573
+ #e;
574
+ #s;
575
+ constructor({ loadText: t, loadBlob: e, getSize: s, sha1: r }) {
576
+ this.loadText = t, this.loadBlob = e, this.getSize = s, this.#s = new ht(lt(r));
577
+ }
578
+ async #t(t) {
579
+ const e = await this.loadText(t);
580
+ if (!e) return null;
581
+ const s = this.parser.parseFromString(e, I.XML);
582
+ if (s.querySelector("parsererror"))
583
+ throw new Error(`XML parsing error: ${t}
584
+ ${s.querySelector("parsererror").innerText}`);
585
+ return s;
586
+ }
587
+ async init() {
588
+ const t = await this.#t("META-INF/container.xml");
589
+ if (!t) throw new Error("Failed to load container file");
590
+ const e = Array.from(
591
+ t.getElementsByTagNameNS(b.CONTAINER, "rootfile"),
592
+ U("full-path", "media-type")
593
+ ).filter((p) => p.mediaType === "application/oebps-package+xml");
594
+ if (!e.length) throw new Error("No package document defined in container");
595
+ const s = e[0].fullPath, r = await this.#t(s);
596
+ if (!r) throw new Error("Failed to load package document");
597
+ const o = await this.#t("META-INF/encryption.xml");
598
+ await this.#s.init(o, r), this.resources = new pt({
599
+ opf: r,
600
+ resolveHref: (p) => M(p, s)
601
+ }), this.#e = new ut({
602
+ loadText: this.loadText,
603
+ loadBlob: (p) => Promise.resolve(this.loadBlob(p)).then(this.#s.getDecoder(p)),
604
+ resources: this.resources
605
+ }), this.transformTarget = this.#e.eventTarget, this.sections = this.resources.spine.map((p, g) => {
606
+ const { idref: m, linear: y, properties: E = [] } = p, S = this.resources.getItemByID(m);
607
+ return S ? {
608
+ id: S.href,
609
+ load: () => this.#e.loadItem(S),
610
+ unload: () => this.#e.unloadItem(S),
611
+ createDocument: () => this.loadDocument(S),
612
+ size: this.getSize(S.href),
613
+ cfi: this.resources.cfis[g],
614
+ linear: y,
615
+ pageSpread: ft(E),
616
+ resolveHref: ($) => M($, S.href),
617
+ mediaOverlay: S.mediaOverlay ? this.resources.getItemByID(S.mediaOverlay) : null
618
+ } : (console.warn(`Could not find item with ID "${m}" in manifest`), null);
619
+ }).filter((p) => p);
620
+ const { navPath: n, ncxPath: l } = this.resources;
621
+ if (n) try {
622
+ const p = (m) => M(m, n), g = rt(await this.#t(n), p);
623
+ this.toc = g.toc, this.pageList = g.pageList, this.landmarks = g.landmarks;
624
+ } catch (p) {
625
+ console.warn(p);
626
+ }
627
+ if (!this.toc && l) try {
628
+ const p = (m) => M(m, l), g = it(await this.#t(l), p);
629
+ this.toc = g.toc, this.pageList = g.pageList;
630
+ } catch (p) {
631
+ console.warn(p);
632
+ }
633
+ this.landmarks ??= this.resources.guide;
634
+ const { metadata: c, rendition: u, media: d } = st(r);
635
+ this.metadata = c, this.rendition = u, this.media = d, this.dir = this.resources.pageProgressionDirection;
636
+ const h = mt(
637
+ await this.#t("META-INF/com.apple.ibooks.display-options.xml") ?? await this.#t("META-INF/com.kobobooks.display-options.xml")
638
+ );
639
+ return h && (h.fixedLayout === "true" && (this.rendition.layout ??= "pre-paginated"), h.openToSpread === "false" && (this.sections.find((p) => p.linear !== "no").pageSpread ??= this.dir === "rtl" ? "left" : "right")), this;
640
+ }
641
+ async loadDocument(t) {
642
+ const e = await this.loadText(t.href);
643
+ return this.parser.parseFromString(e, t.mediaType);
644
+ }
645
+ getMediaOverlay() {
646
+ return new nt(this, this.#t.bind(this));
647
+ }
648
+ resolveCFI(t) {
649
+ return this.resources.resolveCFI(t);
650
+ }
651
+ resolveHref(t) {
652
+ const [e, s] = t.split("#"), r = this.resources.getItemByHref(decodeURI(e));
653
+ return r ? { index: this.resources.spine.findIndex(({ idref: l }) => l === r.id), anchor: s ? (l) => dt(l, s) : () => 0 } : null;
654
+ }
655
+ splitTOCHref(t) {
656
+ return t?.split("#") ?? [];
657
+ }
658
+ getTOCFragment(t, e) {
659
+ return t.getElementById(e) ?? t.querySelector(`[name="${CSS.escape(e)}"]`);
660
+ }
661
+ isExternal(t) {
662
+ return q(t);
663
+ }
664
+ async getCover() {
665
+ const t = this.resources?.cover;
666
+ return t?.href ? new Blob([await this.loadBlob(t.href)], { type: t.mediaType }) : null;
667
+ }
668
+ async getCalibreBookmarks() {
669
+ const t = await this.loadText("META-INF/calibre_bookmarks.txt"), e = "encoding=json+base64:";
670
+ if (t?.startsWith(e)) {
671
+ const s = atob(t.slice(e.length));
672
+ return JSON.parse(s);
673
+ }
674
+ }
675
+ destroy() {
676
+ this.#e?.destroy();
677
+ }
678
+ }
679
+ export {
680
+ yt as EPUB
681
+ };