epub-optimizer 0.0.0-stage → 3.16.1
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/LICENSE +21 -0
- package/README.md +1434 -2
- package/dist/src/batch.d.ts +34 -0
- package/dist/src/batch.js +137 -0
- package/dist/src/cli.d.ts +7 -0
- package/dist/src/cli.js +275 -0
- package/dist/src/index.d.ts +23 -0
- package/dist/src/index.js +24 -0
- package/dist/src/optimization.d.ts +7 -0
- package/dist/src/optimization.js +207 -0
- package/dist/src/pipeline.d.ts +2 -0
- package/dist/src/pipeline.js +48 -0
- package/dist/src/processors/archive-processor.d.ts +26 -0
- package/dist/src/processors/archive-processor.js +170 -0
- package/dist/src/processors/epub-processor.d.ts +17 -0
- package/dist/src/processors/epub-processor.js +133 -0
- package/dist/src/processors/font-characters.d.ts +2 -0
- package/dist/src/processors/font-characters.js +227 -0
- package/dist/src/processors/font-engine.d.ts +6 -0
- package/dist/src/processors/font-engine.js +101 -0
- package/dist/src/processors/font-limits.d.ts +3 -0
- package/dist/src/processors/font-limits.js +3 -0
- package/dist/src/processors/font-processor.d.ts +4 -0
- package/dist/src/processors/font-processor.js +121 -0
- package/dist/src/processors/font-runner.d.ts +8 -0
- package/dist/src/processors/font-runner.js +94 -0
- package/dist/src/processors/font-worker.d.ts +1 -0
- package/dist/src/processors/font-worker.js +12 -0
- package/dist/src/processors/html-processor.d.ts +22 -0
- package/dist/src/processors/html-processor.js +190 -0
- package/dist/src/processors/image-converter.d.ts +14 -0
- package/dist/src/processors/image-converter.js +481 -0
- package/dist/src/processors/image-processor.d.ts +24 -0
- package/dist/src/processors/image-processor.js +165 -0
- package/dist/src/processors/js-processor.d.ts +7 -0
- package/dist/src/processors/js-processor.js +59 -0
- package/dist/src/processors/lazy-img.d.ts +5 -0
- package/dist/src/processors/lazy-img.js +48 -0
- package/dist/src/processors/svg-optimizer.d.ts +5 -0
- package/dist/src/processors/svg-optimizer.js +49 -0
- package/dist/src/scripts/create-epub.d.ts +2 -0
- package/dist/src/scripts/create-epub.js +29 -0
- package/dist/src/scripts/fix/fix-span-tags.d.ts +2 -0
- package/dist/src/scripts/fix/fix-span-tags.js +36 -0
- package/dist/src/scripts/fix/fix-xml.d.ts +3 -0
- package/dist/src/scripts/fix/fix-xml.js +59 -0
- package/dist/src/scripts/fix/index.d.ts +5 -0
- package/dist/src/scripts/fix/index.js +20 -0
- package/dist/src/scripts/fix/remove-empty-styles.d.ts +10 -0
- package/dist/src/scripts/fix/remove-empty-styles.js +53 -0
- package/dist/src/scripts/fix/xhtml-files.d.ts +2 -0
- package/dist/src/scripts/fix/xhtml-files.js +34 -0
- package/dist/src/scripts/ops/add-chapter-sections-to-toc.d.ts +5 -0
- package/dist/src/scripts/ops/add-chapter-sections-to-toc.js +242 -0
- package/dist/src/scripts/ops/add-cover-image-property.d.ts +2 -0
- package/dist/src/scripts/ops/add-cover-image-property.js +27 -0
- package/dist/src/scripts/ops/ncx.d.ts +6 -0
- package/dist/src/scripts/ops/ncx.js +19 -0
- package/dist/src/scripts/ops/update-cover-linear.d.ts +11 -0
- package/dist/src/scripts/ops/update-cover-linear.js +45 -0
- package/dist/src/scripts/ops/update-structure.d.ts +5 -0
- package/dist/src/scripts/ops/update-structure.js +22 -0
- package/dist/src/scripts/ops/update-summary-page.d.ts +2 -0
- package/dist/src/scripts/ops/update-summary-page.js +53 -0
- package/dist/src/scripts/ops/update-toc-with-cover.d.ts +2 -0
- package/dist/src/scripts/ops/update-toc-with-cover.js +140 -0
- package/dist/src/scripts/utils.d.ts +53 -0
- package/dist/src/scripts/utils.js +92 -0
- package/dist/src/scripts/validate-epub.d.ts +12 -0
- package/dist/src/scripts/validate-epub.js +185 -0
- package/dist/src/storage.d.ts +30 -0
- package/dist/src/storage.js +286 -0
- package/dist/src/types.d.ts +51 -0
- package/dist/src/types.js +1 -0
- package/dist/src/utils/author-workflow-config.d.ts +17 -0
- package/dist/src/utils/author-workflow-config.js +95 -0
- package/dist/src/utils/buffered-process.d.ts +8 -0
- package/dist/src/utils/buffered-process.js +36 -0
- package/dist/src/utils/cli-config.d.ts +4 -0
- package/dist/src/utils/cli-config.js +84 -0
- package/dist/src/utils/config.d.ts +49 -0
- package/dist/src/utils/config.js +58 -0
- package/dist/src/utils/diagnostics.d.ts +11 -0
- package/dist/src/utils/diagnostics.js +38 -0
- package/dist/src/utils/epub-doctor.d.ts +78 -0
- package/dist/src/utils/epub-doctor.js +301 -0
- package/dist/src/utils/epub-features.d.ts +20 -0
- package/dist/src/utils/epub-features.js +105 -0
- package/dist/src/utils/epub-integrity.d.ts +25 -0
- package/dist/src/utils/epub-integrity.js +197 -0
- package/dist/src/utils/epub-text.d.ts +13 -0
- package/dist/src/utils/epub-text.js +106 -0
- package/dist/src/utils/epub-utils.d.ts +79 -0
- package/dist/src/utils/epub-utils.js +207 -0
- package/dist/src/utils/epubcheck-report.d.ts +35 -0
- package/dist/src/utils/epubcheck-report.js +68 -0
- package/dist/src/utils/file-size.d.ts +13 -0
- package/dist/src/utils/file-size.js +40 -0
- package/dist/src/utils/files.d.ts +14 -0
- package/dist/src/utils/files.js +39 -0
- package/dist/src/utils/html-report.d.ts +17 -0
- package/dist/src/utils/html-report.js +95 -0
- package/dist/src/utils/i18n.d.ts +5 -0
- package/dist/src/utils/i18n.js +9 -0
- package/dist/src/utils/output-transaction.d.ts +8 -0
- package/dist/src/utils/output-transaction.js +146 -0
- package/dist/src/utils/package-root.d.ts +2 -0
- package/dist/src/utils/package-root.js +15 -0
- package/dist/src/utils/path-safety.d.ts +2 -0
- package/dist/src/utils/path-safety.js +30 -0
- package/dist/src/utils/pipeline-options.d.ts +34 -0
- package/dist/src/utils/pipeline-options.js +49 -0
- package/dist/src/utils/png-animation.d.ts +7 -0
- package/dist/src/utils/png-animation.js +44 -0
- package/dist/src/utils/run-report.d.ts +49 -0
- package/dist/src/utils/run-report.js +71 -0
- package/dist/src/utils/temp-dir.d.ts +11 -0
- package/dist/src/utils/temp-dir.js +80 -0
- package/dist/src/utils/watch-lock.d.ts +8 -0
- package/dist/src/utils/watch-lock.js +100 -0
- package/dist/src/utils/watch-summary.d.ts +13 -0
- package/dist/src/utils/watch-summary.js +130 -0
- package/dist/src/utils/xhtml-structure.d.ts +7 -0
- package/dist/src/utils/xhtml-structure.js +53 -0
- package/dist/src/utils/xhtml.d.ts +27 -0
- package/dist/src/utils/xhtml.js +205 -0
- package/dist/src/utils/xml-dtd.d.ts +6 -0
- package/dist/src/utils/xml-dtd.js +133 -0
- package/dist/src/watch.d.ts +21 -0
- package/dist/src/watch.js +328 -0
- package/package.json +99 -3
- package/scripts/install-epubcheck.sh +44 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { reportError, reportInfo, reportWarning, reportWarningToStdout, } from "../../utils/diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import * as cheerio from "cheerio";
|
|
4
|
+
import { getTOCFiles, getContentPath } from "../../utils/epub-utils.js";
|
|
5
|
+
import { getTempDir, isEntryPoint } from "../utils.js";
|
|
6
|
+
import { normalizeNCXNavigation } from "./ncx.js";
|
|
7
|
+
import { DEFAULT_AUTHOR_WORKFLOW_CONFIG, hasAnyClass, resolveAuthorWorkflowHref, } from "../../utils/author-workflow-config.js";
|
|
8
|
+
/**
|
|
9
|
+
* Extracts chapter structure with subsections from the configured manual summary page
|
|
10
|
+
* @param sommaireFilePath Path to the manual summary file
|
|
11
|
+
* @returns Array of chapters with their subsections
|
|
12
|
+
*/
|
|
13
|
+
async function extractChapterStructure(sommaireFilePath, authorConfig) {
|
|
14
|
+
try {
|
|
15
|
+
reportInfo(`Reading manual sommaire from: ${sommaireFilePath}`);
|
|
16
|
+
const content = await fs.readFile(sommaireFilePath, "utf8");
|
|
17
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
18
|
+
const chapters = [];
|
|
19
|
+
let currentChapter = null;
|
|
20
|
+
// Parse all paragraphs in the sommaire
|
|
21
|
+
$("p").each((_, elem) => {
|
|
22
|
+
const $p = $(elem);
|
|
23
|
+
const classes = $p.attr("class") || "";
|
|
24
|
+
const $link = $p.find("a");
|
|
25
|
+
if ($link.length === 0)
|
|
26
|
+
return;
|
|
27
|
+
const href = $link.attr("href") || "";
|
|
28
|
+
const text = $link.text().trim();
|
|
29
|
+
// Class mappings come from the optional author workflow configuration.
|
|
30
|
+
if (hasAnyClass(classes, authorConfig.chapterClasses)) {
|
|
31
|
+
// Save previous chapter if it exists
|
|
32
|
+
if (currentChapter) {
|
|
33
|
+
chapters.push(currentChapter);
|
|
34
|
+
}
|
|
35
|
+
// Start a new chapter
|
|
36
|
+
currentChapter = {
|
|
37
|
+
href,
|
|
38
|
+
text,
|
|
39
|
+
sections: [],
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
else if (hasAnyClass(classes, authorConfig.sectionClasses) && currentChapter) {
|
|
43
|
+
// Add subsection to current chapter
|
|
44
|
+
currentChapter.sections.push({ href, text });
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
// Don't forget to add the last chapter
|
|
48
|
+
if (currentChapter) {
|
|
49
|
+
chapters.push(currentChapter);
|
|
50
|
+
}
|
|
51
|
+
reportInfo(`Found ${chapters.length} chapters with subsections`);
|
|
52
|
+
// Log chapters with sections for debugging
|
|
53
|
+
const chaptersWithSections = chapters.filter((ch) => ch.sections.length > 0);
|
|
54
|
+
reportInfo(`Chapters with subsections: ${chaptersWithSections.map((ch) => `${ch.text} (${ch.sections.length} sections)`).join(", ")}`);
|
|
55
|
+
return chapters;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
59
|
+
reportError(`Failed to extract chapter structure: ${errorMessage}`);
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Finds a chapter's href without fragment
|
|
65
|
+
* @param href Full href with possible fragment
|
|
66
|
+
* @returns Base href without fragment
|
|
67
|
+
*/
|
|
68
|
+
function getBaseHref(href) {
|
|
69
|
+
return href.split("#")[0] ?? "";
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Updates EPUB3 navigation file to include chapter subsections
|
|
73
|
+
* @param navFilePath Path to the EPUB3 navigation file
|
|
74
|
+
* @param chapters Array of chapters with subsections
|
|
75
|
+
*/
|
|
76
|
+
async function updateEPUB3NavigationWithSections(navFilePath, chapters, sectionNavClass) {
|
|
77
|
+
try {
|
|
78
|
+
reportInfo(`Adding chapter subsections to EPUB3 navigation file: ${navFilePath}`);
|
|
79
|
+
const content = await fs.readFile(navFilePath, "utf8");
|
|
80
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
81
|
+
// Process each chapter that has subsections
|
|
82
|
+
for (const chapter of chapters) {
|
|
83
|
+
if (chapter.sections.length === 0)
|
|
84
|
+
continue;
|
|
85
|
+
const baseHref = getBaseHref(chapter.href);
|
|
86
|
+
// Find the existing list item for this chapter
|
|
87
|
+
// Try to match by href first, then by text content
|
|
88
|
+
let $chapterLi = $(`a[href="${baseHref}"]`).parent("li");
|
|
89
|
+
if ($chapterLi.length === 0) {
|
|
90
|
+
// Try to match by text if href match failed
|
|
91
|
+
$chapterLi = $(`li a:contains("${chapter.text.split(" - ")[0]}")`).parent("li");
|
|
92
|
+
}
|
|
93
|
+
if ($chapterLi.length > 0) {
|
|
94
|
+
// Check if subsections already exist
|
|
95
|
+
const existingOl = $chapterLi.find("> ol");
|
|
96
|
+
if (existingOl.length === 0) {
|
|
97
|
+
// Create a new nested <ol> for subsections
|
|
98
|
+
const $nestedOl = $("<ol></ol>");
|
|
99
|
+
for (const section of chapter.sections) {
|
|
100
|
+
const $sectionLi = $(`<li class="${sectionNavClass}"></li>`);
|
|
101
|
+
const $sectionLink = $(`<a href="${section.href}" class="${sectionNavClass}">${section.text}</a>`);
|
|
102
|
+
$sectionLi.append($sectionLink);
|
|
103
|
+
$nestedOl.append($sectionLi);
|
|
104
|
+
}
|
|
105
|
+
$chapterLi.append($nestedOl);
|
|
106
|
+
reportInfo(`Added ${chapter.sections.length} subsections to: ${chapter.text}`);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
reportInfo(`Subsections already exist for: ${chapter.text}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
reportWarningToStdout(`Warning: Could not find chapter in TOC: ${chapter.text}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// Save the updated TOC
|
|
117
|
+
await fs.writeFile(navFilePath, $.xml());
|
|
118
|
+
reportInfo("Successfully updated EPUB3 navigation file with chapter subsections");
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
122
|
+
reportWarning(`Failed to update EPUB3 navigation file: ${errorMessage}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Updates EPUB2 NCX file to include chapter subsections
|
|
127
|
+
* @param ncxFilePath Path to the EPUB2 NCX file
|
|
128
|
+
* @param chapters Array of chapters with subsections
|
|
129
|
+
*/
|
|
130
|
+
async function updateEPUB2NCXWithSections(ncxFilePath, chapters) {
|
|
131
|
+
try {
|
|
132
|
+
reportInfo(`Adding chapter subsections to EPUB2 NCX file: ${ncxFilePath}`);
|
|
133
|
+
const content = await fs.readFile(ncxFilePath, "utf8");
|
|
134
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
135
|
+
let globalPlayOrder = 1;
|
|
136
|
+
// First, find the highest playOrder to know where to start
|
|
137
|
+
$("navPoint").each((_, el) => {
|
|
138
|
+
const playOrder = parseInt($(el).attr("playOrder") || "1");
|
|
139
|
+
if (playOrder > globalPlayOrder) {
|
|
140
|
+
globalPlayOrder = playOrder;
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
// Process each chapter that has subsections
|
|
144
|
+
for (const chapter of chapters) {
|
|
145
|
+
if (chapter.sections.length === 0)
|
|
146
|
+
continue;
|
|
147
|
+
const baseHref = getBaseHref(chapter.href);
|
|
148
|
+
// Find the navPoint for this chapter
|
|
149
|
+
let $chapterNavPoint = $(`navPoint content[src="${baseHref}"]`).parent();
|
|
150
|
+
if ($chapterNavPoint.length === 0) {
|
|
151
|
+
// Try to match by chapter title in text
|
|
152
|
+
const chapterTitle = chapter.text.split(" - ")[0]?.trim() ?? "";
|
|
153
|
+
const matchedText = $(`navPoint navLabel text:contains("${chapterTitle}")`);
|
|
154
|
+
$chapterNavPoint = matchedText.parent().parent();
|
|
155
|
+
}
|
|
156
|
+
if ($chapterNavPoint.length > 0) {
|
|
157
|
+
// Check if subsections already exist
|
|
158
|
+
const existingSubNavPoints = $chapterNavPoint.find("> navPoint");
|
|
159
|
+
if (existingSubNavPoints.length === 0) {
|
|
160
|
+
// Add subsections as nested navPoints
|
|
161
|
+
for (const [i, section] of chapter.sections.entries()) {
|
|
162
|
+
globalPlayOrder++;
|
|
163
|
+
const navPointId = `${$chapterNavPoint.attr("id")}-section-${i + 1}`;
|
|
164
|
+
const sectionNavPoint = $(`
|
|
165
|
+
<navPoint id="${navPointId}" playOrder="${globalPlayOrder}">
|
|
166
|
+
<navLabel>
|
|
167
|
+
<text>${section.text}</text>
|
|
168
|
+
</navLabel>
|
|
169
|
+
<content src="${section.href}"/>
|
|
170
|
+
</navPoint>
|
|
171
|
+
`);
|
|
172
|
+
$chapterNavPoint.append(sectionNavPoint);
|
|
173
|
+
}
|
|
174
|
+
reportInfo(`Added ${chapter.sections.length} subsections to NCX: ${chapter.text}`);
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
reportInfo(`Subsections already exist in NCX for: ${chapter.text}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
reportWarningToStdout(`Warning: Could not find chapter in NCX: ${chapter.text}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
normalizeNCXNavigation($);
|
|
185
|
+
// Save the updated NCX
|
|
186
|
+
await fs.writeFile(ncxFilePath, $.xml());
|
|
187
|
+
reportInfo("Successfully updated EPUB2 NCX file with chapter subsections");
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
191
|
+
reportWarning(`Failed to update EPUB2 NCX file: ${errorMessage}`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Main function to add chapter sections to TOC files
|
|
196
|
+
*/
|
|
197
|
+
export async function run(opts = {}) {
|
|
198
|
+
const extractedDir = opts.tempDir ?? getTempDir();
|
|
199
|
+
const authorConfig = opts.authorConfig ?? DEFAULT_AUTHOR_WORKFLOW_CONFIG;
|
|
200
|
+
reportInfo("Discovering TOC files and content directory...");
|
|
201
|
+
const contentPath = await getContentPath(extractedDir);
|
|
202
|
+
const tocFiles = await getTOCFiles(extractedDir);
|
|
203
|
+
if (!tocFiles.epub3Nav && !tocFiles.epub2Ncx) {
|
|
204
|
+
reportInfo("No TOC files found. Skipping chapter section updates.");
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const sommaireFilePath = resolveAuthorWorkflowHref(contentPath, authorConfig.summaryHref, "author summary href");
|
|
208
|
+
if (!(await fs.pathExists(sommaireFilePath))) {
|
|
209
|
+
reportInfo(`Manual sommaire file not found at: ${sommaireFilePath}`);
|
|
210
|
+
reportInfo("Skipping chapter section updates.");
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const chapters = await extractChapterStructure(sommaireFilePath, authorConfig);
|
|
214
|
+
if (chapters.length === 0) {
|
|
215
|
+
reportInfo("No chapters found in manual sommaire. Skipping updates.");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const chaptersWithSections = chapters.filter((ch) => ch.sections.length > 0);
|
|
219
|
+
if (chaptersWithSections.length === 0) {
|
|
220
|
+
reportInfo("No chapters with subsections found. Skipping updates.");
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (tocFiles.epub3Nav) {
|
|
224
|
+
await updateEPUB3NavigationWithSections(tocFiles.epub3Nav, chaptersWithSections, authorConfig.sectionNavClass);
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
reportInfo("No EPUB3 navigation file found");
|
|
228
|
+
}
|
|
229
|
+
if (tocFiles.epub2Ncx) {
|
|
230
|
+
await updateEPUB2NCXWithSections(tocFiles.epub2Ncx, chaptersWithSections);
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
reportInfo("No EPUB2 NCX file found");
|
|
234
|
+
}
|
|
235
|
+
reportInfo("Chapter section updates completed successfully");
|
|
236
|
+
}
|
|
237
|
+
if (isEntryPoint(import.meta.url)) {
|
|
238
|
+
run().catch((err) => {
|
|
239
|
+
reportError(err);
|
|
240
|
+
process.exit(1);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { reportError, reportInfo, reportWarningToStdout } from "../../utils/diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import * as cheerio from "cheerio";
|
|
4
|
+
import { getOPFPath } from "../../utils/epub-utils.js";
|
|
5
|
+
import { getTempDir, isEntryPoint } from "../utils.js";
|
|
6
|
+
export async function run(opts = {}) {
|
|
7
|
+
const extractedDir = opts.tempDir ?? getTempDir();
|
|
8
|
+
const opfFile = await getOPFPath(extractedDir);
|
|
9
|
+
reportInfo(`Adding properties="cover-image" to cover-image item in: ${opfFile}`);
|
|
10
|
+
const content = fs.readFileSync(opfFile, "utf8");
|
|
11
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
12
|
+
const coverImageItem = $('item[id="cover-image"]');
|
|
13
|
+
if (coverImageItem.length) {
|
|
14
|
+
coverImageItem.attr("properties", "cover-image");
|
|
15
|
+
fs.writeFileSync(opfFile, $.xml());
|
|
16
|
+
reportInfo('Added properties="cover-image" to cover image');
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
reportWarningToStdout("Warning: Could not find cover-image item in OPF");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (isEntryPoint(import.meta.url)) {
|
|
23
|
+
run().catch((err) => {
|
|
24
|
+
reportError(err);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CheerioAPI } from "cheerio";
|
|
2
|
+
/**
|
|
3
|
+
* Keep NCX navigation metadata consistent with the actual depth-first document
|
|
4
|
+
* order. Kindle relies on monotonically increasing playOrder values.
|
|
5
|
+
*/
|
|
6
|
+
export declare function normalizeNCXNavigation($: CheerioAPI): void;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep NCX navigation metadata consistent with the actual depth-first document
|
|
3
|
+
* order. Kindle relies on monotonically increasing playOrder values.
|
|
4
|
+
*/
|
|
5
|
+
export function normalizeNCXNavigation($) {
|
|
6
|
+
let maxDepth = 0;
|
|
7
|
+
$("navMap navPoint").each((index, element) => {
|
|
8
|
+
$(element).attr("playOrder", String(index + 1));
|
|
9
|
+
maxDepth = Math.max(maxDepth, $(element).parents("navPoint").length + 1);
|
|
10
|
+
});
|
|
11
|
+
const depth = String(maxDepth);
|
|
12
|
+
const depthMeta = $('meta[name="dtb:depth"]');
|
|
13
|
+
if (depthMeta.length > 0) {
|
|
14
|
+
depthMeta.attr("content", depth);
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
$("head").append(`<meta name="dtb:depth" content="${depth}"/>`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type RunOpts } from "../utils.js";
|
|
2
|
+
/**
|
|
3
|
+
* Mark the cover item in an OPF manifest's spine as `linear="yes"` so readers
|
|
4
|
+
* render it first. Returns the updated XML and whether a change was made.
|
|
5
|
+
* Pure function — no I/O.
|
|
6
|
+
*/
|
|
7
|
+
export declare function setCoverLinear(opfXml: string, coverSpineId?: string): {
|
|
8
|
+
xml: string;
|
|
9
|
+
updated: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare function run(opts?: RunOpts): Promise<void>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { reportError, reportInfo, reportWarningToStdout } from "../../utils/diagnostics.js";
|
|
2
|
+
// Sets the cover image as linear in the OPF file
|
|
3
|
+
// When linear="yes", the cover will be displayed in the reading order (on the first page)
|
|
4
|
+
import fs from "fs-extra";
|
|
5
|
+
import * as cheerio from "cheerio";
|
|
6
|
+
import { getOPFPath } from "../../utils/epub-utils.js";
|
|
7
|
+
import { getTempDir, isEntryPoint } from "../utils.js";
|
|
8
|
+
import { DEFAULT_AUTHOR_WORKFLOW_CONFIG } from "../../utils/author-workflow-config.js";
|
|
9
|
+
/**
|
|
10
|
+
* Mark the cover item in an OPF manifest's spine as `linear="yes"` so readers
|
|
11
|
+
* render it first. Returns the updated XML and whether a change was made.
|
|
12
|
+
* Pure function — no I/O.
|
|
13
|
+
*/
|
|
14
|
+
export function setCoverLinear(opfXml, coverSpineId = DEFAULT_AUTHOR_WORKFLOW_CONFIG.coverSpineId) {
|
|
15
|
+
const $ = cheerio.load(opfXml, { xmlMode: true });
|
|
16
|
+
const coverRef = $("spine itemref")
|
|
17
|
+
.filter((_, element) => $(element).attr("idref") === coverSpineId)
|
|
18
|
+
.first();
|
|
19
|
+
if (!coverRef.length) {
|
|
20
|
+
return { xml: opfXml, updated: false };
|
|
21
|
+
}
|
|
22
|
+
coverRef.attr("linear", "yes");
|
|
23
|
+
return { xml: $.xml(), updated: true };
|
|
24
|
+
}
|
|
25
|
+
export async function run(opts = {}) {
|
|
26
|
+
const extractedDir = opts.tempDir ?? getTempDir();
|
|
27
|
+
const opfFile = await getOPFPath(extractedDir);
|
|
28
|
+
reportInfo(`Updating cover in OPF file: ${opfFile}`);
|
|
29
|
+
const content = fs.readFileSync(opfFile, "utf8");
|
|
30
|
+
const coverSpineId = opts.authorConfig?.coverSpineId ?? DEFAULT_AUTHOR_WORKFLOW_CONFIG.coverSpineId;
|
|
31
|
+
const { xml, updated } = setCoverLinear(content, coverSpineId);
|
|
32
|
+
if (updated) {
|
|
33
|
+
fs.writeFileSync(opfFile, xml);
|
|
34
|
+
reportInfo(`Successfully set cover spine item "${coverSpineId}" to linear="yes"`);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
reportWarningToStdout("Warning: No cover reference found in spine section of OPF file");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (isEntryPoint(import.meta.url)) {
|
|
41
|
+
run().catch((err) => {
|
|
42
|
+
reportError(err);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { reportError, reportInfo } from "../../utils/diagnostics.js";
|
|
2
|
+
import { isEntryPoint } from "../utils.js";
|
|
3
|
+
import { run as updateCoverLinear } from "./update-cover-linear.js";
|
|
4
|
+
import { run as updateTocWithCover } from "./update-toc-with-cover.js";
|
|
5
|
+
import { run as updateSummaryPage } from "./update-summary-page.js";
|
|
6
|
+
import { run as addChapterSectionsToToc } from "./add-chapter-sections-to-toc.js";
|
|
7
|
+
/**
|
|
8
|
+
* Apply all EPUB structure updates in sequence, in-process.
|
|
9
|
+
*/
|
|
10
|
+
export async function runStructureUpdates(opts = {}) {
|
|
11
|
+
await updateCoverLinear(opts);
|
|
12
|
+
await updateTocWithCover(opts);
|
|
13
|
+
await updateSummaryPage(opts);
|
|
14
|
+
await addChapterSectionsToToc(opts);
|
|
15
|
+
reportInfo("All structure updates completed.");
|
|
16
|
+
}
|
|
17
|
+
if (isEntryPoint(import.meta.url)) {
|
|
18
|
+
runStructureUpdates().catch((err) => {
|
|
19
|
+
reportError(err);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { reportError, reportInfo, reportWarningToStdout } from "../../utils/diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import * as cheerio from "cheerio";
|
|
4
|
+
import { getCoverLabel } from "../../utils/i18n.js";
|
|
5
|
+
import { getContentPath } from "../../utils/epub-utils.js";
|
|
6
|
+
import { getLang, getTempDir, isEntryPoint } from "../utils.js";
|
|
7
|
+
import { createOwnerRelativeHref, DEFAULT_AUTHOR_WORKFLOW_CONFIG, hasAnyClass, referenceTargetsFile, resolveAuthorWorkflowHref, } from "../../utils/author-workflow-config.js";
|
|
8
|
+
export async function run(opts = {}) {
|
|
9
|
+
const extractedDir = opts.tempDir ?? getTempDir();
|
|
10
|
+
const coverLabel = getCoverLabel(opts.lang ?? getLang());
|
|
11
|
+
const authorConfig = opts.authorConfig ?? DEFAULT_AUTHOR_WORKFLOW_CONFIG;
|
|
12
|
+
const contentDir = await getContentPath(extractedDir);
|
|
13
|
+
const summaryFile = resolveAuthorWorkflowHref(contentDir, authorConfig.summaryHref, "author summary href");
|
|
14
|
+
const coverFile = resolveAuthorWorkflowHref(contentDir, authorConfig.coverHref, "author cover href");
|
|
15
|
+
if (!fs.existsSync(summaryFile)) {
|
|
16
|
+
reportInfo(`Summary file not found at ${summaryFile}, skipping summary update`);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
reportInfo(`Updating summary page: ${summaryFile}`);
|
|
20
|
+
const content = fs.readFileSync(summaryFile, "utf8");
|
|
21
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
22
|
+
// Remove the 'Sommaire' self-reference
|
|
23
|
+
$("a[href]")
|
|
24
|
+
.filter((_, element) => referenceTargetsFile(extractedDir, summaryFile, $(element).attr("href"), summaryFile))
|
|
25
|
+
.parent()
|
|
26
|
+
.remove();
|
|
27
|
+
const existingCoverLink = $("a[href]").filter((_, element) => referenceTargetsFile(extractedDir, summaryFile, $(element).attr("href"), coverFile));
|
|
28
|
+
if (existingCoverLink.length === 0) {
|
|
29
|
+
const firstLink = $("p")
|
|
30
|
+
.filter((_, element) => hasAnyClass($(element).attr("class"), [authorConfig.summaryEntryClass]))
|
|
31
|
+
.first();
|
|
32
|
+
if (firstLink.length) {
|
|
33
|
+
const coverParagraph = $(`<p class="${authorConfig.summaryEntryClass}" style=""></p>`);
|
|
34
|
+
coverParagraph.append($(`<a href="${createOwnerRelativeHref(summaryFile, coverFile)}">${coverLabel}</a>`));
|
|
35
|
+
firstLink.before(coverParagraph);
|
|
36
|
+
reportInfo("Successfully added cover to summary page");
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
reportWarningToStdout("Warning: Could not find link paragraphs in summary page");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
reportInfo("Cover is already in the summary page");
|
|
44
|
+
}
|
|
45
|
+
fs.writeFileSync(summaryFile, $.xml());
|
|
46
|
+
reportInfo("Summary page updated successfully");
|
|
47
|
+
}
|
|
48
|
+
if (isEntryPoint(import.meta.url)) {
|
|
49
|
+
run().catch((err) => {
|
|
50
|
+
reportError(err);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { reportError, reportInfo, reportWarning, reportWarningToStdout, } from "../../utils/diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import * as cheerio from "cheerio";
|
|
4
|
+
import { getCoverLabel } from "../../utils/i18n.js";
|
|
5
|
+
import { getContentPath, getTOCFiles } from "../../utils/epub-utils.js";
|
|
6
|
+
import { getLang, getTempDir, isEntryPoint } from "../utils.js";
|
|
7
|
+
import { normalizeNCXNavigation } from "./ncx.js";
|
|
8
|
+
import { createOwnerRelativeHref, DEFAULT_AUTHOR_WORKFLOW_CONFIG, referenceTargetsFile, resolveAuthorWorkflowHref, } from "../../utils/author-workflow-config.js";
|
|
9
|
+
/**
|
|
10
|
+
* Updates EPUB3 navigation file to include cover link
|
|
11
|
+
* @param navFilePath Path to the EPUB3 navigation file
|
|
12
|
+
* @param coverLabel Localized cover label
|
|
13
|
+
*/
|
|
14
|
+
async function updateEPUB3Navigation(epubDir, navFilePath, coverFile, coverLabel, authorConfig) {
|
|
15
|
+
try {
|
|
16
|
+
reportInfo(`Adding cover to EPUB3 navigation file: ${navFilePath}`);
|
|
17
|
+
const content = await fs.readFile(navFilePath, "utf8");
|
|
18
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
19
|
+
// Check if cover is already in the TOC
|
|
20
|
+
const coverLink = $("a[href]").filter((_, element) => referenceTargetsFile(epubDir, navFilePath, $(element).attr("href"), coverFile));
|
|
21
|
+
if (coverLink.length === 0) {
|
|
22
|
+
// css-select cannot evaluate namespace-wildcard attributes. Inspect
|
|
23
|
+
// attribute names explicitly so alternate prefixes and fallbacks work.
|
|
24
|
+
const tocLists = [
|
|
25
|
+
$('nav[epub\\:type="toc"] > ol'),
|
|
26
|
+
$("nav")
|
|
27
|
+
.filter((_, element) => Object.entries(element.attribs).some(([name, value]) => (name === "type" || name.endsWith(":type")) && value.split(/\s+/).includes("toc")))
|
|
28
|
+
.children("ol"),
|
|
29
|
+
$('nav[role="doc-toc"] > ol'),
|
|
30
|
+
$("nav > ol"),
|
|
31
|
+
$("ol"),
|
|
32
|
+
];
|
|
33
|
+
let olElement = $();
|
|
34
|
+
for (const list of tocLists) {
|
|
35
|
+
olElement = list.first();
|
|
36
|
+
if (olElement.length)
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
if (olElement.length) {
|
|
40
|
+
// Create new list item with cover link
|
|
41
|
+
const coverItem = $(`<li class="${authorConfig.coverNavClass}"></li>`);
|
|
42
|
+
const anchorElement = $(`<a href="${createOwnerRelativeHref(navFilePath, coverFile)}" class="${authorConfig.coverNavClass}">${coverLabel}</a>`);
|
|
43
|
+
coverItem.append(anchorElement);
|
|
44
|
+
// Add it as the first item
|
|
45
|
+
olElement.prepend(coverItem);
|
|
46
|
+
// Save the updated TOC
|
|
47
|
+
await fs.writeFile(navFilePath, $.xml());
|
|
48
|
+
reportInfo("Successfully added cover to EPUB3 navigation file");
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
reportWarningToStdout("Warning: Could not find TOC list in EPUB3 navigation file");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
reportInfo("Cover is already in EPUB3 navigation file");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
60
|
+
reportWarning(`Failed to update EPUB3 navigation file: ${errorMessage}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Updates EPUB2 NCX file to include cover navigation point
|
|
65
|
+
* @param ncxFilePath Path to the EPUB2 NCX file
|
|
66
|
+
* @param coverLabel Localized cover label
|
|
67
|
+
*/
|
|
68
|
+
async function updateEPUB2NCX(epubDir, ncxFilePath, coverFile, coverLabel, authorConfig) {
|
|
69
|
+
try {
|
|
70
|
+
reportInfo(`Adding cover to EPUB2 NCX file: ${ncxFilePath}`);
|
|
71
|
+
const content = await fs.readFile(ncxFilePath, "utf8");
|
|
72
|
+
const $ = cheerio.load(content, { xmlMode: true });
|
|
73
|
+
// Check if cover is already in the NCX navMap
|
|
74
|
+
const coverNavPoint = $("navPoint")
|
|
75
|
+
.filter((_, element) => referenceTargetsFile(epubDir, ncxFilePath, $(element).find("> content").attr("src"), coverFile))
|
|
76
|
+
.first();
|
|
77
|
+
if (coverNavPoint.length === 0) {
|
|
78
|
+
const navMap = $("navMap");
|
|
79
|
+
if (navMap.length) {
|
|
80
|
+
// Create a new navPoint for the cover
|
|
81
|
+
const coverNavPoint = $(`
|
|
82
|
+
<navPoint id="navpoint-${authorConfig.coverSpineId}" playOrder="1">
|
|
83
|
+
<navLabel>
|
|
84
|
+
<text>${coverLabel}</text>
|
|
85
|
+
</navLabel>
|
|
86
|
+
<content src="${createOwnerRelativeHref(ncxFilePath, coverFile)}"/>
|
|
87
|
+
</navPoint>
|
|
88
|
+
`);
|
|
89
|
+
// Add it as the first navPoint
|
|
90
|
+
navMap.prepend(coverNavPoint);
|
|
91
|
+
normalizeNCXNavigation($);
|
|
92
|
+
// Save the updated NCX
|
|
93
|
+
await fs.writeFile(ncxFilePath, $.xml());
|
|
94
|
+
reportInfo("Successfully added cover to EPUB2 NCX file");
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
reportWarningToStdout("Warning: Could not find navMap in EPUB2 NCX file");
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
reportInfo("Cover is already in EPUB2 NCX file");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
106
|
+
reportWarning(`Failed to update EPUB2 NCX file: ${errorMessage}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export async function run(opts = {}) {
|
|
110
|
+
const extractedDir = opts.tempDir ?? getTempDir();
|
|
111
|
+
const coverLabel = getCoverLabel(opts.lang ?? getLang());
|
|
112
|
+
const authorConfig = opts.authorConfig ?? DEFAULT_AUTHOR_WORKFLOW_CONFIG;
|
|
113
|
+
reportInfo("Discovering TOC files from OPF manifest...");
|
|
114
|
+
const tocFiles = await getTOCFiles(extractedDir);
|
|
115
|
+
const contentDir = await getContentPath(extractedDir);
|
|
116
|
+
const coverFile = resolveAuthorWorkflowHref(contentDir, authorConfig.coverHref, "author cover href");
|
|
117
|
+
if (!tocFiles.epub3Nav && !tocFiles.epub2Ncx) {
|
|
118
|
+
reportInfo("No TOC files found in OPF manifest. Skipping TOC updates.");
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (tocFiles.epub3Nav) {
|
|
122
|
+
await updateEPUB3Navigation(extractedDir, tocFiles.epub3Nav, coverFile, coverLabel, authorConfig);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
reportInfo("No EPUB3 navigation file found");
|
|
126
|
+
}
|
|
127
|
+
if (tocFiles.epub2Ncx) {
|
|
128
|
+
await updateEPUB2NCX(extractedDir, tocFiles.epub2Ncx, coverFile, coverLabel, authorConfig);
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
reportInfo("No EPUB2 NCX file found");
|
|
132
|
+
}
|
|
133
|
+
reportInfo("TOC updates completed successfully");
|
|
134
|
+
}
|
|
135
|
+
if (isEntryPoint(import.meta.url)) {
|
|
136
|
+
run().catch((err) => {
|
|
137
|
+
reportError(err);
|
|
138
|
+
process.exit(1);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { AuthorWorkflowConfig } from "../utils/author-workflow-config.js";
|
|
2
|
+
/**
|
|
3
|
+
* Returns true when a module is being executed directly (e.g.
|
|
4
|
+
* `node dist/src/scripts/fix/fix-xml.js`) rather than imported by another
|
|
5
|
+
* module. Callers should pass `import.meta.url`. We realpath both sides so
|
|
6
|
+
* symlinks, pnpm `.bin` shims, and relative invocations all line up.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isEntryPoint(metaUrl: string): boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Options passed when running a script programmatically (in-process, via
|
|
11
|
+
* `run(opts)`). When invoked as a standalone CLI the script falls back to
|
|
12
|
+
* reading the same values from argv / config.
|
|
13
|
+
*/
|
|
14
|
+
export interface RunOpts {
|
|
15
|
+
/** Absolute path to the extracted EPUB directory. */
|
|
16
|
+
tempDir?: string;
|
|
17
|
+
/** UI language code (e.g. "fr", "en"). */
|
|
18
|
+
lang?: string;
|
|
19
|
+
/** Output EPUB path (for create-epub / validate-epub). */
|
|
20
|
+
output?: string;
|
|
21
|
+
/** Fail instead of continuing after warnings or recoverable processing errors. */
|
|
22
|
+
strict?: boolean;
|
|
23
|
+
/** Maximum EPUBCheck runtime in milliseconds. */
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
/** Resolved optional configuration for the project-author structure updates. */
|
|
26
|
+
authorConfig?: AuthorWorkflowConfig;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Defines the shape of args returned by parseArgs
|
|
30
|
+
*/
|
|
31
|
+
export interface CommandArgs {
|
|
32
|
+
input?: string;
|
|
33
|
+
output?: string;
|
|
34
|
+
[key: string]: unknown;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Parse command line arguments consistently across all scripts
|
|
38
|
+
* @param includeInputOption Whether to include input option
|
|
39
|
+
* @param includeOutputOption Whether to include output option
|
|
40
|
+
* @returns Parsed args object
|
|
41
|
+
*/
|
|
42
|
+
export declare function parseArgs(includeInputOption?: boolean, includeOutputOption?: boolean): CommandArgs;
|
|
43
|
+
/**
|
|
44
|
+
* Get the UI language from CLI args or config.
|
|
45
|
+
* Reads --lang, falls back to config.lang.
|
|
46
|
+
*/
|
|
47
|
+
export declare function getLang(): string;
|
|
48
|
+
/**
|
|
49
|
+
* Get the temp directory from CLI args or config
|
|
50
|
+
* Reads the --temp or -t argument, falls back to config.tempDir
|
|
51
|
+
* @returns Absolute path to temp directory
|
|
52
|
+
*/
|
|
53
|
+
export declare function getTempDir(): string;
|