@storyteller-platform/epub 0.7.0 → 0.8.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.cjs DELETED
@@ -1,2749 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var index_exports = {};
30
- __export(index_exports, {
31
- Epub: () => Epub,
32
- EpubFactory: () => EpubFactory,
33
- EpubReadOnlyError: () => EpubReadOnlyError,
34
- EpubVersionError: () => EpubVersionError,
35
- MemoryAdapter: () => import_memory.MemoryAdapter,
36
- TmpFsAdapter: () => import_tmpfs2.TmpFsAdapter
37
- });
38
- module.exports = __toCommonJS(index_exports);
39
- var import_promises = require("node:fs/promises");
40
- var import_async_mutex = require("async-mutex");
41
- var import_fast_xml_parser = require("fast-xml-parser");
42
- var import_mem = __toESM(require("mem"), 1);
43
- var import_mime_types = require("mime-types");
44
- var import_nanoid = require("nanoid");
45
- var import_path = require("@storyteller-platform/path");
46
- var import_tmpfs = require("./adapters/tmpfs.cjs");
47
- var Upgrade = __toESM(require("./upgrade.ts"), 1);
48
- var import_memory = require("./adapters/memory.cjs");
49
- var import_tmpfs2 = require("./adapters/tmpfs.cjs");
50
- class EpubVersionError extends Error {
51
- }
52
- class EpubReadOnlyError extends Error {
53
- }
54
- class Epub {
55
- /**
56
- * Prefer the static factories ({@link Epub.using}, {@link Epub.from},
57
- * {@link Epub.create}, {@link Epub.upgrade}) over calling this constructor
58
- * directly. It's public so {@link EpubFactory} can construct instances; nothing
59
- * else should need to.
60
- */
61
- constructor(adapterClass, adapter, inputPath, readonlyOverride = false) {
62
- this.adapterClass = adapterClass;
63
- this.adapter = adapter;
64
- this.inputPath = inputPath;
65
- this.readonlyOverride = readonlyOverride;
66
- this.storage = adapterClass.kind;
67
- this.readXhtmlItemContents = (0, import_mem.default)(
68
- this.readXhtmlItemContents.bind(this),
69
- // This isn't unnecessary, the generic here just isn't handling the
70
- // overloaded method type correctly
71
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
72
- { cacheKey: ([id, as]) => `${id}:${as ?? "xhtml"}` }
73
- );
74
- }
75
- static xmlParser = new import_fast_xml_parser.XMLParser({
76
- allowBooleanAttributes: true,
77
- preserveOrder: true,
78
- ignoreAttributes: false,
79
- parseTagValue: false
80
- });
81
- static xhtmlParser = (() => {
82
- const parser = new import_fast_xml_parser.XMLParser({
83
- allowBooleanAttributes: true,
84
- alwaysCreateTextNode: true,
85
- preserveOrder: true,
86
- ignoreAttributes: false,
87
- htmlEntities: true,
88
- trimValues: false,
89
- stopNodes: ["*.pre", "*.script"],
90
- parseTagValue: false,
91
- updateTag(_tagName, _jPath, attrs) {
92
- if (attrs && "@_/" in attrs) {
93
- delete attrs["@_/"];
94
- }
95
- return true;
96
- }
97
- });
98
- parser.addEntity("nbsp", "\xA0");
99
- parser.addEntity("#160", "\xA0");
100
- return parser;
101
- })();
102
- static xmlBuilder = new import_fast_xml_parser.XMLBuilder({
103
- preserveOrder: true,
104
- format: true,
105
- ignoreAttributes: false,
106
- suppressEmptyNode: true
107
- });
108
- static xhtmlBuilder = new import_fast_xml_parser.XMLBuilder({
109
- preserveOrder: true,
110
- ignoreAttributes: false,
111
- stopNodes: ["*.pre", "*.script"],
112
- suppressEmptyNode: true
113
- });
114
- /**
115
- * Format a duration, provided as a number of seconds, as
116
- * a SMIL clock value, to be used for Media Overlays.
117
- *
118
- * @link https://www.w3.org/TR/epub-33/#sec-duration
119
- */
120
- static formatSmilDuration(duration) {
121
- const hours = Math.floor(duration / 3600);
122
- const minutes = Math.floor(duration / 60 - hours * 60);
123
- const secondsAndMillis = duration - minutes * 60 - hours * 3600;
124
- const [seconds, millis] = secondsAndMillis.toFixed(2).split(".");
125
- return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.padStart(2, "0")}.${millis ?? "0"}`;
126
- }
127
- /**
128
- * Given an XML structure representing a complete XHTML document,
129
- * add a `link` element to the `head` of the document.
130
- *
131
- * This method modifies the provided XML structure.
132
- */
133
- static addLinkToXhtmlHead(xml, link) {
134
- const html = Epub.findXmlChildByName("html", xml);
135
- if (!html) throw new Error("Invalid XHTML document: no html element");
136
- const head = Epub.findXmlChildByName("head", html.html);
137
- if (!head) throw new Error("Invalid XHTML document: no head element");
138
- head["head"].push({
139
- link: [],
140
- ":@": {
141
- "@_rel": link.rel,
142
- "@_href": link.href,
143
- "@_type": link.type
144
- }
145
- });
146
- }
147
- /**
148
- * Given an XML structure representing a complete XHTML document,
149
- * return the sub-structure representing the children of the
150
- * document's body element.
151
- */
152
- static getXhtmlBody(xml) {
153
- const html = Epub.findXmlChildByName("html", xml);
154
- if (!html) throw new Error("Invalid XHTML document: no html element");
155
- const body = Epub.findXmlChildByName("body", html["html"]);
156
- if (!body) throw new Error("Invalid XHTML document: No body element");
157
- return body["body"];
158
- }
159
- static createXmlElement(name, properties, children = []) {
160
- return {
161
- ":@": Object.fromEntries(
162
- Object.entries(properties).map(([prop, value]) => [`@_${prop}`, value])
163
- ),
164
- [name]: children
165
- };
166
- }
167
- static createXmlTextNode(text) {
168
- return { ["#text"]: text };
169
- }
170
- /**
171
- * Given an XML structure representing a complete XHTML document,
172
- * return a string representing the concatenation of all text nodes
173
- * in the document.
174
- */
175
- static getXhtmlTextContent(xml) {
176
- let text = "";
177
- for (const child of xml) {
178
- if (Epub.isXmlTextNode(child)) {
179
- text += child["#text"];
180
- continue;
181
- }
182
- const children = Epub.getXmlChildren(child);
183
- text += Epub.getXhtmlTextContent(children);
184
- }
185
- return text;
186
- }
187
- /**
188
- * Given an XMLElement, return its attributes.
189
- */
190
- static getXmlAttributes(element) {
191
- return Object.fromEntries(
192
- Object.entries(element[":@"] ?? {}).map(([key, value]) => [
193
- key.slice(2),
194
- value
195
- ])
196
- );
197
- }
198
- /**
199
- * Given an XMLElement, return its tag name.
200
- */
201
- static getXmlElementName(element) {
202
- const keys = Object.keys(element);
203
- const elementName = keys.find((key) => key !== ":@" && key !== "#text");
204
- if (!elementName)
205
- throw new Error(
206
- `Invalid XML Element: missing tag name
207
- ${JSON.stringify(element, null, 2)}`
208
- );
209
- return elementName;
210
- }
211
- /**
212
- * Given an XMLElement, return a list of its children
213
- */
214
- static getXmlChildren(element) {
215
- const elementName = Epub.getXmlElementName(element);
216
- return element[elementName];
217
- }
218
- static replaceXmlChildren(element, children) {
219
- const elementName = Epub.getXmlElementName(element);
220
- element[elementName] = children;
221
- }
222
- /**
223
- * Given an XML structure, find the first child matching
224
- * the provided name and optional filter.
225
- */
226
- static findXmlChildByName(name, xml, filter) {
227
- const element = xml.find(
228
- (e) => name in e && (filter ? filter(e) : true)
229
- );
230
- return element;
231
- }
232
- /**
233
- * Given an XML structure, find the first descendant matching
234
- * the provided name and optional filter.
235
- *
236
- * Will perform a breadth first search for the element, returning
237
- * the highest element in the tree matching the name and filter.
238
- */
239
- static findXmlDescendantByName(name, xml, filter) {
240
- const found = Epub.findXmlChildByName(name, xml, filter);
241
- if (found) return found;
242
- for (const node of xml) {
243
- if (Epub.isXmlTextNode(node)) continue;
244
- const children = Epub.getXmlChildren(node);
245
- const found2 = this.findXmlDescendantByName(name, children, filter);
246
- if (found2) return found2;
247
- }
248
- return void 0;
249
- }
250
- /**
251
- * Given an XMLNode, determine whether it represents
252
- * a text node or an XML element.
253
- */
254
- static isXmlTextNode(node) {
255
- return "#text" in node;
256
- }
257
- rootfile = null;
258
- manifest = null;
259
- spine = null;
260
- packageMutex = new import_async_mutex.Mutex();
261
- /**
262
- * Storage backend kind in use for this instance
263
- *
264
- * Public so callers can declare type-level requirements via {@link InMemoryEpubReader}
265
- * Orthogonal to the read-only / writable axis (controlled by `readonlyOverride`
266
- * and the adapter's capability bag)
267
- */
268
- storage;
269
- /**
270
- * Runtime guard for mutation methods
271
- */
272
- assertWritable() {
273
- if (!this.adapterClass.capabilities.writable || this.readonlyOverride) {
274
- throw new EpubReadOnlyError(
275
- "cannot mutate a read-only Epub. open via Epub.using(TmpFsAdapter).from(path) (without { readonly: true }) to modify."
276
- );
277
- }
278
- }
279
- /**
280
- * Construct a new EPUB on a writable backend, optionally seeded
281
- * with the provided metadata. Equivalent to
282
- * `Epub.using(TmpFsAdapter).create(...)`.
283
- *
284
- * @param dublinCore Core metadata terms
285
- * @param additionalMetadata An array of additional metadata entries
286
- */
287
- static async create(path, dublinCore, additionalMetadata = []) {
288
- return Epub.using(import_tmpfs.TmpFsAdapter).create(path, dublinCore, additionalMetadata);
289
- }
290
- /**
291
- * Specify the storage backend to use for the EPUB
292
- *
293
- * The returned factory exposes `from`, `create`, and `upgrade`,
294
- * which route through the supplied adapter.
295
- *
296
- * @example
297
- * ```ts
298
- * using epub = await Epub.using(TmpFsAdapter).from(path)
299
- * using reader = await Epub.using(MemoryAdapter).from(buffer, { cache: false })
300
- * ```
301
- */
302
- static using(adapterClass) {
303
- return new EpubFactory(adapterClass);
304
- }
305
- static async from(pathOrData, options = {}) {
306
- return Epub.using(import_tmpfs.TmpFsAdapter).from(pathOrData, options);
307
- }
308
- static async assertEpub3(epub) {
309
- const version = await epub.getVersion();
310
- if (!version.startsWith("3.")) {
311
- epub.discardAndClose();
312
- throw new EpubVersionError(
313
- "This is not a valid EPUB 3 publication. This library only supports EPUB 3, not EPUB 2. Use Epub.upgrade(path) to convert."
314
- );
315
- }
316
- }
317
- async copy(path) {
318
- if (!this.adapter.duplicate) {
319
- throw new Error(
320
- `cannot copy an Epub backed by ${this.adapterClass.kind}: adapter does not implement duplicate()`
321
- );
322
- }
323
- const newAdapter = await this.adapter.duplicate();
324
- return new Epub(this.adapterClass, newAdapter, path);
325
- }
326
- async removeEntry(href) {
327
- this.assertWritable();
328
- if (!this.adapter.remove) {
329
- throw new EpubReadOnlyError(
330
- `adapter ${this.adapterClass.kind} does not support entry removal`
331
- );
332
- }
333
- const rootfile = await this.getRootfile();
334
- const filename = this.resolveInternalHref(rootfile, href);
335
- await this.adapter.remove(filename);
336
- }
337
- async getFileData(path, encoding) {
338
- if (encoding) {
339
- return this.adapter.read(path, encoding);
340
- }
341
- return this.adapter.read(path);
342
- }
343
- /**
344
- * Length of the underlying archive entry for a manifest item, in bytes
345
- * Necessary to compute the readium page count which is for COMPRESSED content
346
- * @see {@link https://github.com/readium/architecture/issues/123}
347
- */
348
- async getItemArchiveLength(id) {
349
- const rootfile = await this.getRootfile();
350
- const manifest = await this.getManifest();
351
- const manifestItem = manifest[id];
352
- if (!manifestItem)
353
- throw new Error(`Could not find item with id "${id}" in manifest`);
354
- const path = this.resolveInternalHref(rootfile, manifestItem.href);
355
- return this.adapter.archiveLength(path);
356
- }
357
- async getRootfile() {
358
- var _a;
359
- if (this.rootfile !== null) return this.rootfile;
360
- const containerString = await this.getFileData(
361
- (0, import_path.join)(this.adapter.rootPath, "META-INF", "container.xml"),
362
- "utf-8"
363
- );
364
- if (!containerString)
365
- throw new Error("Failed to parse EPUB: Missing META-INF/container.xml");
366
- const containerDocument = Epub.xmlParser.parse(containerString);
367
- const container = Epub.findXmlChildByName("container", containerDocument);
368
- if (!container)
369
- throw new Error(
370
- "Failed to parse EPUB container.xml: Found no container element"
371
- );
372
- const rootfiles = Epub.findXmlChildByName(
373
- "rootfiles",
374
- Epub.getXmlChildren(container)
375
- );
376
- if (!rootfiles)
377
- throw new Error(
378
- "Failed to parse EPUB container.xml: Found no rootfiles element"
379
- );
380
- const rootfile = Epub.findXmlChildByName(
381
- "rootfile",
382
- Epub.getXmlChildren(rootfiles),
383
- (node) => {
384
- var _a2;
385
- return !Epub.isXmlTextNode(node) && ((_a2 = node[":@"]) == null ? void 0 : _a2["@_media-type"]) === "application/oebps-package+xml";
386
- }
387
- );
388
- const fullPath = (_a = rootfile == null ? void 0 : rootfile[":@"]) == null ? void 0 : _a["@_full-path"];
389
- if (!fullPath)
390
- throw new Error(
391
- "Failed to parse EPUB container.xml: Found no rootfile element"
392
- );
393
- this.rootfile = (0, import_path.resolve)(this.adapter.rootPath, fullPath);
394
- return this.rootfile;
395
- }
396
- async getPackageDocument() {
397
- const rootfile = await this.getRootfile();
398
- const packageDocumentString = await this.getFileData(rootfile, "utf-8");
399
- if (!packageDocumentString)
400
- throw new Error(
401
- `Failed to parse EPUB: could not find package document at ${rootfile}`
402
- );
403
- const packageDocument = Epub.xmlParser.parse(
404
- packageDocumentString
405
- );
406
- return packageDocument;
407
- }
408
- async getPackageElement() {
409
- const packageDocument = await this.getPackageDocument();
410
- const packageElement = Epub.findXmlChildByName("package", packageDocument);
411
- if (!packageElement) {
412
- throw new Error(
413
- "Failed to parse EPUB: Found no package element in package document"
414
- );
415
- }
416
- return packageElement;
417
- }
418
- /**
419
- * Safely modify the package document, without race conditions.
420
- *
421
- * Since the reading the package document is an async process,
422
- * multiple simultaneously dispatched function calls that all
423
- * attempt to modify it can clobber each other's changes. This
424
- * method uses a mutex to ensure that each update runs exclusively.
425
- *
426
- * @param producer The function to update the package document. If
427
- * it returns a new package document, that will be persisted, otherwise
428
- * it will be assumed that the package document was modified in place.
429
- */
430
- async withPackage(producer) {
431
- this.assertWritable();
432
- await this.packageMutex.runExclusive(async () => {
433
- const packageDocument = await this.getPackageDocument();
434
- const packageElement = Epub.findXmlChildByName("package", packageDocument);
435
- if (!packageElement) {
436
- throw new Error(
437
- "Failed to parse EPUB: Found no package element in package document"
438
- );
439
- }
440
- const produced = await producer(packageElement);
441
- const updatedPackageDocument = await Epub.xmlBuilder.build(
442
- produced ?? packageDocument
443
- );
444
- const rootfile = await this.getRootfile();
445
- await this.writeEntryContents(rootfile, updatedPackageDocument, "utf-8");
446
- });
447
- }
448
- /**
449
- * Retrieve the manifest for the Epub.
450
- *
451
- * This is represented as a map from each manifest items'
452
- * id to the rest of its properties.
453
- *
454
- * @link https://www.w3.org/TR/epub-33/#sec-pkg-manifest
455
- */
456
- async getManifest() {
457
- if (this.manifest !== null) return this.manifest;
458
- const packageElement = await this.getPackageElement();
459
- const manifest = Epub.findXmlChildByName(
460
- "manifest",
461
- Epub.getXmlChildren(packageElement)
462
- );
463
- if (!manifest)
464
- throw new Error(
465
- "Failed to parse EPUB: Found no manifest element in package document"
466
- );
467
- this.manifest = Epub.getXmlChildren(manifest).reduce((acc, item) => {
468
- var _a, _b;
469
- if (Epub.isXmlTextNode(item)) return acc;
470
- if (!((_a = item[":@"]) == null ? void 0 : _a["@_id"]) || !item[":@"]["@_href"]) {
471
- return acc;
472
- }
473
- return {
474
- ...acc,
475
- [item[":@"]["@_id"]]: {
476
- id: item[":@"]["@_id"],
477
- href: item[":@"]["@_href"],
478
- mediaType: item[":@"]["@_media-type"],
479
- mediaOverlay: item[":@"]["@_media-overlay"],
480
- fallback: item[":@"]["@_fallback"],
481
- properties: (_b = item[":@"]["@_properties"]) == null ? void 0 : _b.split(" ")
482
- }
483
- };
484
- }, {});
485
- return this.manifest;
486
- }
487
- /**
488
- * Returns the first index in the metadata element's children array
489
- * that matches the provided predicate.
490
- *
491
- * Note: This may technically be different than the index in the
492
- * getMetadata() array, as it includes non-metadata nodes, like
493
- * text nodes. These are technically not allowed, but may exist,
494
- * nonetheless. As consumers only ever see the getMetadata()
495
- * array, this method is only meant to be used internally.
496
- */
497
- findMetadataIndex(packageElement, predicate) {
498
- const metadataElement = Epub.findXmlChildByName(
499
- "metadata",
500
- Epub.getXmlChildren(packageElement)
501
- );
502
- if (!metadataElement)
503
- throw new Error(
504
- "Failed to parse EPUB: Found no metadata element in package document"
505
- );
506
- return metadataElement.metadata.findIndex((node) => {
507
- const item = Epub.parseMetadataItem(node);
508
- if (!item) return false;
509
- return predicate(item);
510
- });
511
- }
512
- /**
513
- * Returns the item in the metadata element's children array
514
- * that matches the provided predicate.
515
- */
516
- async findMetadataItem(predicate) {
517
- const [first] = await this.findAllMetadataItems(predicate);
518
- return first ?? null;
519
- }
520
- /**
521
- * Returns the item in the metadata element's children array
522
- * that matches the provided predicate.
523
- */
524
- async findAllMetadataItems(predicate) {
525
- const packageElement = await this.getPackageElement();
526
- const metadataElement = Epub.findXmlChildByName(
527
- "metadata",
528
- Epub.getXmlChildren(packageElement)
529
- );
530
- if (!metadataElement)
531
- throw new Error(
532
- "Failed to parse EPUB: Found no metadata element in package document"
533
- );
534
- const elements = metadataElement.metadata.filter((node) => {
535
- const item = Epub.parseMetadataItem(node);
536
- if (!item) return false;
537
- return predicate(item);
538
- });
539
- return elements.map((element) => Epub.parseMetadataItem(element)).filter((item) => !!item);
540
- }
541
- static parseMetadataItem(node) {
542
- if (Epub.isXmlTextNode(node)) return null;
543
- const elementName = Epub.getXmlElementName(node);
544
- const textNode = Epub.getXmlChildren(node)[0];
545
- const value = !textNode || !Epub.isXmlTextNode(textNode) ? void 0 : textNode["#text"].replaceAll(/\s+/g, " ");
546
- const attributes = node[":@"] ?? {};
547
- const { id, ...properties } = Object.fromEntries(
548
- Object.entries(attributes).map(([attrName, value2]) => [
549
- attrName.slice(2),
550
- value2
551
- ])
552
- );
553
- return {
554
- id,
555
- type: elementName,
556
- properties,
557
- value
558
- };
559
- }
560
- /**
561
- * Retrieve the metadata entries for the Epub.
562
- *
563
- * This is represented as an array of metadata entries,
564
- * in the order that they're presented in the Epub package document.
565
- *
566
- * For more useful semantic representations of metadata, use
567
- * specific methods such as `getTitle()` and `getAuthors()`.
568
- *
569
- * @link https://www.w3.org/TR/epub-33/#sec-pkg-metadata
570
- */
571
- async getMetadata() {
572
- const packageElement = await this.getPackageElement();
573
- const metadataElement = Epub.findXmlChildByName(
574
- "metadata",
575
- Epub.getXmlChildren(packageElement)
576
- );
577
- if (!metadataElement)
578
- throw new Error(
579
- "Failed to parse EPUB: Found no metadata element in package document"
580
- );
581
- const metadata = metadataElement.metadata.map((node) => Epub.parseMetadataItem(node)).filter((node) => !!node);
582
- return metadata;
583
- }
584
- /**
585
- * Retrieve the first identifier from the dc:identifier element
586
- * in the EPUB metadata.
587
- *
588
- * If there is no dc:identifier element, returns null.
589
- *
590
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
591
- *
592
- * @deprecated Use {@link getUniqueIdentifier} instead to get the unique identifier,
593
- * or {@link getIdentifiers} to get all identifiers.
594
- */
595
- async getIdentifier() {
596
- const metadata = await this.getMetadata();
597
- const entry = metadata.find(({ type }) => type === "dc:identifier");
598
- return (entry == null ? void 0 : entry.value) ?? null;
599
- }
600
- /**
601
- * Set the dc:identifier metadata element with the provided string.
602
- *
603
- * Updates the existing dc:identifier element if one exists.
604
- * Otherwise creates a new element
605
- *
606
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
607
- *
608
- * @deprecated Use {@link setUniqueIdentifier} instead.
609
- */
610
- async setIdentifier(identifier) {
611
- await this.replaceMetadata(({ type }) => type === "dc:identifier", {
612
- type: "dc:identifier",
613
- properties: {},
614
- value: identifier
615
- });
616
- }
617
- /**
618
- * Retrieve the identifier with the unique identifier id
619
- * in the EPUB metadata.
620
- *
621
- * If there is no unique identifier id, returns the first dc:identifier element.
622
- *
623
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
624
- */
625
- async getUniqueIdentifier() {
626
- const metadata = await this.getMetadata();
627
- const uniqueId = await this.getUniqueIdentifierId();
628
- if (!uniqueId) {
629
- return null;
630
- }
631
- const entry = metadata.find(
632
- ({ type, id }) => type === "dc:identifier" && id === uniqueId
633
- );
634
- return (entry == null ? void 0 : entry.value) ?? null;
635
- }
636
- /**
637
- * Set the unique identifier id for the EPUB.
638
- *
639
- * Updates the existing dc:identifier element referenced by the unique identifier id if one exists.
640
- * Otherwise creates a new element with the provided identifier, and sets the unique identifier id to the new element's id.
641
- *
642
- * Note: you likely shouldn't change the unique identifier id unless you are producing a new EPUB.
643
- *
644
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
645
- */
646
- async setUniqueIdentifier(identifier) {
647
- await this.withPackage(async (packageElement) => {
648
- const metadata = Epub.findXmlChildByName(
649
- "metadata",
650
- Epub.getXmlChildren(packageElement)
651
- );
652
- if (!metadata) {
653
- throw new Error(
654
- "Failed to parse EPUB: found no metadata element in package document"
655
- );
656
- }
657
- let uniqueId = await this.getUniqueIdentifierId();
658
- if (!uniqueId) {
659
- const newUniqueId = (0, import_nanoid.nanoid)();
660
- packageElement[":@"] = {
661
- ...packageElement[":@"],
662
- "@_unique-identifier": newUniqueId
663
- };
664
- uniqueId = newUniqueId;
665
- }
666
- const children = Epub.getXmlChildren(metadata);
667
- const entry = Epub.findXmlChildByName(
668
- "dc:identifier",
669
- children,
670
- (node) => {
671
- var _a;
672
- return ((_a = node[":@"]) == null ? void 0 : _a["@_id"]) === uniqueId;
673
- }
674
- );
675
- if (entry) {
676
- children.splice(
677
- children.indexOf(entry),
678
- 1,
679
- Epub.createXmlElement("dc:identifier", { id: uniqueId }, [
680
- Epub.createXmlTextNode(identifier)
681
- ])
682
- );
683
- return;
684
- }
685
- children.push(
686
- Epub.createXmlElement("dc:identifier", { id: uniqueId }, [
687
- Epub.createXmlTextNode(identifier)
688
- ])
689
- );
690
- });
691
- }
692
- /**
693
- * Retrieve the id of the publication's unique identifier, as declared by the
694
- * package element's `unique-identifier` attribute.
695
- *
696
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
697
- */
698
- async getUniqueIdentifierId() {
699
- var _a;
700
- const packageElement = await this.getPackageElement();
701
- return ((_a = packageElement[":@"]) == null ? void 0 : _a["@_unique-identifier"]) ?? null;
702
- }
703
- /**
704
- * Collect `dc:identifier` or `dc:source` entries, attaching the value and
705
- * scheme of any refining `identifier-type` meta (spec D.3.8) and a legacy
706
- * `opf:scheme` attribute. Values are not interpreted.
707
- *
708
- * `onRefinement` is invoked for every other meta refining a collected entry,
709
- * so callers can surface element-specific refinements (e.g. `source-of` on a
710
- * `dc:source`).
711
- */
712
- static collectDcEntries(metadata, type, onRefinement) {
713
- const entries = metadata.filter((entry) => entry.type === type && entry.value !== void 0).map((entry) => ({
714
- // filtered above, so value is defined
715
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
716
- value: entry.value,
717
- ...entry.id && { id: entry.id },
718
- ...entry.properties["opf:scheme"] && {
719
- scheme: entry.properties["opf:scheme"]
720
- }
721
- }));
722
- for (const meta of metadata) {
723
- if (meta.type !== "meta" || meta.value === void 0) continue;
724
- const property = meta.properties["property"];
725
- const refines = meta.properties["refines"];
726
- if (!property || !refines) continue;
727
- const target = entries.find((t) => t.id === refines.slice(1));
728
- if (!target) continue;
729
- if (property === "identifier-type") {
730
- target.identifierType = meta.value;
731
- if (meta.properties["scheme"]) target.scheme = meta.properties["scheme"];
732
- } else {
733
- onRefinement == null ? void 0 : onRefinement(target, property, meta.value);
734
- }
735
- }
736
- return entries;
737
- }
738
- /**
739
- * Retrieve every `dc:identifier` entry, returned as found.
740
- *
741
- * Values are not interpreted. Any refining `identifier-type` meta (spec
742
- * D.3.8) or legacy `opf:scheme` attribute is surfaced on the entry, but no
743
- * parsing of the value itself is attempted. To read `dc:source` entries, use
744
- * {@link getSources}.
745
- *
746
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
747
- */
748
- async getIdentifiers() {
749
- const metadata = await this.getMetadata();
750
- return Epub.collectDcEntries(metadata, "dc:identifier");
751
- }
752
- /**
753
- * Retrieve every `dc:source` entry, returned as found.
754
- *
755
- * Like {@link getIdentifiers}, values are not interpreted. In addition to a
756
- * refining `identifier-type`, a refining `source-of` meta (spec D.3.11) is
757
- * surfaced as `sourceOf`.
758
- *
759
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcsource
760
- */
761
- async getSources() {
762
- const metadata = await this.getMetadata();
763
- return Epub.collectDcEntries(
764
- metadata,
765
- "dc:source",
766
- (source, property) => {
767
- if (property === "source-of") {
768
- source.isPageBreakSource = true;
769
- }
770
- }
771
- );
772
- }
773
- /**
774
- * Retrieve the `pageBreakSource` property (EPUB 3.4, spec D.2.9), the
775
- * publication-level source for the source of its page break markers.
776
- *
777
- * This property replaces the refining `source-of="pagination"` meta (spec
778
- * D.3.11), see {@link EpubSource.sourceOf}. If no `pageBreakSource` property is found,
779
- * we fall back to finding a `dc:source` with a `source-of="pagination"` refinement.
780
- *
781
- * @link https://www.w3.org/TR/epub/#pageBreakSource
782
- */
783
- async getPageBreakSource() {
784
- const entry = await this.findMetadataItem(
785
- (item) => item.type === "meta" && item.properties["property"] === "pageBreakSource" && !!item.value
786
- );
787
- if (entry) {
788
- return {
789
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
790
- value: entry.value,
791
- id: entry.id,
792
- identifierType: void 0,
793
- scheme: void 0,
794
- isPageBreakSource: true
795
- };
796
- }
797
- const sources = await this.getSources();
798
- const source = sources.find((source2) => source2.isPageBreakSource);
799
- if (source) {
800
- return source;
801
- }
802
- return null;
803
- }
804
- /**
805
- * Set the `pageBreakSource` property (EPUB 3.4, spec D.2.9), or remove it when
806
- * passed null. Replaces an existing `pageBreakSource` meta if present.
807
- *
808
- * Pass `none` to indicate the pagination is unique to this publication.
809
- *
810
- * @link https://www.w3.org/TR/epub/#pageBreakSource
811
- */
812
- async setPageBreakSource(value) {
813
- if (value === null) {
814
- await this.removeMetadata(
815
- (item) => item.properties["property"] === "pageBreakSource"
816
- );
817
- return;
818
- }
819
- await this.replaceMetadata(
820
- (item) => item.properties["property"] === "pageBreakSource",
821
- { type: "meta", properties: { property: "pageBreakSource" }, value }
822
- );
823
- }
824
- /**
825
- * Replace the publication's `dc:identifier` entries.
826
- *
827
- * This replaces ALL existing `dc:identifier` elements except the publication's
828
- * unique identifier (the one referenced by the package element's
829
- * `unique-identifier` attribute), which is always preserved and must not be
830
- * included in the provided list. If included anyway, it is ignored. See
831
- * {@link setUniqueIdentifier} to change it.
832
- *
833
- * Identifiers are placed in the order they are provided.
834
- *
835
- * `dc:source` entries are not touched, use {@link setSources} for those.
836
- *
837
- * When an entry has an `identifierType`, it is written in the refining form
838
- * (a `meta` with `property="identifier-type"`, carrying the `scheme`
839
- * attribute when provided). An entry with only a `scheme` is written using
840
- * the legacy `opf:scheme` attribute.
841
- *
842
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcidentifier
843
- */
844
- async setIdentifiers(identifiers) {
845
- const uniqueId = await this.getUniqueIdentifierId();
846
- await this.withPackage((packageElement) => {
847
- var _a;
848
- const metadata = Epub.findXmlChildByName(
849
- "metadata",
850
- Epub.getXmlChildren(packageElement)
851
- );
852
- if (!metadata)
853
- throw new Error(
854
- "Failed to parse EPUB: found no metadata element in package document"
855
- );
856
- const children = Epub.getXmlChildren(metadata);
857
- const removedIds = /* @__PURE__ */ new Set();
858
- for (let i = children.length - 1; i >= 0; i--) {
859
- const node = children[i];
860
- if (Epub.isXmlTextNode(node) || Epub.getXmlElementName(node) !== "dc:identifier") {
861
- continue;
862
- }
863
- const id = (_a = node[":@"]) == null ? void 0 : _a["@_id"];
864
- if (id && id === uniqueId) {
865
- continue;
866
- }
867
- if (id) {
868
- removedIds.add(id);
869
- }
870
- children.splice(i, 1);
871
- }
872
- Epub.removeRefiningMetas(children, removedIds, ["identifier-type"]);
873
- for (const identifier of identifiers) {
874
- if (identifier.id && identifier.id === uniqueId) continue;
875
- const id = identifier.id ?? (identifier.identifierType !== void 0 ? (0, import_nanoid.nanoid)() : void 0);
876
- children.push(
877
- Epub.createXmlElement(
878
- "dc:identifier",
879
- {
880
- ...id && { id },
881
- ...identifier.scheme && identifier.identifierType === void 0 && {
882
- "opf:scheme": identifier.scheme
883
- }
884
- },
885
- [Epub.createXmlTextNode(identifier.value)]
886
- )
887
- );
888
- if (identifier.identifierType !== void 0 && id) {
889
- children.push(
890
- Epub.createXmlElement(
891
- "meta",
892
- {
893
- refines: `#${id}`,
894
- property: "identifier-type",
895
- ...identifier.scheme && { scheme: identifier.scheme }
896
- },
897
- [Epub.createXmlTextNode(identifier.identifierType)]
898
- )
899
- );
900
- }
901
- }
902
- });
903
- }
904
- /**
905
- * Remove `meta` refinements pointing at any of the given ids,
906
- * restricted to the given `property` values as a cleanup step
907
- * Mutates `children` in place.
908
- */
909
- static removeRefiningMetas(children, ids, properties) {
910
- var _a, _b, _c;
911
- for (let i = children.length - 1; i >= 0; i--) {
912
- const node = children[i];
913
- if (Epub.isXmlTextNode(node) || Epub.getXmlElementName(node) !== "meta") {
914
- continue;
915
- }
916
- const property = (_a = node[":@"]) == null ? void 0 : _a["@_property"];
917
- if (!property || !properties.includes(property)) continue;
918
- const refines = (_c = (_b = node[":@"]) == null ? void 0 : _b["@_refines"]) == null ? void 0 : _c.slice(1);
919
- if (refines && ids.has(refines)) {
920
- children.splice(i, 1);
921
- }
922
- }
923
- }
924
- /**
925
- * Replace the publication's `dc:source` entries.
926
- *
927
- * This replaces ALL existing `dc:source` elements (and their refining
928
- * `identifier-type` / `source-of` metas). `dc:identifier` entries are not
929
- * touched; use {@link setIdentifiers} for those. Pass an empty array to
930
- * remove all sources.
931
- *
932
- * When an entry has an `identifierType`, it is written in the refining form.
933
- * A `sourceOf` value is written as a refining `source-of` meta (spec D.3.11).
934
- * An entry with only a `scheme` uses the legacy `opf:scheme` attribute.
935
- *
936
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcsource
937
- */
938
- async setSources(sources) {
939
- await this.withPackage((packageElement) => {
940
- var _a;
941
- const metadata = Epub.findXmlChildByName(
942
- "metadata",
943
- Epub.getXmlChildren(packageElement)
944
- );
945
- if (!metadata)
946
- throw new Error(
947
- "Failed to parse EPUB: found no metadata element in package document"
948
- );
949
- const children = Epub.getXmlChildren(metadata);
950
- const removedIds = /* @__PURE__ */ new Set();
951
- for (let i = children.length - 1; i >= 0; i--) {
952
- const node = children[i];
953
- if (Epub.isXmlTextNode(node) || Epub.getXmlElementName(node) !== "dc:source") {
954
- continue;
955
- }
956
- const id = (_a = node[":@"]) == null ? void 0 : _a["@_id"];
957
- if (id) {
958
- removedIds.add(id);
959
- }
960
- children.splice(i, 1);
961
- }
962
- Epub.removeRefiningMetas(children, removedIds, [
963
- "identifier-type",
964
- "source-of"
965
- ]);
966
- for (const source of sources) {
967
- const needsId = source.identifierType !== void 0 || source.isPageBreakSource;
968
- const id = source.id ?? (needsId ? (0, import_nanoid.nanoid)() : void 0);
969
- children.push(
970
- Epub.createXmlElement(
971
- "dc:source",
972
- {
973
- ...id && { id },
974
- ...source.scheme && source.identifierType === void 0 && {
975
- "opf:scheme": source.scheme
976
- }
977
- },
978
- [Epub.createXmlTextNode(source.value)]
979
- )
980
- );
981
- if (source.identifierType !== void 0 && id) {
982
- children.push(
983
- Epub.createXmlElement(
984
- "meta",
985
- {
986
- refines: `#${id}`,
987
- property: "identifier-type",
988
- ...source.scheme && { scheme: source.scheme }
989
- },
990
- [Epub.createXmlTextNode(source.identifierType)]
991
- )
992
- );
993
- }
994
- if (source.isPageBreakSource && id) {
995
- children.push(
996
- Epub.createXmlElement(
997
- "meta",
998
- { refines: `#${id}`, property: "source-of" },
999
- [Epub.createXmlTextNode("pagination")]
1000
- )
1001
- );
1002
- }
1003
- }
1004
- });
1005
- }
1006
- /**
1007
- * Even "EPUB 3" publications sometimes still only use the
1008
- * EPUB 2 specification for identifying the cover image.
1009
- * This is a private method that is used as a fallback if
1010
- * we fail to find the cover image according to the EPUB 3
1011
- * spec.
1012
- */
1013
- async getEpub2CoverImage() {
1014
- var _a;
1015
- const packageElement = await this.getPackageElement();
1016
- const metadataElement = Epub.findXmlChildByName(
1017
- "metadata",
1018
- Epub.getXmlChildren(packageElement)
1019
- );
1020
- if (!metadataElement)
1021
- throw new Error(
1022
- "Failed to parse EPUB: Found no metadata element in package document"
1023
- );
1024
- const coverImageElement = Epub.getXmlChildren(metadataElement).find(
1025
- (node) => {
1026
- var _a2;
1027
- return !Epub.isXmlTextNode(node) && ((_a2 = node[":@"]) == null ? void 0 : _a2["@_name"]) === "cover";
1028
- }
1029
- );
1030
- const manifestItemId = (_a = coverImageElement == null ? void 0 : coverImageElement[":@"]) == null ? void 0 : _a["@_content"];
1031
- if (!manifestItemId) return null;
1032
- const manifest = await this.getManifest();
1033
- return Object.values(manifest).find((item) => item.id === manifestItemId) ?? null;
1034
- }
1035
- /**
1036
- * Retrieve the cover image manifest item.
1037
- *
1038
- * This does not return the actual image data. To
1039
- * retrieve the image data, pass this item's id to
1040
- * epub.readItemContents, or use epub.getCoverImage()
1041
- * instead.
1042
- *
1043
- * @link https://www.w3.org/TR/epub-33/#sec-cover-image
1044
- */
1045
- async getCoverImageItem() {
1046
- const manifest = await this.getManifest();
1047
- const coverImage = Object.values(manifest).find(
1048
- (item) => {
1049
- var _a;
1050
- return (_a = item.properties) == null ? void 0 : _a.includes("cover-image");
1051
- }
1052
- );
1053
- if (coverImage) return coverImage;
1054
- return this.getEpub2CoverImage();
1055
- }
1056
- /**
1057
- * Retrieve the cover image data as a byte array.
1058
- *
1059
- * This does not include, for example, the cover image's
1060
- * filename or mime type. To retrieve the image manifest
1061
- * item, use epub.getCoverImageItem().
1062
- *
1063
- * @link https://www.w3.org/TR/epub-33/#sec-cover-image
1064
- */
1065
- async getCoverImage() {
1066
- const coverImageItem = await this.getCoverImageItem();
1067
- if (!coverImageItem) return coverImageItem;
1068
- return this.readItemContents(coverImageItem.id);
1069
- }
1070
- /**
1071
- * Set the cover image for the EPUB.
1072
- *
1073
- * Adds a manifest item with the `cover-image` property, per
1074
- * the EPUB 3 spec, and then writes the provided image data to
1075
- * the provided href within the publication.
1076
- */
1077
- async setCoverImage(href, data) {
1078
- const coverImageItem = await this.getCoverImageItem();
1079
- if (coverImageItem) {
1080
- await this.removeManifestItem(coverImageItem.id);
1081
- }
1082
- const mediaType = (0, import_mime_types.lookup)(href);
1083
- if (!mediaType)
1084
- throw new Error(`Invalid file extension for cover image: ${href}`);
1085
- await this.addManifestItem(
1086
- { id: "cover-image", href, mediaType, properties: ["cover-image"] },
1087
- data
1088
- );
1089
- }
1090
- /**
1091
- * Retrieve the publication date from the dc:date element
1092
- * in the EPUB metadata as a Date object.
1093
- *
1094
- * If there is no dc:date element, returns null.
1095
- *
1096
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcdate
1097
- */
1098
- async getPublicationDate() {
1099
- const metadata = await this.getMetadata();
1100
- const entry = metadata.find(({ type }) => type === "dc:date");
1101
- if (!(entry == null ? void 0 : entry.value)) return null;
1102
- return new Date(entry.value);
1103
- }
1104
- /**
1105
- * Set the dc:date metadata element with the provided date.
1106
- *
1107
- * Updates the existing dc:date element if one exists.
1108
- * Otherwise creates a new element
1109
- *
1110
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcdate
1111
- */
1112
- async setPublicationDate(date) {
1113
- await this.replaceMetadata(({ type }) => type === "dc:date", {
1114
- type: "dc:date",
1115
- properties: {},
1116
- value: date.toISOString()
1117
- });
1118
- }
1119
- /**
1120
- * Retrieve the modified date from the dcterms:modified metadata
1121
- * in the EPUB metadata as a Date object.
1122
- *
1123
- * If there is no meta element with dcterms:modified, returns null.
1124
- *
1125
- * @link https://www.w3.org/TR/epub-33/#sec-metadata-last-modified
1126
- */
1127
- async getModifiedDate() {
1128
- const metadata = await this.getMetadata();
1129
- const entry = metadata.find(
1130
- ({ properties }) => properties["property"] === "dcterms:modified"
1131
- );
1132
- if (!(entry == null ? void 0 : entry.value)) return null;
1133
- return new Date(entry.value);
1134
- }
1135
- /**
1136
- * Retrieve the layout from the rendition:layout meta element
1137
- * in the EPUB metadata.
1138
- *
1139
- * If there is no meta element, returns 'reflowable'.
1140
- *
1141
- * @link https://www.w3.org/TR/epub-33/#layout
1142
- */
1143
- async getLayout() {
1144
- const metadata = await this.getMetadata();
1145
- const entry = metadata.find(
1146
- ({ properties }) => properties["property"] === "rendition:layout"
1147
- );
1148
- if ((entry == null ? void 0 : entry.value) !== "reflowable" && (entry == null ? void 0 : entry.value) !== "pre-paginated") {
1149
- return "reflowable";
1150
- }
1151
- return entry.value;
1152
- }
1153
- /**
1154
- * Retrieve the base direction from the package element.
1155
- *
1156
- * If there is no `dir` attribute on the package element,
1157
- * returns 'auto'.
1158
- *
1159
- * @link https://www.w3.org/TR/epub-33/#attrdef-dir
1160
- */
1161
- async getBaseDirection() {
1162
- var _a;
1163
- const packageEl = await this.getPackageElement();
1164
- const dir = (_a = packageEl[":@"]) == null ? void 0 : _a["@_dir"];
1165
- if (dir !== "ltr" && dir !== "rtl" && dir !== "auto") {
1166
- return "auto";
1167
- }
1168
- return dir;
1169
- }
1170
- /**
1171
- * Set the dc:type metadata element.
1172
- *
1173
- * Updates the existing dc:type element if one exists.
1174
- * Otherwise creates a new element.
1175
- *
1176
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dctype
1177
- */
1178
- async setType(type) {
1179
- await this.replaceMetadata(({ type: type2 }) => type2 === "dc:type", {
1180
- type: "dc:type",
1181
- properties: {},
1182
- value: type
1183
- });
1184
- }
1185
- /**
1186
- * Retrieve the publication type from the dc:type element
1187
- * in the EPUB metadata.
1188
- *
1189
- * If there is no dc:type element, returns null.
1190
- *
1191
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dctype
1192
- */
1193
- async getType() {
1194
- const metadata = await this.getMetadata();
1195
- return metadata.find(({ type }) => type === "dc:type") ?? null;
1196
- }
1197
- /**
1198
- * Add a subject to the EPUB metadata.
1199
- *
1200
- * @param subject May be a string representing just a schema-less
1201
- * subject name, or a DcSubject object
1202
- *
1203
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcsubject
1204
- */
1205
- async addSubject(subject) {
1206
- const subjectEntry = typeof subject === "string" ? {
1207
- value: subject
1208
- } : subject;
1209
- const subjectId = (0, import_nanoid.nanoid)();
1210
- await this.addMetadata({
1211
- id: subjectId,
1212
- type: "dc:subject",
1213
- properties: {},
1214
- value: subjectEntry.value
1215
- });
1216
- if ("authority" in subjectEntry) {
1217
- await this.addMetadata({
1218
- type: "meta",
1219
- properties: { refines: `#${subjectId}`, property: "authority" },
1220
- value: subjectEntry.authority
1221
- });
1222
- await this.addMetadata({
1223
- type: "meta",
1224
- properties: { refines: `#${subjectId}`, property: "term" },
1225
- value: subjectEntry.term
1226
- });
1227
- }
1228
- }
1229
- /**
1230
- * Remove a subject from the EPUB metadata.
1231
- *
1232
- * Removes the subject at the provided index. This index
1233
- * refers to the array returned by `epub.getSubjects()`.
1234
- *
1235
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccreator
1236
- */
1237
- async removeSubject(index) {
1238
- await this.withPackage((packageElement) => {
1239
- const metadata = Epub.findXmlChildByName(
1240
- "metadata",
1241
- Epub.getXmlChildren(packageElement)
1242
- );
1243
- if (!metadata)
1244
- throw new Error(
1245
- "Failed to parse EPUB: found no metadata element in package document"
1246
- );
1247
- let subjectCount = null;
1248
- let metadataIndex = null;
1249
- for (const meta of Epub.getXmlChildren(metadata)) {
1250
- if (subjectCount === index) break;
1251
- metadataIndex = metadataIndex === null ? 0 : metadataIndex + 1;
1252
- if (Epub.isXmlTextNode(meta)) continue;
1253
- if (Epub.getXmlElementName(meta) !== "dc:subject") continue;
1254
- subjectCount = subjectCount === null ? 0 : subjectCount + 1;
1255
- }
1256
- if (subjectCount === null || metadataIndex === null) return;
1257
- Epub.getXmlChildren(metadata).splice(metadataIndex, 1);
1258
- });
1259
- }
1260
- /**
1261
- * Retrieve the list of subjects for this EPUB.
1262
- *
1263
- * Subjects without associated authority and term metadata
1264
- * will be returned as strings. Otherwise, they will
1265
- * be represented as DcSubject objects, with a value,
1266
- * authority, and term.
1267
- *
1268
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dcsubject
1269
- */
1270
- async getSubjects() {
1271
- const metadata = await this.getMetadata();
1272
- const subjectEntries = metadata.filter(({ type }) => type === "dc:subject");
1273
- const subjects = subjectEntries.map(({ value }) => value).filter((value) => !!value);
1274
- metadata.forEach((entry) => {
1275
- if (entry.type !== "meta" || entry.properties["property"] !== "term" && entry.properties["property"] !== "authority") {
1276
- return;
1277
- }
1278
- const subjectIdref = entry.properties["refines"];
1279
- if (!subjectIdref) return;
1280
- const subjectId = subjectIdref.slice(1);
1281
- const index = subjectEntries.findIndex((entry2) => entry2.id === subjectId);
1282
- if (index === -1) return;
1283
- const subject = typeof subjects[index] === "string" ? { value: subjects[index], authority: void 0, term: void 0 } : (
1284
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1285
- subjects[index]
1286
- );
1287
- subject[entry.properties["property"]] = entry.value;
1288
- subjects.splice(index, 1, subject);
1289
- });
1290
- return subjects;
1291
- }
1292
- /**
1293
- * Retrieve the Epub's language as specified in its
1294
- * package document metadata.
1295
- *
1296
- * If no language metadata is specified, returns null.
1297
- * Returns the language as an Intl.Locale instance.
1298
- *
1299
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dclanguage
1300
- */
1301
- async getLanguage() {
1302
- const metadata = await this.getMetadata();
1303
- const languageEntries = metadata.filter(
1304
- (entry) => entry.type === "dc:language"
1305
- );
1306
- const primaryLanguage = languageEntries[0];
1307
- if (!primaryLanguage) return null;
1308
- const locale = primaryLanguage.value;
1309
- if (!locale || locale.toLowerCase() === "und") return null;
1310
- try {
1311
- return new Intl.Locale(locale);
1312
- } catch {
1313
- return null;
1314
- }
1315
- }
1316
- /**
1317
- * Update the Epub's language metadata entry.
1318
- *
1319
- * Updates the existing dc:language element if one exists.
1320
- * Otherwise creates a new element
1321
- *
1322
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dclanguage
1323
- */
1324
- async setLanguage(locale) {
1325
- await this.replaceMetadata(({ type }) => type === "dc:language", {
1326
- type: "dc:language",
1327
- properties: {},
1328
- value: locale.toString()
1329
- });
1330
- }
1331
- /**
1332
- * Retrieve the title of the Epub.
1333
- *
1334
- * @param main Optional - whether to return only the first title segment
1335
- * if multiple are found. Otherwise, will follow the spec to combine title
1336
- * segments
1337
- *
1338
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dctitle
1339
- */
1340
- async getTitle(expanded = false) {
1341
- var _a;
1342
- const entries = await this.getTitles();
1343
- if (!expanded) {
1344
- const mainEntry = entries.find((entry) => entry.type === "main");
1345
- if (mainEntry) return mainEntry.title;
1346
- const shortEntry = entries.find((entry) => entry.type === "short");
1347
- if (shortEntry) return shortEntry.title;
1348
- return ((_a = entries[0]) == null ? void 0 : _a.title) ?? null;
1349
- }
1350
- const expandedEntry = entries.find((entry) => entry.type === "expanded");
1351
- if (expandedEntry) return expandedEntry.title;
1352
- return entries.map((entry) => entry.title).join(", ");
1353
- }
1354
- /**
1355
- * Retrieve the subtitle of the Epub, if it exists.
1356
- *
1357
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dctitle
1358
- */
1359
- async getSubtitle() {
1360
- const entries = await this.getTitles();
1361
- const subtitleEntry = entries.find((entry) => entry.type === "subtitle");
1362
- return (subtitleEntry == null ? void 0 : subtitleEntry.title) ?? null;
1363
- }
1364
- /**
1365
- * Retrieve all title entries of the Epub.
1366
- *
1367
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dctitle
1368
- */
1369
- async getTitles() {
1370
- const metadata = await this.getMetadata();
1371
- const titleEntries = metadata.filter((entry) => entry.type === "dc:title");
1372
- const titleRefinements = metadata.filter(
1373
- (entry) => entry.type === "meta" && entry.properties["refines"] && (entry.properties["property"] === "title-type" || entry.properties["property"] === "display-seq")
1374
- );
1375
- const sortedTitleParts = titleEntries.filter(
1376
- (titleEntry) => titleEntry.id && titleRefinements.some(
1377
- (entry) => {
1378
- var _a;
1379
- return entry.value && ((_a = entry.properties["refines"]) == null ? void 0 : _a.slice(1)) === titleEntry.id && entry.properties["property"] === "display-seq" && !Number.isNaN(parseInt(entry.value, 10));
1380
- }
1381
- )
1382
- ).sort((a, b) => {
1383
- const refinementA = titleRefinements.find(
1384
- (entry) => entry.properties["property"] === "display-seq" && entry.properties["refines"].slice(1) === a.id
1385
- );
1386
- const refinementB = titleRefinements.find(
1387
- (entry) => entry.properties["property"] === "display-seq" && entry.properties["refines"].slice(1) === b.id
1388
- );
1389
- const sortA = parseInt(refinementA.value, 10);
1390
- const sortB = parseInt(refinementB.value, 10);
1391
- return sortA - sortB;
1392
- });
1393
- return (sortedTitleParts.length === 0 ? titleEntries : sortedTitleParts).map((entry) => {
1394
- const titleType = titleRefinements.find(
1395
- (refinement) => {
1396
- var _a;
1397
- return ((_a = refinement.properties["refines"]) == null ? void 0 : _a.slice(1)) === entry.id && refinement.properties["property"] === "title-type";
1398
- }
1399
- );
1400
- return {
1401
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1402
- title: entry.value,
1403
- type: (titleType == null ? void 0 : titleType.value) ?? null
1404
- };
1405
- });
1406
- }
1407
- /**
1408
- * Update the Epub's description metadata entry.
1409
- *
1410
- * Updates the existing dc:description element if one exists.
1411
- * Otherwise creates a new element. Any non-ASCII symbols,
1412
- * `&`, `<`, `>`, `"`, `'`, and `\``` will be encoded as HTML entities.
1413
- */
1414
- async setDescription(description) {
1415
- await this.replaceMetadata(({ type }) => type === "dc:description", {
1416
- type: "dc:description",
1417
- value: description,
1418
- properties: {}
1419
- });
1420
- }
1421
- /**
1422
- * Retrieve the Epub's description as specified in its
1423
- * package document metadata.
1424
- *
1425
- * If no description metadata is specified, returns null.
1426
- * Returns the description as a string. Descriptions may
1427
- * include HTML markup.
1428
- */
1429
- async getDescription() {
1430
- const metadata = await this.getMetadata();
1431
- const descriptionEntry = metadata.find(
1432
- (entry) => entry.type === "dc:description"
1433
- );
1434
- if (!(descriptionEntry == null ? void 0 : descriptionEntry.value)) return null;
1435
- return descriptionEntry.value;
1436
- }
1437
- /**
1438
- * Return the set of custom vocabulary prefixes set on this publication's
1439
- * root package element.
1440
- *
1441
- * Returns a map from prefix to URI
1442
- *
1443
- * @link https://www.w3.org/TR/epub-33/#sec-prefix-attr
1444
- */
1445
- async getPackageVocabularyPrefixes() {
1446
- var _a;
1447
- const packageElement = await this.getPackageElement();
1448
- const prefixValue = (_a = packageElement[":@"]) == null ? void 0 : _a["@_prefix"];
1449
- if (!prefixValue) return {};
1450
- const matches = prefixValue.matchAll(/(?:([a-z]+): +(\S+)\s*)/gs);
1451
- return Array.from(matches).reduce(
1452
- (acc, match) => match[1] && match[2] ? { ...acc, [match[1]]: match[2] } : acc,
1453
- {}
1454
- );
1455
- }
1456
- /**
1457
- * Set a custom vocabulary prefix on the root package element.
1458
- *
1459
- * @link https://www.w3.org/TR/epub-33/#sec-prefix-attr
1460
- */
1461
- async setPackageVocabularyPrefix(prefix, uri) {
1462
- await this.withPackage(async (packageElement) => {
1463
- const prefixes = await this.getPackageVocabularyPrefixes();
1464
- prefixes[prefix] = uri;
1465
- packageElement[":@"] ??= {};
1466
- packageElement[":@"]["@_prefix"] = Object.entries(prefixes).map(([p, u]) => `${p}: ${u}`).join("\n ");
1467
- });
1468
- }
1469
- /**
1470
- * Set the title of the Epub.
1471
- *
1472
- * This will replace all existing dc:title elements with
1473
- * this title. It will be given title-type "main".
1474
- *
1475
- * To set specific titles and their types, use epub.setTitles().
1476
- *
1477
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dctitle
1478
- */
1479
- // TODO: This should allow users to optionally specify an array,
1480
- // rather than a single string, to support expanded titles.
1481
- async setTitle(title) {
1482
- await this.withPackage((packageElement) => {
1483
- const metadata = Epub.findXmlChildByName(
1484
- "metadata",
1485
- Epub.getXmlChildren(packageElement)
1486
- );
1487
- if (!metadata)
1488
- throw new Error(
1489
- "Failed to parse EPUB: found no metadata element in package document"
1490
- );
1491
- const titleElement = Epub.findXmlChildByName(
1492
- "dc:title",
1493
- metadata.metadata
1494
- );
1495
- if (!titleElement) {
1496
- Epub.getXmlChildren(metadata).push(
1497
- Epub.createXmlElement("dc:title", {}, [
1498
- Epub.createXmlTextNode(title)
1499
- ])
1500
- );
1501
- } else {
1502
- titleElement["dc:title"] = [Epub.createXmlTextNode(title)];
1503
- }
1504
- });
1505
- }
1506
- async setTitles(entries) {
1507
- await this.withPackage((packageElement) => {
1508
- var _a, _b;
1509
- const metadata = Epub.findXmlChildByName(
1510
- "metadata",
1511
- Epub.getXmlChildren(packageElement)
1512
- );
1513
- if (!metadata) {
1514
- throw new Error(
1515
- "Failed to parse EPUB: found no metadata element in package document"
1516
- );
1517
- }
1518
- const metadataEntries = Epub.getXmlChildren(metadata);
1519
- for (let i = metadataEntries.length - 1; i >= 0; i--) {
1520
- const meta = metadataEntries[i];
1521
- if (Epub.isXmlTextNode(meta)) continue;
1522
- if (Epub.getXmlElementName(meta) === "dc:title" || ((_a = meta[":@"]) == null ? void 0 : _a["@_property"]) === "title-type" || ((_b = meta[":@"]) == null ? void 0 : _b["@_property"]) === "display-seq") {
1523
- metadataEntries.splice(i, 1);
1524
- }
1525
- }
1526
- for (let i = 0; i < entries.length; i++) {
1527
- const entry = entries[i];
1528
- const id = (0, import_nanoid.nanoid)();
1529
- metadataEntries.push(
1530
- Epub.createXmlElement("dc:title", { id }, [
1531
- Epub.createXmlTextNode(entry.title)
1532
- ])
1533
- );
1534
- if (entry.type) {
1535
- metadataEntries.push(
1536
- Epub.createXmlElement(
1537
- "meta",
1538
- { refines: `#${id}`, property: "title-type" },
1539
- [Epub.createXmlTextNode(entry.type)]
1540
- )
1541
- );
1542
- }
1543
- metadataEntries.push(
1544
- Epub.createXmlElement(
1545
- "meta",
1546
- { refines: `#${id}`, property: "display-seq" },
1547
- [Epub.createXmlTextNode((i + 1).toString())]
1548
- )
1549
- );
1550
- }
1551
- });
1552
- }
1553
- /**
1554
- * Retrieve the list of collections.
1555
- */
1556
- async getCollections() {
1557
- var _a, _b;
1558
- const metadata = await this.getMetadata();
1559
- const collections = [];
1560
- for (const entry of metadata) {
1561
- if (entry.properties["property"] === "belongs-to-collection" && entry.value) {
1562
- const type = (_a = metadata.find(
1563
- (e) => e.properties["refines"] === `#${entry.id ?? ""}` && e.properties["property"] === "collection-type"
1564
- )) == null ? void 0 : _a.value;
1565
- const position = (_b = metadata.find(
1566
- (e) => e.properties["refines"] === `#${entry.id ?? ""}` && e.properties["property"] === "group-position"
1567
- )) == null ? void 0 : _b.value;
1568
- collections.push({
1569
- name: entry.value,
1570
- ...type && { type },
1571
- ...position && { position }
1572
- });
1573
- }
1574
- }
1575
- return collections;
1576
- }
1577
- /**
1578
- * Add a collection to the EPUB metadata.
1579
- *
1580
- * If index is provided, the collection will be placed at
1581
- * that index in the list of collections. Otherwise, it
1582
- * will be added to the end of the list.
1583
- */
1584
- async addCollection(collection, index) {
1585
- const collectionId = (0, import_nanoid.nanoid)();
1586
- await this.withPackage((packageElement) => {
1587
- var _a;
1588
- const metadata = Epub.findXmlChildByName(
1589
- "metadata",
1590
- Epub.getXmlChildren(packageElement)
1591
- );
1592
- if (!metadata)
1593
- throw new Error(
1594
- "Failed to parse EPUB: found no metadata element in package document"
1595
- );
1596
- let collectionCount = 0;
1597
- let metadataIndex = 0;
1598
- for (const meta of Epub.getXmlChildren(metadata)) {
1599
- if (collectionCount === index) break;
1600
- metadataIndex++;
1601
- if (Epub.isXmlTextNode(meta)) continue;
1602
- if (Epub.getXmlElementName(meta) !== "meta") continue;
1603
- if (((_a = meta[":@"]) == null ? void 0 : _a["@_property"]) !== "belongs-to-collection") continue;
1604
- collectionCount++;
1605
- }
1606
- Epub.getXmlChildren(metadata).splice(
1607
- metadataIndex,
1608
- 0,
1609
- Epub.createXmlElement(
1610
- "meta",
1611
- { id: collectionId, property: "belongs-to-collection" },
1612
- [Epub.createXmlTextNode(collection.name)]
1613
- )
1614
- );
1615
- });
1616
- if (collection.position) {
1617
- await this.addMetadata({
1618
- type: "meta",
1619
- properties: { refines: `#${collectionId}`, property: "group-position" },
1620
- value: collection.position
1621
- });
1622
- }
1623
- if (collection.type) {
1624
- await this.addMetadata({
1625
- type: "meta",
1626
- properties: {
1627
- refines: `#${collectionId}`,
1628
- property: "collection-type"
1629
- },
1630
- value: collection.type
1631
- });
1632
- }
1633
- }
1634
- /**
1635
- * Remove a collection from the EPUB metadata.
1636
- *
1637
- * Removes the collection at the provided index. This index
1638
- * refers to the array returned by `epub.getCollections()`.
1639
- */
1640
- async removeCollection(index) {
1641
- await this.withPackage((packageElement) => {
1642
- var _a, _b;
1643
- const metadata = Epub.findXmlChildByName(
1644
- "metadata",
1645
- Epub.getXmlChildren(packageElement)
1646
- );
1647
- if (!metadata)
1648
- throw new Error(
1649
- "Failed to parse EPUB: found no metadata element in package document"
1650
- );
1651
- let collectionCount = null;
1652
- let metadataIndex = null;
1653
- for (const meta of Epub.getXmlChildren(metadata)) {
1654
- if (collectionCount === index) break;
1655
- metadataIndex = metadataIndex === null ? 0 : metadataIndex + 1;
1656
- if (Epub.isXmlTextNode(meta)) continue;
1657
- if (Epub.getXmlElementName(meta) !== "meta") continue;
1658
- if (((_a = meta[":@"]) == null ? void 0 : _a["@_property"]) !== "belongs-to-collection") continue;
1659
- collectionCount = collectionCount === null ? 0 : collectionCount + 1;
1660
- }
1661
- if (collectionCount === null || metadataIndex === null) return;
1662
- const [removed] = Epub.getXmlChildren(metadata).splice(metadataIndex, 1);
1663
- if (removed && !Epub.isXmlTextNode(removed) && ((_b = removed[":@"]) == null ? void 0 : _b["@_id"])) {
1664
- const id = removed[":@"]["@_id"];
1665
- const newChildren = Epub.getXmlChildren(metadata).filter((node) => {
1666
- var _a2;
1667
- if (Epub.isXmlTextNode(node)) return true;
1668
- if (Epub.getXmlElementName(node) !== "meta") return true;
1669
- if (((_a2 = node[":@"]) == null ? void 0 : _a2["@_refines"]) !== `#${id}`) return true;
1670
- return false;
1671
- });
1672
- Epub.replaceXmlChildren(metadata, newChildren);
1673
- }
1674
- });
1675
- }
1676
- /**
1677
- * Retrieve the list of creators.
1678
- *
1679
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccreator
1680
- */
1681
- async getCreators(type = "creator") {
1682
- const metadata = await this.getMetadata();
1683
- const creatorEntries = metadata.filter(
1684
- (entry) => entry.type === `dc:${type}`
1685
- );
1686
- const creators = [];
1687
- const creatorsById = /* @__PURE__ */ new Map();
1688
- for (const entry of creatorEntries) {
1689
- if (!entry.value) continue;
1690
- const creator = { name: entry.value };
1691
- creators.push(creator);
1692
- if (entry.id) creatorsById.set(entry.id, creator);
1693
- }
1694
- metadata.forEach((entry) => {
1695
- if (entry.type !== "meta" || entry.properties["property"] !== "file-as" && entry.properties["property"] !== "role" && entry.properties["property"] !== "alternate-script" || !entry.value) {
1696
- return;
1697
- }
1698
- const creatorIdref = entry.properties["refines"];
1699
- if (!creatorIdref) return;
1700
- const creatorId = creatorIdref.slice(1);
1701
- const creator = creatorsById.get(creatorId);
1702
- if (!creator) return;
1703
- if (entry.properties["alternate-script"]) {
1704
- if (!entry.properties["xml:lang"]) return;
1705
- creator.alternateScripts ??= [];
1706
- creator.alternateScripts.push({
1707
- name: entry.value,
1708
- locale: new Intl.Locale(entry.properties["xml:lang"])
1709
- });
1710
- return;
1711
- }
1712
- const prop = entry.properties["property"] === "file-as" ? "fileAs" : "role";
1713
- creator[prop] = entry.value;
1714
- if (prop === "role" && entry.properties["scheme"]) {
1715
- creator.roleScheme = entry.properties["scheme"];
1716
- }
1717
- });
1718
- return creators;
1719
- }
1720
- /**
1721
- * Retrieve the list of contributors.
1722
- *
1723
- * This is a convenience method for
1724
- * `epub.getCreators('contributor')`.
1725
- *
1726
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccontributor
1727
- */
1728
- getContributors() {
1729
- return this.getCreators("contributor");
1730
- }
1731
- /**
1732
- * Add a creator to the EPUB metadata.
1733
- *
1734
- * If index is provided, the creator will be placed at
1735
- * that index in the list of creators. Otherwise, it
1736
- * will be added to the end of the list.
1737
- *
1738
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccreator
1739
- */
1740
- async addCreator(creator, index, type = "creator") {
1741
- const creatorId = (0, import_nanoid.nanoid)();
1742
- await this.withPackage((packageElement) => {
1743
- const metadata = Epub.findXmlChildByName(
1744
- "metadata",
1745
- Epub.getXmlChildren(packageElement)
1746
- );
1747
- if (!metadata)
1748
- throw new Error(
1749
- "Failed to parse EPUB: found no metadata element in package document"
1750
- );
1751
- let creatorCount = 0;
1752
- let metadataIndex = 0;
1753
- for (const meta of Epub.getXmlChildren(metadata)) {
1754
- if (creatorCount === index) break;
1755
- metadataIndex++;
1756
- if (Epub.isXmlTextNode(meta)) continue;
1757
- if (Epub.getXmlElementName(meta) !== `dc:${type}`) continue;
1758
- creatorCount++;
1759
- }
1760
- Epub.getXmlChildren(metadata).splice(
1761
- metadataIndex,
1762
- 0,
1763
- Epub.createXmlElement(`dc:${type}`, { id: creatorId }, [
1764
- Epub.createXmlTextNode(creator.name)
1765
- ])
1766
- );
1767
- });
1768
- if (creator.role) {
1769
- await this.addMetadata({
1770
- type: "meta",
1771
- properties: {
1772
- refines: `#${creatorId}`,
1773
- property: "role",
1774
- ...creator.roleScheme && { scheme: creator.roleScheme }
1775
- },
1776
- value: creator.role
1777
- });
1778
- }
1779
- if (creator.fileAs) {
1780
- await this.addMetadata({
1781
- type: "meta",
1782
- properties: { refines: `#${creatorId}`, property: "file-as" },
1783
- value: creator.fileAs
1784
- });
1785
- }
1786
- if (creator.alternateScripts) {
1787
- for (const alternate of creator.alternateScripts) {
1788
- await this.addMetadata({
1789
- type: "meta",
1790
- properties: {
1791
- refines: `#${creatorId}`,
1792
- property: "alternate-script",
1793
- "xml:lang": alternate.locale.toString()
1794
- },
1795
- value: alternate.name
1796
- });
1797
- }
1798
- }
1799
- }
1800
- /**
1801
- * Remove a creator from the EPUB metadata.
1802
- *
1803
- * Removes the creator at the provided index. This index
1804
- * refers to the array returned by `epub.getCreators()`.
1805
- *
1806
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccreator
1807
- */
1808
- async removeCreator(index, type = "creator") {
1809
- await this.withPackage((packageElement) => {
1810
- var _a;
1811
- const metadata = Epub.findXmlChildByName(
1812
- "metadata",
1813
- Epub.getXmlChildren(packageElement)
1814
- );
1815
- if (!metadata)
1816
- throw new Error(
1817
- "Failed to parse EPUB: found no metadata element in package document"
1818
- );
1819
- let creatorCount = null;
1820
- let metadataIndex = null;
1821
- for (const meta of Epub.getXmlChildren(metadata)) {
1822
- if (creatorCount === index) break;
1823
- metadataIndex = metadataIndex === null ? 0 : metadataIndex + 1;
1824
- if (Epub.isXmlTextNode(meta)) continue;
1825
- if (Epub.getXmlElementName(meta) !== `dc:${type}`) continue;
1826
- creatorCount = creatorCount === null ? 0 : creatorCount + 1;
1827
- }
1828
- if (creatorCount === null || metadataIndex === null) return;
1829
- const [removed] = Epub.getXmlChildren(metadata).splice(metadataIndex, 1);
1830
- if (removed && !Epub.isXmlTextNode(removed) && ((_a = removed[":@"]) == null ? void 0 : _a["@_id"])) {
1831
- const id = removed[":@"]["@_id"];
1832
- const newChildren = Epub.getXmlChildren(metadata).filter((node) => {
1833
- var _a2;
1834
- if (Epub.isXmlTextNode(node)) return true;
1835
- if (Epub.getXmlElementName(node) !== "meta") return true;
1836
- if (((_a2 = node[":@"]) == null ? void 0 : _a2["@_refines"]) !== `#${id}`) return true;
1837
- return false;
1838
- });
1839
- Epub.replaceXmlChildren(metadata, newChildren);
1840
- }
1841
- });
1842
- }
1843
- /**
1844
- * Remove a contributor from the EPUB metadata.
1845
- *
1846
- * Removes the contributor at the provided index. This index
1847
- * refers to the array returned by `epub.getContributors()`.
1848
- *
1849
- * This is a convenience method for
1850
- * `epub.removeCreator(index, 'contributor')`.
1851
- *
1852
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccreator
1853
- */
1854
- async removeContributor(index) {
1855
- return this.removeCreator(index, "contributor");
1856
- }
1857
- /**
1858
- * Add a contributor to the EPUB metadata.
1859
- *
1860
- * If index is provided, the creator will be placed at
1861
- * that index in the list of creators. Otherwise, it
1862
- * will be added to the end of the list.
1863
- *
1864
- * This is a convenience method for
1865
- * `epub.addCreator(contributor, index, 'contributor')`.
1866
- *
1867
- * @link https://www.w3.org/TR/epub-33/#sec-opf-dccreator
1868
- */
1869
- addContributor(contributor, index) {
1870
- return this.addCreator(contributor, index, "contributor");
1871
- }
1872
- async getSpine() {
1873
- if (this.spine !== null) return this.spine;
1874
- const packageElement = await this.getPackageElement();
1875
- const spine = Epub.findXmlChildByName(
1876
- "spine",
1877
- Epub.getXmlChildren(packageElement)
1878
- );
1879
- if (!spine)
1880
- throw new Error(
1881
- "Failed to parse EPUB: Found no spine element in package document"
1882
- );
1883
- this.spine = spine["spine"].filter((node) => !Epub.isXmlTextNode(node)).map((itemref) => {
1884
- var _a;
1885
- return (_a = itemref[":@"]) == null ? void 0 : _a["@_idref"];
1886
- }).filter((idref) => !!idref);
1887
- return this.spine;
1888
- }
1889
- /**
1890
- * Retrieve the manifest items that make up the Epub's spine.
1891
- *
1892
- * The spine specifies the order that the contents of the Epub
1893
- * should be displayed to users by default.
1894
- *
1895
- * @link https://www.w3.org/TR/epub-33/#sec-spine-elem
1896
- */
1897
- async getSpineItems() {
1898
- const spine = await this.getSpine();
1899
- const manifest = await this.getManifest();
1900
- return spine.map((itemref) => manifest[itemref]).filter((entry) => !!entry);
1901
- }
1902
- /**
1903
- * Add an item to the spine of the EPUB.
1904
- *
1905
- * If `index` is undefined, the item will be added
1906
- * to the end of the spine. Otherwise it will be
1907
- * inserted at the specified index.
1908
- *
1909
- * If the manifestId does not correspond to an item
1910
- * in the manifest, this will throw an error.
1911
- *
1912
- * @link https://www.w3.org/TR/epub-33/#sec-spine-elem
1913
- */
1914
- async addSpineItem(manifestId, index) {
1915
- const item = Epub.createXmlElement("itemref", { idref: manifestId });
1916
- const manifest = await this.getManifest();
1917
- const manifestItem = manifest[manifestId];
1918
- if (!manifestItem)
1919
- throw new Error(`Manifest item not found with id "${manifestId}"`);
1920
- await this.withPackage((packageElement) => {
1921
- const spine = Epub.findXmlChildByName(
1922
- "spine",
1923
- Epub.getXmlChildren(packageElement)
1924
- );
1925
- if (!spine)
1926
- throw new Error(
1927
- "Failed to parse EPUB: Found no spine element in package document"
1928
- );
1929
- if (index === void 0) {
1930
- Epub.getXmlChildren(spine).push(item);
1931
- } else {
1932
- Epub.getXmlChildren(spine).splice(index, 0, item);
1933
- }
1934
- });
1935
- this.spine = null;
1936
- }
1937
- /**
1938
- * Remove the spine item at the specified index.
1939
- *
1940
- * @link https://www.w3.org/TR/epub-33/#sec-spine-elem
1941
- */
1942
- async removeSpineItem(index) {
1943
- await this.withPackage((packageElement) => {
1944
- const spine = Epub.findXmlChildByName(
1945
- "spine",
1946
- Epub.getXmlChildren(packageElement)
1947
- );
1948
- if (!spine)
1949
- throw new Error(
1950
- "Failed to parse EPUB: Found no spine element in package document"
1951
- );
1952
- Epub.getXmlChildren(spine).splice(index, 1);
1953
- });
1954
- this.spine = null;
1955
- }
1956
- async getNavigationChildren(ol, navHref, { resolveToRoot } = {}) {
1957
- var _a;
1958
- const children = [];
1959
- const childrenElements = Epub.getXmlChildren(ol).filter(
1960
- (node) => !Epub.isXmlTextNode(node) && Epub.getXmlElementName(node) === "li"
1961
- );
1962
- for (const childEl of childrenElements) {
1963
- const [firstChild, secondChild] = Epub.getXmlChildren(childEl).filter(
1964
- (node) => !Epub.isXmlTextNode(node) && ["a", "span", "ol"].includes(Epub.getXmlElementName(node))
1965
- );
1966
- if (!firstChild) continue;
1967
- if (!["a", "span"].includes(Epub.getXmlElementName(firstChild))) {
1968
- continue;
1969
- }
1970
- if (Epub.getXmlElementName(firstChild) === "span" && (!secondChild || Epub.getXmlElementName(secondChild) !== "ol")) {
1971
- continue;
1972
- }
1973
- children.push({
1974
- title: Epub.getXhtmlTextContent(Epub.getXmlChildren(firstChild)),
1975
- ...Epub.getXmlElementName(firstChild) === "a" && ((_a = firstChild[":@"]) == null ? void 0 : _a["@_href"]) && {
1976
- href: await this.resolveHref(
1977
- firstChild[":@"]["@_href"],
1978
- void 0,
1979
- { toRoot: resolveToRoot }
1980
- )
1981
- },
1982
- ...secondChild && Epub.getXmlElementName(secondChild) === "ol" && {
1983
- children: await this.getNavigationChildren(secondChild, navHref, {
1984
- resolveToRoot
1985
- })
1986
- }
1987
- });
1988
- }
1989
- return children;
1990
- }
1991
- async getNavigation(role, { resolveToRoot } = {}) {
1992
- const manifest = await this.getManifest();
1993
- const navItem = Object.values(manifest).find(
1994
- (item) => {
1995
- var _a;
1996
- return (_a = item.properties) == null ? void 0 : _a.includes("nav");
1997
- }
1998
- );
1999
- if (!navItem) return null;
2000
- const navContents = await this.readXhtmlItemContents(navItem.id);
2001
- const navEl = Epub.findXmlDescendantByName(
2002
- "nav",
2003
- navContents,
2004
- (node) => Epub.getXmlAttributes(node)["epub:type"] === role
2005
- );
2006
- if (!navEl) return null;
2007
- const [firstChild, secondChild] = Epub.getXmlChildren(navEl).filter(
2008
- (node) => !!(!Epub.isXmlTextNode(node) && Epub.getXmlElementName(node).match(/(?:h[1-6]|ol)/))
2009
- );
2010
- if (!firstChild) return null;
2011
- const title = Epub.getXmlElementName(firstChild).match(/h[1-6]/) ? Epub.getXhtmlTextContent(Epub.getXmlChildren(firstChild)) : null;
2012
- const list = Epub.getXmlElementName(firstChild) === "ol" ? firstChild : secondChild && Epub.getXmlElementName(secondChild) === "ol" ? secondChild : null;
2013
- if (!list) return null;
2014
- const children = await this.getNavigationChildren(list, navItem.href, {
2015
- resolveToRoot
2016
- });
2017
- return {
2018
- ...title && { title },
2019
- children
2020
- };
2021
- }
2022
- /**
2023
- * Returns the structured table of contents navigation document
2024
- * as a Navigation object.
2025
- *
2026
- * @link https://www.w3.org/TR/epub-33/#sec-nav-toc
2027
- */
2028
- async getTableOfContents({
2029
- resolveToRoot
2030
- } = {}) {
2031
- const navigationToc = await this.getNavigation("toc", { resolveToRoot });
2032
- if (navigationToc) return navigationToc;
2033
- const ncxToc = await this.getNcxTableOfContents();
2034
- return {
2035
- children: ncxToc
2036
- };
2037
- }
2038
- /**
2039
- * Returns the structured landmarks navigation document
2040
- * as a Navigation object
2041
- *
2042
- * @link https://www.w3.org/TR/epub-33/#sec-nav-landmarks
2043
- */
2044
- async getLandmarks({
2045
- resolveToRoot
2046
- } = {}) {
2047
- return this.getNavigation("landmarks", { resolveToRoot });
2048
- }
2049
- /**
2050
- * Returns the structured page list navigation document
2051
- * as a Navigation object
2052
- *
2053
- * @link https://www.w3.org/TR/epub-33/#sec-nav-landmarks
2054
- */
2055
- async getPageList({
2056
- resolveToRoot
2057
- } = {}) {
2058
- return this.getNavigation("page-list", { resolveToRoot });
2059
- }
2060
- /**
2061
- * Returns a Zip Entry path for an HREF
2062
- */
2063
- resolveInternalHref(from, href) {
2064
- const startPath = (0, import_path.dirname)(from);
2065
- return (0, import_path.resolve)(
2066
- this.adapter.rootPath,
2067
- (0, import_path.hrefToPlatformPath)(startPath),
2068
- (0, import_path.hrefToPlatformPath)(href)
2069
- );
2070
- }
2071
- /**
2072
- * Returns a path-relative-scheme-less URL, relative to the
2073
- * container root.
2074
- *
2075
- * @param href The href to resolve
2076
- * @param [relativeTo] Optional - The href to resolve this href relative to.
2077
- Use if resolving a relative href from a file other than the package document.
2078
- */
2079
- async resolveHref(href, relativeTo, { toRoot } = {}) {
2080
- const rootfile = await this.getRootfile();
2081
- const from = relativeTo ? this.resolveInternalHref(rootfile, relativeTo) : rootfile;
2082
- const path = this.resolveInternalHref(from, href);
2083
- return path.replace(toRoot ? this.adapter.rootPath : (0, import_path.dirname)(rootfile), "").slice(1);
2084
- }
2085
- async readFileContents(href, relativeTo, encoding) {
2086
- const rootfile = await this.getRootfile();
2087
- const from = relativeTo ? this.resolveInternalHref(rootfile, relativeTo) : rootfile;
2088
- const path = this.resolveInternalHref(from, href);
2089
- const itemEntry = encoding ? await this.getFileData(path, encoding) : await this.getFileData(path);
2090
- return itemEntry;
2091
- }
2092
- async readItemContents(id, encoding) {
2093
- const rootfile = await this.getRootfile();
2094
- const manifest = await this.getManifest();
2095
- const manifestItem = manifest[id];
2096
- if (!manifestItem)
2097
- throw new Error(`Could not find item with id "${id}" in manifest`);
2098
- const path = this.resolveInternalHref(rootfile, manifestItem.href);
2099
- const itemEntry = encoding ? await this.getFileData(path, encoding) : await this.getFileData(path);
2100
- return itemEntry;
2101
- }
2102
- /**
2103
- * Create a new XHTML document with the given body
2104
- * and head.
2105
- *
2106
- * @param body The XML nodes to place in the body of the document
2107
- * @param head Optional - the XMl nodes to place in the head
2108
- * @param language Optional - defaults to the EPUB's language
2109
- */
2110
- async createXhtmlDocument(body, head, language) {
2111
- const lang = language ?? await this.getLanguage();
2112
- return [
2113
- Epub.createXmlElement("?xml", { version: "1.0", encoding: "UTF-8" }, [
2114
- { "#text": "" }
2115
- ]),
2116
- Epub.createXmlElement(
2117
- "html",
2118
- {
2119
- xmlns: "http://www.w3.org/1999/xhtml",
2120
- "xmlns:epub": "http://www.idpf.org/2007/ops",
2121
- ...lang && { "xml:lang": lang.toString(), lang: lang.toString() }
2122
- },
2123
- [
2124
- Epub.createXmlElement("head", {}, head),
2125
- Epub.createXmlElement("body", {}, body)
2126
- ]
2127
- )
2128
- ];
2129
- }
2130
- async readXhtmlItemContents(id, as = "xhtml") {
2131
- const contents = await this.readItemContents(id, "utf-8");
2132
- const xml = Epub.xhtmlParser.parse(contents);
2133
- if (as === "xhtml") return xml;
2134
- const body = Epub.getXhtmlBody(xml);
2135
- return Epub.getXhtmlTextContent(body);
2136
- }
2137
- async writeEntryContents(path, contents, encoding) {
2138
- this.assertWritable();
2139
- if (!this.adapter.write) {
2140
- throw new EpubReadOnlyError(
2141
- `adapter ${this.adapterClass.kind} does not support writes`
2142
- );
2143
- }
2144
- if (encoding === "utf-8") {
2145
- await this.adapter.write(path, contents, encoding);
2146
- } else {
2147
- await this.adapter.write(path, contents);
2148
- }
2149
- }
2150
- async writeItemContents(id, contents, encoding) {
2151
- const rootfile = await this.getRootfile();
2152
- const manifest = await this.getManifest();
2153
- const manifestItem = manifest[id];
2154
- if (!manifestItem)
2155
- throw new Error(`Could not find item with id "${id}" in manifest`);
2156
- import_mem.default.clear(this.readXhtmlItemContents);
2157
- const href = this.resolveInternalHref(rootfile, manifestItem.href);
2158
- if (encoding === "utf-8") {
2159
- await this.writeEntryContents(href, contents, encoding);
2160
- } else {
2161
- await this.writeEntryContents(href, contents);
2162
- }
2163
- }
2164
- /**
2165
- * Write new contents for an existing XHTML item,
2166
- * specified by its id.
2167
- *
2168
- * The id must reference an existing manifest item. If
2169
- * creating a new item, use `epub.addManifestItem()` instead.
2170
- *
2171
- * @param id The id of the manifest item to write new contents for
2172
- * @param contents The new contents. Must be a parsed XML tree.
2173
- *
2174
- * @link https://www.w3.org/TR/epub-33/#sec-xhtml
2175
- */
2176
- async writeXhtmlItemContents(id, contents) {
2177
- await this.writeItemContents(
2178
- id,
2179
- Epub.xhtmlBuilder.build(contents),
2180
- "utf-8"
2181
- );
2182
- }
2183
- async removeManifestItem(id) {
2184
- await this.withPackage(async (packageElement) => {
2185
- var _a;
2186
- const manifest = Epub.findXmlChildByName(
2187
- "manifest",
2188
- Epub.getXmlChildren(packageElement)
2189
- );
2190
- if (!manifest)
2191
- throw new Error(
2192
- "Failed to parse EPUB: Found no manifest element in package document"
2193
- );
2194
- const itemIndex = Epub.getXmlChildren(manifest).findIndex(
2195
- (node) => {
2196
- var _a2;
2197
- return !Epub.isXmlTextNode(node) && ((_a2 = node[":@"]) == null ? void 0 : _a2["@_id"]) === id;
2198
- }
2199
- );
2200
- if (itemIndex === -1) return;
2201
- const [item] = Epub.getXmlChildren(manifest).splice(itemIndex, 1);
2202
- if (!item || Epub.isXmlTextNode(item) || !((_a = item[":@"]) == null ? void 0 : _a["@_href"])) return;
2203
- await this.removeEntry(item[":@"]["@_href"]);
2204
- });
2205
- this.manifest = null;
2206
- }
2207
- async addManifestItem(item, contents, encoding) {
2208
- await this.withPackage((packageElement) => {
2209
- const manifest = Epub.findXmlChildByName(
2210
- "manifest",
2211
- Epub.getXmlChildren(packageElement)
2212
- );
2213
- if (!manifest)
2214
- throw new Error(
2215
- "Failed to parse EPUB: Found no manifest element in package document"
2216
- );
2217
- Epub.getXmlChildren(manifest).push(
2218
- Epub.createXmlElement("item", {
2219
- id: item.id,
2220
- href: item.href,
2221
- ...item.mediaType && { "media-type": item.mediaType },
2222
- ...item.fallback && { fallback: item.fallback },
2223
- ...item.mediaOverlay && { "media-overlay": item.mediaOverlay },
2224
- ...item.properties && {
2225
- properties: item.properties.join(" ")
2226
- }
2227
- })
2228
- );
2229
- });
2230
- this.manifest = null;
2231
- const rootfile = await this.getRootfile();
2232
- const filename = this.resolveInternalHref(rootfile, item.href);
2233
- const data = encoding === "utf-8" || encoding === "xml" ? new TextEncoder().encode(
2234
- encoding === "utf-8" ? contents : await Epub.xmlBuilder.build(
2235
- contents
2236
- )
2237
- ) : contents;
2238
- await this.writeEntryContents(filename, data);
2239
- }
2240
- /**
2241
- * Update the manifest entry for an existing item.
2242
- *
2243
- * To update the contents of an entry, use `epub.writeItemContents()`
2244
- * or `epub.writeXhtmlItemContents()`
2245
- *
2246
- * @link https://www.w3.org/TR/epub-33/#sec-pkg-manifest
2247
- */
2248
- async updateManifestItem(id, newItem) {
2249
- await this.withPackage((packageElement) => {
2250
- const manifest = Epub.findXmlChildByName(
2251
- "manifest",
2252
- Epub.getXmlChildren(packageElement)
2253
- );
2254
- if (!manifest)
2255
- throw new Error(
2256
- "Failed to parse EPUB: Found no manifest element in package document"
2257
- );
2258
- const itemIndex = manifest["manifest"].findIndex(
2259
- (item) => {
2260
- var _a;
2261
- return !Epub.isXmlTextNode(item) && ((_a = item[":@"]) == null ? void 0 : _a["@_id"]) === id;
2262
- }
2263
- );
2264
- Epub.getXmlChildren(manifest).splice(
2265
- itemIndex,
2266
- 1,
2267
- Epub.createXmlElement("item", {
2268
- id,
2269
- href: newItem.href,
2270
- ...newItem.mediaType && { "media-type": newItem.mediaType },
2271
- ...newItem.fallback && { fallback: newItem.fallback },
2272
- ...newItem.mediaOverlay && {
2273
- "media-overlay": newItem.mediaOverlay
2274
- },
2275
- ...newItem.properties && {
2276
- properties: newItem.properties.join(" ")
2277
- }
2278
- })
2279
- );
2280
- });
2281
- this.manifest = null;
2282
- }
2283
- /**
2284
- * Add a new metadata entry to the Epub.
2285
- *
2286
- * This method, like `epub.getMetadata()`, operates on
2287
- * metadata entries. For more useful semantic representations
2288
- * of metadata, use specific methods such as `setTitle()` and
2289
- * `setLanguage()`.
2290
- *
2291
- * @link https://www.w3.org/TR/epub-33/#sec-pkg-metadata
2292
- */
2293
- async addMetadata(entry) {
2294
- await this.withPackage((packageElement) => {
2295
- const metadata = Epub.findXmlChildByName(
2296
- "metadata",
2297
- Epub.getXmlChildren(packageElement)
2298
- );
2299
- if (!metadata)
2300
- throw new Error(
2301
- "Failed to parse EPUB: found no metadata element in package document"
2302
- );
2303
- Epub.getXmlChildren(metadata).push(
2304
- Epub.createXmlElement(
2305
- entry.type,
2306
- {
2307
- ...entry.id && { id: entry.id },
2308
- ...entry.properties
2309
- },
2310
- entry.value !== void 0 ? [Epub.createXmlTextNode(entry.value)] : []
2311
- )
2312
- );
2313
- });
2314
- }
2315
- /**
2316
- * Replace a metadata entry with a new one.
2317
- *
2318
- * The `predicate` argument will be used to determine which entry
2319
- * to replace. The first metadata entry that matches the
2320
- * predicate will be replaced.
2321
- *
2322
- * @param predicate Calls predicate once for each metadata entry,
2323
- * until it finds one where predicate returns true
2324
- * @param entry The new entry to replace the found entry with
2325
- *
2326
- * @link https://www.w3.org/TR/epub-33/#sec-pkg-metadata
2327
- */
2328
- async replaceMetadata(predicate, entry) {
2329
- await this.withPackage((packageElement) => {
2330
- const metadataElement = Epub.findXmlChildByName(
2331
- "metadata",
2332
- Epub.getXmlChildren(packageElement)
2333
- );
2334
- if (!metadataElement)
2335
- throw new Error(
2336
- "Failed to parse EPUB: found no metadata element in package document"
2337
- );
2338
- const oldEntryIndex = this.findMetadataIndex(packageElement, predicate);
2339
- const newElement = Epub.createXmlElement(
2340
- entry.type,
2341
- {
2342
- ...entry.id && { id: entry.id },
2343
- ...entry.properties
2344
- },
2345
- entry.value !== void 0 ? [Epub.createXmlTextNode(entry.value)] : []
2346
- );
2347
- if (oldEntryIndex === -1) {
2348
- metadataElement.metadata.push(newElement);
2349
- } else {
2350
- metadataElement.metadata.splice(oldEntryIndex, 1, newElement);
2351
- }
2352
- });
2353
- }
2354
- /**
2355
- * Remove one or more metadata entries.
2356
- *
2357
- * The `predicate` argument will be used to determine which entries
2358
- * to remove. The all metadata entries that match the
2359
- * predicate will be removed.
2360
- *
2361
- * @param predicate Calls predicate once for each metadata entry,
2362
- * removing any for which it returns true
2363
- *
2364
- * @link https://www.w3.org/TR/epub-33/#sec-pkg-metadata
2365
- */
2366
- async removeMetadata(predicate) {
2367
- await this.withPackage((packageElement) => {
2368
- const metadataElement = Epub.findXmlChildByName(
2369
- "metadata",
2370
- Epub.getXmlChildren(packageElement)
2371
- );
2372
- if (!metadataElement) {
2373
- throw new Error(
2374
- "Failed to parse EPUB: found no metadata element in package document"
2375
- );
2376
- }
2377
- const metadataEntries = Epub.getXmlChildren(metadataElement);
2378
- for (let i = metadataEntries.length - 1; i >= 0; i--) {
2379
- const meta = metadataEntries[i];
2380
- const item = Epub.parseMetadataItem(meta);
2381
- if (!item) continue;
2382
- if (predicate(item)) {
2383
- metadataEntries.splice(i, 1);
2384
- }
2385
- }
2386
- });
2387
- }
2388
- /**
2389
- * Returns the EPUB version declared on the package element.
2390
- */
2391
- async getVersion() {
2392
- var _a;
2393
- const packageElement = await this.getPackageElement();
2394
- return ((_a = packageElement[":@"]) == null ? void 0 : _a["@_version"]) ?? "2.0";
2395
- }
2396
- /**
2397
- * Parse the NCX table of contents, if one exists, and return
2398
- * a tree of TocEntry nodes.
2399
- *
2400
- * Useful for both EPUB 2 publications (where the NCX is the
2401
- * primary navigation) and EPUB 3 publications that retain an
2402
- * NCX for backwards compatibility.
2403
- */
2404
- async getNcxTableOfContents() {
2405
- var _a;
2406
- const [manifest, packageElement] = await Promise.all([
2407
- this.getManifest(),
2408
- this.getPackageElement()
2409
- ]);
2410
- const spine = Epub.findXmlChildByName(
2411
- "spine",
2412
- Epub.getXmlChildren(packageElement)
2413
- );
2414
- const spineTocId = (_a = spine == null ? void 0 : spine[":@"]) == null ? void 0 : _a["@_toc"];
2415
- const ncxItem = spineTocId ? manifest[spineTocId] : Object.values(manifest).find(
2416
- (item) => {
2417
- var _a2;
2418
- return ((_a2 = item.mediaType) == null ? void 0 : _a2.toLowerCase()) === "application/x-dtbncx+xml";
2419
- }
2420
- );
2421
- if (!ncxItem) return [];
2422
- const ncxContent = await this.readItemContents(ncxItem.id, "utf-8");
2423
- const ncxXml = Epub.xmlParser.parse(ncxContent);
2424
- const ncxElement = Epub.findXmlChildByName("ncx", ncxXml);
2425
- if (!ncxElement) return [];
2426
- const ncxChildren = Epub.getXmlChildren(ncxElement);
2427
- const navMap = Epub.findXmlChildByName("navMap", ncxChildren) ?? Epub.findXmlChildByName("navmap", ncxChildren);
2428
- if (!navMap) return [];
2429
- return this.parseNavPoints(Epub.getXmlChildren(navMap), ncxItem.href);
2430
- }
2431
- async parseNavPoints(nodes, ncxHref) {
2432
- var _a;
2433
- const entries = [];
2434
- for (const node of nodes) {
2435
- if (Epub.isXmlTextNode(node)) continue;
2436
- const name = Epub.getXmlElementName(node);
2437
- const isNavPoint = name === "navPoint" || name === "navpoint";
2438
- if (!isNavPoint) continue;
2439
- const children = Epub.getXmlChildren(node);
2440
- const navLabel = Epub.findXmlChildByName("navLabel", children) ?? Epub.findXmlChildByName("navlabel", children);
2441
- let title = null;
2442
- if (navLabel) {
2443
- const textEl = Epub.findXmlChildByName(
2444
- "text",
2445
- Epub.getXmlChildren(navLabel)
2446
- );
2447
- if (textEl) {
2448
- title = Epub.getXhtmlTextContent(Epub.getXmlChildren(textEl)).trim() || null;
2449
- }
2450
- }
2451
- const contentEl = Epub.findXmlChildByName("content", children);
2452
- const src = (_a = contentEl == null ? void 0 : contentEl[":@"]) == null ? void 0 : _a["@_src"];
2453
- const href = src ? await this.resolveHref(src, ncxHref) : null;
2454
- const childEntries = await this.parseNavPoints(children, ncxHref);
2455
- entries.push({
2456
- title: title ?? `${entries.length}`,
2457
- ...href && { href },
2458
- children: childEntries
2459
- });
2460
- }
2461
- return entries;
2462
- }
2463
- /**
2464
- * Retrieve the guide entries from the package document.
2465
- *
2466
- * The guide element is deprecated in EPUB 3 in favor of
2467
- * the landmarks nav, but many publications still include it.
2468
- */
2469
- async getGuideEntries() {
2470
- const packageElement = await this.getPackageElement();
2471
- const guide = Epub.findXmlChildByName(
2472
- "guide",
2473
- Epub.getXmlChildren(packageElement)
2474
- );
2475
- if (!guide) return [];
2476
- return Epub.getXmlChildren(guide).filter(
2477
- (node) => !Epub.isXmlTextNode(node) && "reference" in node
2478
- ).map((ref) => {
2479
- var _a, _b, _c;
2480
- return {
2481
- href: ((_a = ref[":@"]) == null ? void 0 : _a["@_href"]) ?? "",
2482
- title: ((_b = ref[":@"]) == null ? void 0 : _b["@_title"]) ?? "",
2483
- type: (((_c = ref[":@"]) == null ? void 0 : _c["@_type"]) ?? "").toLowerCase()
2484
- };
2485
- }).filter((entry) => entry.href);
2486
- }
2487
- discardAndClose() {
2488
- this.rootfile = null;
2489
- this.manifest = null;
2490
- this.spine = null;
2491
- void this.adapter.dispose();
2492
- }
2493
- /**
2494
- * Write the current contents of the Epub to a new
2495
- * EPUB archive on disk.
2496
- *
2497
- * When this method is called, the "dcterms:modified"
2498
- * meta tag is automatically updated to the current UTC
2499
- * timestamp.
2500
- */
2501
- async saveAndClose() {
2502
- this.assertWritable();
2503
- if (!this.inputPath) {
2504
- throw new Error("In-memory EPUB files cannot be saved to disk");
2505
- }
2506
- if (!this.adapter.serialize) {
2507
- throw new Error(
2508
- `adapter ${this.adapterClass.kind} does not support serialization`
2509
- );
2510
- }
2511
- await this.replaceMetadata(
2512
- (entry) => entry.properties["property"] === "dcterms:modified",
2513
- {
2514
- type: "meta",
2515
- properties: { property: "dcterms:modified" },
2516
- // We need UTC with integer seconds, but toISOString gives UTC with ms
2517
- value: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d+/, "")
2518
- }
2519
- );
2520
- await this.adapter.serialize(this.inputPath);
2521
- }
2522
- /**
2523
- * Upgrade an EPUB 2 publication to EPUB 3 in place, returning a new,
2524
- * valid Epub 3 instance. Equivalent to
2525
- * `Epub.using(TmpFsAdapter).upgrade(...)`.
2526
- */
2527
- static async upgrade(path, options = {}) {
2528
- return Epub.using(import_tmpfs.TmpFsAdapter).upgrade(path, options);
2529
- }
2530
- [Symbol.dispose]() {
2531
- this.discardAndClose();
2532
- }
2533
- }
2534
- class EpubFactory {
2535
- constructor(adapterClass) {
2536
- this.adapterClass = adapterClass;
2537
- }
2538
- async from(source, options = {}) {
2539
- const adapter = await this.adapterClass.init(
2540
- source,
2541
- options
2542
- );
2543
- const inputPath = typeof source === "string" ? source : void 0;
2544
- const readonlyOverride = options.readonly === true;
2545
- const epub = new Epub(
2546
- this.adapterClass,
2547
- adapter,
2548
- inputPath,
2549
- readonlyOverride
2550
- );
2551
- try {
2552
- await epub.getPackageElement();
2553
- } catch (e) {
2554
- epub.discardAndClose();
2555
- console.error(e);
2556
- throw new Error(
2557
- "This is not a valid EPUB publication. Could not read the package document."
2558
- );
2559
- }
2560
- await Epub.assertEpub3(epub);
2561
- return epub;
2562
- }
2563
- /**
2564
- * Construct a new EPUB on this factory's adapter, optionally seeded
2565
- * with the provided metadata. Requires a writable adapter that
2566
- * implements `initEmpty` (today: {@link TmpFsAdapter}).
2567
- *
2568
- * @throws when the adapter is read-only or does not implement initEmpty
2569
- */
2570
- async create(path, {
2571
- title,
2572
- language,
2573
- identifier,
2574
- date,
2575
- subjects,
2576
- type,
2577
- creators,
2578
- contributors
2579
- }, additionalMetadata = []) {
2580
- if (!this.adapterClass.capabilities.writable) {
2581
- throw new EpubReadOnlyError(
2582
- `adapter ${this.adapterClass.kind} is read-only; cannot create`
2583
- );
2584
- }
2585
- if (!this.adapterClass.initEmpty) {
2586
- throw new Error(
2587
- `adapter ${this.adapterClass.kind} does not support create() (missing initEmpty)`
2588
- );
2589
- }
2590
- const adapter = await this.adapterClass.initEmpty();
2591
- if (!adapter.write) {
2592
- throw new Error(
2593
- `adapter ${this.adapterClass.kind} declared writable but did not implement write()`
2594
- );
2595
- }
2596
- const encoder = new TextEncoder();
2597
- const container = encoder.encode(`<?xml version="1.0"?>
2598
- <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
2599
- <rootfiles>
2600
- <rootfile media-type="application/oebps-package+xml" full-path="OEBPS/content.opf"/>
2601
- </rootfiles>
2602
- </container>
2603
- `);
2604
- await adapter.write(
2605
- (0, import_path.join)(adapter.rootPath, "META-INF", "container.xml"),
2606
- container
2607
- );
2608
- const packageDocument = encoder.encode(`<?xml version="1.0"?>
2609
- <package unique-identifier="pub-id" dir="${language.textInfo.direction}" xml:lang="${language.toString()}" version="3.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
2610
- <metadata>
2611
- </metadata>
2612
- <manifest>
2613
- </manifest>
2614
- <spine>
2615
- </spine>
2616
- </package>
2617
- `);
2618
- await adapter.write(
2619
- (0, import_path.join)(adapter.rootPath, "OEBPS", "content.opf"),
2620
- packageDocument
2621
- );
2622
- const epub = new Epub(this.adapterClass, adapter, path);
2623
- const metadata = [
2624
- {
2625
- id: "pub-id",
2626
- type: "dc:identifier",
2627
- properties: {},
2628
- value: identifier
2629
- },
2630
- ...additionalMetadata
2631
- ];
2632
- await Promise.all(metadata.map((entry) => epub.addMetadata(entry)));
2633
- await epub.setTitle(title);
2634
- await epub.setLanguage(language);
2635
- if (date) await epub.setPublicationDate(date);
2636
- if (type) await epub.setType(type);
2637
- if (subjects) {
2638
- await Promise.all(subjects.map((subject) => epub.addSubject(subject)));
2639
- }
2640
- if (creators) {
2641
- await Promise.all(creators.map((creator) => epub.addCreator(creator)));
2642
- }
2643
- if (contributors) {
2644
- await Promise.all(
2645
- contributors.map((contributor) => epub.addCreator(contributor))
2646
- );
2647
- }
2648
- return epub;
2649
- }
2650
- /**
2651
- * Upgrade an EPUB 2 publication to EPUB 3 in place using this
2652
- * factory's adapter, returning a new, valid Epub 3 instance.
2653
- *
2654
- * Performs the following transformations:
2655
- * - upgrades OPF metadata to EPUB 3 conventions
2656
- * - scans XHTML documents and adds manifest item properties
2657
- * - parses the NCX into a TOC tree and generates a nav.xhtml
2658
- * - removes the NCX file and the guide element (configurable)
2659
- * - fixes common font MIME types
2660
- * - bumps the package version to 3.0
2661
- * - goes over each xhtml item and rewrites it using XMLParser to make sure the output is valid XHTML
2662
- *
2663
- * Requires a writable adapter. When {@link Upgrade.Epub2UpgradeOptions.outputPath}
2664
- * is set, the source file is copied to that path on disk first; this
2665
- * only makes sense for adapters whose `source` is a real fs path.
2666
- *
2667
- * @throws when the adapter is read-only
2668
- */
2669
- async upgrade(path, options = {}) {
2670
- var _a;
2671
- if (!this.adapterClass.capabilities.writable) {
2672
- throw new EpubReadOnlyError(
2673
- `adapter ${this.adapterClass.kind} is read-only; cannot upgrade`
2674
- );
2675
- }
2676
- const { removeNcx = false, outputPath } = options;
2677
- if (outputPath) {
2678
- await (0, import_promises.mkdir)((0, import_path.dirname)(outputPath), { recursive: true });
2679
- await (0, import_promises.cp)(path, outputPath, { force: true });
2680
- }
2681
- const source = outputPath ?? path;
2682
- const adapter = await this.adapterClass.init(
2683
- source,
2684
- options
2685
- );
2686
- const epub = new Epub(this.adapterClass, adapter, source);
2687
- try {
2688
- await epub.getPackageElement();
2689
- } catch (e) {
2690
- epub.discardAndClose();
2691
- console.error(e);
2692
- throw new Error(
2693
- "This is not a valid EPUB publication. Could not read the package document."
2694
- );
2695
- }
2696
- const version = await epub.getVersion();
2697
- if (version.startsWith("3.")) {
2698
- return epub;
2699
- }
2700
- const tocEntries = await epub.getNcxTableOfContents();
2701
- let landmarks = [];
2702
- await epub.withPackage((pkg) => {
2703
- landmarks = Upgrade.extractGuideLandmarks(pkg);
2704
- Upgrade.upgradePackageMetadata(pkg);
2705
- Upgrade.fixFontMimeTypes(pkg);
2706
- Upgrade.removeGuide(pkg);
2707
- if (removeNcx) {
2708
- Upgrade.removeSpineTocRef(pkg);
2709
- }
2710
- Upgrade.setPackageVersion(pkg, "3.0");
2711
- });
2712
- await Upgrade.collectManifestProperties(epub);
2713
- if (removeNcx) {
2714
- await Upgrade.removeNcx(epub);
2715
- }
2716
- const navHref = await Upgrade.chooseNavHref(epub);
2717
- const navContent = await Upgrade.buildNavDocument(
2718
- epub,
2719
- tocEntries,
2720
- landmarks
2721
- );
2722
- await epub.addManifestItem(
2723
- {
2724
- id: "nav",
2725
- href: navHref,
2726
- mediaType: "application/xhtml+xml",
2727
- properties: ["nav"]
2728
- },
2729
- navContent,
2730
- "utf-8"
2731
- );
2732
- const manifest = await epub.getManifest();
2733
- for (const item of Object.values(manifest)) {
2734
- if (((_a = item.mediaType) == null ? void 0 : _a.toLowerCase()) !== "application/xhtml+xml") continue;
2735
- const contents = await epub.readXhtmlItemContents(item.id);
2736
- await epub.writeXhtmlItemContents(item.id, contents);
2737
- }
2738
- return epub;
2739
- }
2740
- }
2741
- // Annotate the CommonJS export names for ESM import in node:
2742
- 0 && (module.exports = {
2743
- Epub,
2744
- EpubFactory,
2745
- EpubReadOnlyError,
2746
- EpubVersionError,
2747
- MemoryAdapter,
2748
- TmpFsAdapter
2749
- });