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.
Files changed (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1434 -2
  3. package/dist/src/batch.d.ts +34 -0
  4. package/dist/src/batch.js +137 -0
  5. package/dist/src/cli.d.ts +7 -0
  6. package/dist/src/cli.js +275 -0
  7. package/dist/src/index.d.ts +23 -0
  8. package/dist/src/index.js +24 -0
  9. package/dist/src/optimization.d.ts +7 -0
  10. package/dist/src/optimization.js +207 -0
  11. package/dist/src/pipeline.d.ts +2 -0
  12. package/dist/src/pipeline.js +48 -0
  13. package/dist/src/processors/archive-processor.d.ts +26 -0
  14. package/dist/src/processors/archive-processor.js +170 -0
  15. package/dist/src/processors/epub-processor.d.ts +17 -0
  16. package/dist/src/processors/epub-processor.js +133 -0
  17. package/dist/src/processors/font-characters.d.ts +2 -0
  18. package/dist/src/processors/font-characters.js +227 -0
  19. package/dist/src/processors/font-engine.d.ts +6 -0
  20. package/dist/src/processors/font-engine.js +101 -0
  21. package/dist/src/processors/font-limits.d.ts +3 -0
  22. package/dist/src/processors/font-limits.js +3 -0
  23. package/dist/src/processors/font-processor.d.ts +4 -0
  24. package/dist/src/processors/font-processor.js +121 -0
  25. package/dist/src/processors/font-runner.d.ts +8 -0
  26. package/dist/src/processors/font-runner.js +94 -0
  27. package/dist/src/processors/font-worker.d.ts +1 -0
  28. package/dist/src/processors/font-worker.js +12 -0
  29. package/dist/src/processors/html-processor.d.ts +22 -0
  30. package/dist/src/processors/html-processor.js +190 -0
  31. package/dist/src/processors/image-converter.d.ts +14 -0
  32. package/dist/src/processors/image-converter.js +481 -0
  33. package/dist/src/processors/image-processor.d.ts +24 -0
  34. package/dist/src/processors/image-processor.js +165 -0
  35. package/dist/src/processors/js-processor.d.ts +7 -0
  36. package/dist/src/processors/js-processor.js +59 -0
  37. package/dist/src/processors/lazy-img.d.ts +5 -0
  38. package/dist/src/processors/lazy-img.js +48 -0
  39. package/dist/src/processors/svg-optimizer.d.ts +5 -0
  40. package/dist/src/processors/svg-optimizer.js +49 -0
  41. package/dist/src/scripts/create-epub.d.ts +2 -0
  42. package/dist/src/scripts/create-epub.js +29 -0
  43. package/dist/src/scripts/fix/fix-span-tags.d.ts +2 -0
  44. package/dist/src/scripts/fix/fix-span-tags.js +36 -0
  45. package/dist/src/scripts/fix/fix-xml.d.ts +3 -0
  46. package/dist/src/scripts/fix/fix-xml.js +59 -0
  47. package/dist/src/scripts/fix/index.d.ts +5 -0
  48. package/dist/src/scripts/fix/index.js +20 -0
  49. package/dist/src/scripts/fix/remove-empty-styles.d.ts +10 -0
  50. package/dist/src/scripts/fix/remove-empty-styles.js +53 -0
  51. package/dist/src/scripts/fix/xhtml-files.d.ts +2 -0
  52. package/dist/src/scripts/fix/xhtml-files.js +34 -0
  53. package/dist/src/scripts/ops/add-chapter-sections-to-toc.d.ts +5 -0
  54. package/dist/src/scripts/ops/add-chapter-sections-to-toc.js +242 -0
  55. package/dist/src/scripts/ops/add-cover-image-property.d.ts +2 -0
  56. package/dist/src/scripts/ops/add-cover-image-property.js +27 -0
  57. package/dist/src/scripts/ops/ncx.d.ts +6 -0
  58. package/dist/src/scripts/ops/ncx.js +19 -0
  59. package/dist/src/scripts/ops/update-cover-linear.d.ts +11 -0
  60. package/dist/src/scripts/ops/update-cover-linear.js +45 -0
  61. package/dist/src/scripts/ops/update-structure.d.ts +5 -0
  62. package/dist/src/scripts/ops/update-structure.js +22 -0
  63. package/dist/src/scripts/ops/update-summary-page.d.ts +2 -0
  64. package/dist/src/scripts/ops/update-summary-page.js +53 -0
  65. package/dist/src/scripts/ops/update-toc-with-cover.d.ts +2 -0
  66. package/dist/src/scripts/ops/update-toc-with-cover.js +140 -0
  67. package/dist/src/scripts/utils.d.ts +53 -0
  68. package/dist/src/scripts/utils.js +92 -0
  69. package/dist/src/scripts/validate-epub.d.ts +12 -0
  70. package/dist/src/scripts/validate-epub.js +185 -0
  71. package/dist/src/storage.d.ts +30 -0
  72. package/dist/src/storage.js +286 -0
  73. package/dist/src/types.d.ts +51 -0
  74. package/dist/src/types.js +1 -0
  75. package/dist/src/utils/author-workflow-config.d.ts +17 -0
  76. package/dist/src/utils/author-workflow-config.js +95 -0
  77. package/dist/src/utils/buffered-process.d.ts +8 -0
  78. package/dist/src/utils/buffered-process.js +36 -0
  79. package/dist/src/utils/cli-config.d.ts +4 -0
  80. package/dist/src/utils/cli-config.js +84 -0
  81. package/dist/src/utils/config.d.ts +49 -0
  82. package/dist/src/utils/config.js +58 -0
  83. package/dist/src/utils/diagnostics.d.ts +11 -0
  84. package/dist/src/utils/diagnostics.js +38 -0
  85. package/dist/src/utils/epub-doctor.d.ts +78 -0
  86. package/dist/src/utils/epub-doctor.js +301 -0
  87. package/dist/src/utils/epub-features.d.ts +20 -0
  88. package/dist/src/utils/epub-features.js +105 -0
  89. package/dist/src/utils/epub-integrity.d.ts +25 -0
  90. package/dist/src/utils/epub-integrity.js +197 -0
  91. package/dist/src/utils/epub-text.d.ts +13 -0
  92. package/dist/src/utils/epub-text.js +106 -0
  93. package/dist/src/utils/epub-utils.d.ts +79 -0
  94. package/dist/src/utils/epub-utils.js +207 -0
  95. package/dist/src/utils/epubcheck-report.d.ts +35 -0
  96. package/dist/src/utils/epubcheck-report.js +68 -0
  97. package/dist/src/utils/file-size.d.ts +13 -0
  98. package/dist/src/utils/file-size.js +40 -0
  99. package/dist/src/utils/files.d.ts +14 -0
  100. package/dist/src/utils/files.js +39 -0
  101. package/dist/src/utils/html-report.d.ts +17 -0
  102. package/dist/src/utils/html-report.js +95 -0
  103. package/dist/src/utils/i18n.d.ts +5 -0
  104. package/dist/src/utils/i18n.js +9 -0
  105. package/dist/src/utils/output-transaction.d.ts +8 -0
  106. package/dist/src/utils/output-transaction.js +146 -0
  107. package/dist/src/utils/package-root.d.ts +2 -0
  108. package/dist/src/utils/package-root.js +15 -0
  109. package/dist/src/utils/path-safety.d.ts +2 -0
  110. package/dist/src/utils/path-safety.js +30 -0
  111. package/dist/src/utils/pipeline-options.d.ts +34 -0
  112. package/dist/src/utils/pipeline-options.js +49 -0
  113. package/dist/src/utils/png-animation.d.ts +7 -0
  114. package/dist/src/utils/png-animation.js +44 -0
  115. package/dist/src/utils/run-report.d.ts +49 -0
  116. package/dist/src/utils/run-report.js +71 -0
  117. package/dist/src/utils/temp-dir.d.ts +11 -0
  118. package/dist/src/utils/temp-dir.js +80 -0
  119. package/dist/src/utils/watch-lock.d.ts +8 -0
  120. package/dist/src/utils/watch-lock.js +100 -0
  121. package/dist/src/utils/watch-summary.d.ts +13 -0
  122. package/dist/src/utils/watch-summary.js +130 -0
  123. package/dist/src/utils/xhtml-structure.d.ts +7 -0
  124. package/dist/src/utils/xhtml-structure.js +53 -0
  125. package/dist/src/utils/xhtml.d.ts +27 -0
  126. package/dist/src/utils/xhtml.js +205 -0
  127. package/dist/src/utils/xml-dtd.d.ts +6 -0
  128. package/dist/src/utils/xml-dtd.js +133 -0
  129. package/dist/src/watch.d.ts +21 -0
  130. package/dist/src/watch.js +328 -0
  131. package/package.json +99 -3
  132. package/scripts/install-epubcheck.sh +44 -0
@@ -0,0 +1,92 @@
1
+ import path from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import yargs from "yargs/yargs";
5
+ import { hideBin } from "yargs/helpers";
6
+ import config from "../utils/config.js";
7
+ /**
8
+ * Returns true when a module is being executed directly (e.g.
9
+ * `node dist/src/scripts/fix/fix-xml.js`) rather than imported by another
10
+ * module. Callers should pass `import.meta.url`. We realpath both sides so
11
+ * symlinks, pnpm `.bin` shims, and relative invocations all line up.
12
+ */
13
+ export function isEntryPoint(metaUrl) {
14
+ const entry = process.argv[1];
15
+ if (!entry)
16
+ return false;
17
+ try {
18
+ return realpathSync(fileURLToPath(metaUrl)) === realpathSync(entry);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ /**
25
+ * Parse command line arguments consistently across all scripts
26
+ * @param includeInputOption Whether to include input option
27
+ * @param includeOutputOption Whether to include output option
28
+ * @returns Parsed args object
29
+ */
30
+ export function parseArgs(includeInputOption = true, includeOutputOption = true) {
31
+ const parser = yargs(hideBin(process.argv));
32
+ if (includeInputOption) {
33
+ parser.option("input", {
34
+ alias: "i",
35
+ type: "string",
36
+ description: "Input EPUB file path",
37
+ default: config.inputEPUB,
38
+ });
39
+ }
40
+ if (includeOutputOption) {
41
+ parser.option("output", {
42
+ alias: "o",
43
+ type: "string",
44
+ description: "Output EPUB file path",
45
+ default: config.outputEPUB,
46
+ });
47
+ }
48
+ return parser.help(false).version(false).argv;
49
+ }
50
+ /**
51
+ * Get the UI language from CLI args or config.
52
+ * Reads --lang, falls back to config.lang.
53
+ */
54
+ export function getLang() {
55
+ const args = process.argv.slice(2);
56
+ for (let i = 0; i < args.length; i++) {
57
+ const arg = args[i];
58
+ if (arg === undefined)
59
+ continue;
60
+ if (arg.startsWith("--lang="))
61
+ return arg.split("=")[1] ?? config.lang;
62
+ if (arg === "--lang" && i + 1 < args.length)
63
+ return args[i + 1] ?? config.lang;
64
+ }
65
+ return config.lang;
66
+ }
67
+ /**
68
+ * Get the temp directory from CLI args or config
69
+ * Reads the --temp or -t argument, falls back to config.tempDir
70
+ * @returns Absolute path to temp directory
71
+ */
72
+ export function getTempDir() {
73
+ const args = process.argv.slice(2);
74
+ // Look for --temp or -t in the arguments array
75
+ for (let i = 0; i < args.length; i++) {
76
+ const arg = args[i];
77
+ if (arg === undefined)
78
+ continue;
79
+ // Check for --temp=value or -t=value
80
+ if (arg.startsWith("--temp=") || arg.startsWith("-t=")) {
81
+ const tempPath = arg.split("=")[1] ?? "";
82
+ return path.isAbsolute(tempPath) ? tempPath : path.join(process.cwd(), tempPath);
83
+ }
84
+ // Check for --temp value or -t value (next arg is the value)
85
+ if ((arg === "--temp" || arg === "-t") && i + 1 < args.length) {
86
+ const tempPath = args[i + 1] ?? "";
87
+ return path.isAbsolute(tempPath) ? tempPath : path.join(process.cwd(), tempPath);
88
+ }
89
+ }
90
+ // Fallback to config default
91
+ return path.join(process.cwd(), config.tempDir);
92
+ }
@@ -0,0 +1,12 @@
1
+ import { type RunOpts } from "./utils.js";
2
+ import { type EpubCheckReport, type EpubCheckTotals } from "../utils/epubcheck-report.js";
3
+ export interface ValidationOptions extends RunOpts {
4
+ /** Receives this invocation's diagnostics on success, failure or timeout. */
5
+ onReport?: (report: EpubCheckReport) => void;
6
+ }
7
+ /** Compatibility fallback when detailed JSON diagnostics are unavailable. */
8
+ export declare function parseEpubCheckMessages(output: string): EpubCheckTotals | undefined;
9
+ /** Synchronous compatibility entry point for existing direct callers. */
10
+ export declare function run(opts?: ValidationOptions): void;
11
+ /** Keep timers and sibling book processing responsive during native validation. */
12
+ export declare function runAsync(opts?: ValidationOptions): Promise<void>;
@@ -0,0 +1,185 @@
1
+ import { reportError, reportInfo, reportWarning } from "../utils/diagnostics.js";
2
+ import { runBufferedProcess } from "../utils/buffered-process.js";
3
+ import { spawnSync } from "node:child_process";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import config from "../utils/config.js";
8
+ import { parseArgs, isEntryPoint } from "./utils.js";
9
+ import { parseEpubCheckJson, } from "../utils/epubcheck-report.js";
10
+ /** Compatibility fallback when detailed JSON diagnostics are unavailable. */
11
+ export function parseEpubCheckMessages(output) {
12
+ const match = output.match(/Messages:\s*(\d+)\s+fatals?\s*\/\s*(\d+)\s+errors?\s*\/\s*(\d+)\s+warnings?\s*\/\s*(\d+)\s+infos?/i);
13
+ if (!match)
14
+ return undefined;
15
+ return {
16
+ fatals: Number(match[1]),
17
+ errors: Number(match[2]),
18
+ warnings: Number(match[3]),
19
+ infos: Number(match[4]),
20
+ };
21
+ }
22
+ function assertOwnedReportDirectory(directory, owner) {
23
+ const current = fs.lstatSync(directory);
24
+ if (!current.isDirectory() || current.dev !== owner.dev || current.ino !== owner.ino)
25
+ throw new Error("Refusing to use an EPUBCheck report directory whose ownership changed.");
26
+ }
27
+ /** Run the pinned Java validator; the requested EPUB is never changed here. */
28
+ function* validation(opts) {
29
+ let outputEpub = opts.output;
30
+ if (!outputEpub) {
31
+ const argv = parseArgs(false, true);
32
+ outputEpub = argv.output ?? config.outputEPUB;
33
+ }
34
+ if (!outputEpub)
35
+ throw new Error("No output EPUB file specified.");
36
+ const timeoutMs = opts.timeoutMs ?? config.epubcheckTimeoutMs;
37
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
38
+ throw new Error("EPUBCheck timeout must be a positive integer no larger than 2147483647.");
39
+ // A fresh private directory prevents stale reports and input/report collisions.
40
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "epubcheck-report-"));
41
+ const owner = fs.lstatSync(directory);
42
+ const reportPath = path.join(directory, "diagnostics.json");
43
+ const report = { source: "unavailable", exitCode: null, messages: [] };
44
+ let failure;
45
+ try {
46
+ reportInfo(`Validating EPUB: ${outputEpub}`);
47
+ const args = [
48
+ "-jar",
49
+ path.resolve(config.epubcheckPath),
50
+ outputEpub,
51
+ "--locale",
52
+ "en",
53
+ "--json",
54
+ reportPath,
55
+ ];
56
+ if (opts.strict)
57
+ args.push("--failonwarnings");
58
+ const result = yield { args, timeoutMs };
59
+ report.exitCode = result.status;
60
+ if (result.stdout)
61
+ process.stdout.write(result.stdout);
62
+ if (result.stderr)
63
+ process.stderr.write(result.stderr);
64
+ if (result.error) {
65
+ if (result.error.code === "ETIMEDOUT")
66
+ throw new Error(`EPUBCheck exceeded its ${timeoutMs} ms time limit.`, {
67
+ cause: result.error,
68
+ });
69
+ throw new Error(`Failed to run EPUBCheck: ${result.error.message}`, { cause: result.error });
70
+ }
71
+ try {
72
+ assertOwnedReportDirectory(directory, owner);
73
+ const stats = fs.lstatSync(reportPath);
74
+ if (!stats.isFile() || stats.size > 16 * 1024 * 1024)
75
+ throw new Error("EPUBCheck JSON report must be a regular file no larger than 16 MiB.");
76
+ Object.assign(report, parseEpubCheckJson(fs.readFileSync(reportPath, "utf8")), {
77
+ source: "json",
78
+ });
79
+ }
80
+ catch (error) {
81
+ const reason = error instanceof SyntaxError
82
+ ? "Malformed JSON."
83
+ : error instanceof Error
84
+ ? error.message
85
+ : "Unsupported diagnostics.";
86
+ report.diagnosticsError = `Could not read EPUBCheck JSON diagnostics; detailed validation messages are unavailable. ${reason}`;
87
+ report.totals = parseEpubCheckMessages(`${result.stdout ?? ""}\n${result.stderr ?? ""}`);
88
+ report.source = report.totals ? "text" : "unavailable";
89
+ if (report.totals)
90
+ reportInfo(report.diagnosticsError);
91
+ else
92
+ reportWarning("Could not read EPUBCheck message totals; validation diagnostics are incomplete.");
93
+ }
94
+ // JSON mode keeps native totals but redirects detailed messages to the file.
95
+ for (const message of report.messages) {
96
+ const locations = message.locations
97
+ .map((location) => `${location.path}${location.line === undefined ? "" : `(${location.line}${location.column === undefined ? "" : `,${location.column}`})`}`)
98
+ .join(", ");
99
+ process.stderr.write(`${message.severity}(${message.code}): ${locations ? `${locations}: ` : ""}${message.message}\n`);
100
+ }
101
+ if (report.totals?.warnings)
102
+ reportWarning(`EPUBCheck reported ${report.totals.warnings} warning(s).`);
103
+ if (result.status !== 0)
104
+ throw new Error(`EPUB validation failed (exit ${result.status ?? "unknown"}).`);
105
+ if (report.totals?.fatals ||
106
+ report.totals?.errors ||
107
+ report.messages.some((message) => message.severity === "FATAL" || message.severity === "ERROR"))
108
+ throw new Error("EPUB validation failed: EPUBCheck reported fatal/error diagnostics despite exit 0.");
109
+ if (opts.strict && !report.totals)
110
+ throw new Error("Could not read EPUBCheck message totals; validation diagnostics are incomplete.");
111
+ if (opts.strict &&
112
+ (report.totals?.warnings || report.messages.some((message) => message.severity === "WARNING")))
113
+ throw new Error("EPUBCheck warnings are not allowed in strict mode.");
114
+ reportInfo("EPUB validation passed.");
115
+ }
116
+ catch (error) {
117
+ if (report.source === "unavailable")
118
+ report.diagnosticsError ??= error instanceof Error ? error.message : String(error);
119
+ failure = { error };
120
+ }
121
+ finally {
122
+ try {
123
+ assertOwnedReportDirectory(directory, owner);
124
+ fs.rmSync(directory, { recursive: true, force: true });
125
+ }
126
+ catch (error) {
127
+ failure ??= { error };
128
+ reportWarning(`Failed to clean EPUBCheck diagnostics: ${error instanceof Error ? error.message : String(error)}`);
129
+ }
130
+ try {
131
+ opts.onReport?.(report);
132
+ }
133
+ catch (error) {
134
+ failure ??= { error };
135
+ }
136
+ }
137
+ if (failure)
138
+ throw failure.error;
139
+ }
140
+ /** Synchronous compatibility entry point for existing direct callers. */
141
+ export function run(opts = {}) {
142
+ const operation = validation(opts);
143
+ const request = operation.next();
144
+ if (request.done)
145
+ return;
146
+ let result;
147
+ try {
148
+ result = spawnSync("java", request.value.args, {
149
+ encoding: "utf8",
150
+ maxBuffer: 16 * 1024 * 1024,
151
+ timeout: request.value.timeoutMs,
152
+ killSignal: "SIGKILL",
153
+ });
154
+ }
155
+ catch (error) {
156
+ operation.throw(error);
157
+ return;
158
+ }
159
+ operation.next(result);
160
+ }
161
+ /** Keep timers and sibling book processing responsive during native validation. */
162
+ export async function runAsync(opts = {}) {
163
+ const operation = validation(opts);
164
+ const request = operation.next();
165
+ if (request.done)
166
+ return;
167
+ let result;
168
+ try {
169
+ result = await runBufferedProcess("java", request.value.args, request.value.timeoutMs);
170
+ }
171
+ catch (error) {
172
+ operation.throw(error);
173
+ return;
174
+ }
175
+ operation.next(result);
176
+ }
177
+ if (isEntryPoint(import.meta.url)) {
178
+ try {
179
+ run();
180
+ }
181
+ catch (err) {
182
+ reportError(err);
183
+ process.exit(1);
184
+ }
185
+ }
@@ -0,0 +1,30 @@
1
+ export interface StorageRevision {
2
+ job: string;
3
+ input: string;
4
+ completedMs: number;
5
+ bytes: number;
6
+ signature: string;
7
+ }
8
+ export interface StoragePlan {
9
+ schema: 1;
10
+ directory: string;
11
+ identity: string;
12
+ keepRevisions: number;
13
+ createdAt: string;
14
+ verifiedRevisionBytes: number;
15
+ candidateBytes: number;
16
+ candidates: StorageRevision[];
17
+ retained: StorageRevision[];
18
+ protected: Array<{
19
+ name: string;
20
+ reason: string;
21
+ }>;
22
+ }
23
+ /** Read-only inventory and plan. Unknown/failed jobs and originals are never purge candidates. */
24
+ export declare function planStorage(directory: string, keepRevisions?: number): Promise<StoragePlan>;
25
+ export declare function saveStoragePlan(plan: StoragePlan, destination: string): Promise<void>;
26
+ /** Applying requires a saved preview and a fresh plan identical under the watcher lock. */
27
+ export declare function applyStoragePlan(file: string): Promise<{
28
+ removed: string[];
29
+ fileBytes: number;
30
+ }>;
@@ -0,0 +1,286 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { constants } from "node:fs";
4
+ import { open } from "node:fs/promises";
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ import { acquireKernelWatchLock, clearRecoverableWatchRecord } from "./utils/watch-lock.js";
7
+ import { refreshWatchSummary } from "./utils/watch-summary.js";
8
+ const JOB = /^[a-zA-Z0-9_-]+-[a-f0-9]{16}-([a-f0-9]{64})-[a-f0-9]{16}$/;
9
+ const FILES = new Set([
10
+ "optimized.epub",
11
+ "completed.json",
12
+ "report.json",
13
+ "report.html",
14
+ "watch-status.json",
15
+ ]);
16
+ const identity = (s) => `${s.dev}:${s.ino}`;
17
+ const version = (s) => `${identity(s)}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`;
18
+ async function assertOwner(directory, expected) {
19
+ const current = await fs.lstat(directory);
20
+ if (!current.isDirectory() || identity(current) !== expected)
21
+ throw new Error("Storage directory identity changed");
22
+ }
23
+ async function hashFile(file) {
24
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
25
+ try {
26
+ const before = await handle.stat();
27
+ if (!before.isFile() || before.nlink !== 1)
28
+ throw new Error("Unsafe or hard-linked revision resource");
29
+ const hash = createHash("sha256");
30
+ for await (const bytes of handle.createReadStream({ autoClose: false }))
31
+ hash.update(bytes);
32
+ if (version(before) !== version(await handle.stat()))
33
+ throw new Error("Revision changed during inspection");
34
+ return hash.digest("hex");
35
+ }
36
+ finally {
37
+ await handle.close();
38
+ }
39
+ }
40
+ async function readJson(file, limit) {
41
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
42
+ try {
43
+ const before = await handle.stat();
44
+ if (!before.isFile() || before.nlink !== 1 || before.size > limit)
45
+ throw new Error("Unsafe or oversized storage record");
46
+ const buffer = Buffer.alloc(limit + 1);
47
+ let offset = 0;
48
+ while (offset < buffer.length) {
49
+ const r = await handle.read(buffer, offset, buffer.length - offset, offset);
50
+ if (!r.bytesRead)
51
+ break;
52
+ offset += r.bytesRead;
53
+ }
54
+ if (offset > limit || version(before) !== version(await handle.stat()))
55
+ throw new Error("Storage record changed or exceeds limit");
56
+ return JSON.parse(buffer.subarray(0, offset).toString("utf8"));
57
+ }
58
+ finally {
59
+ await handle.close();
60
+ }
61
+ }
62
+ function object(value) {
63
+ if (!value || typeof value !== "object" || Array.isArray(value))
64
+ throw new Error("Invalid storage record");
65
+ return value;
66
+ }
67
+ function inside(candidate, root) {
68
+ const relative = path.relative(root, candidate);
69
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
70
+ }
71
+ async function inspectRevision(root, job) {
72
+ const match = JOB.exec(job);
73
+ if (!match)
74
+ throw new Error("Not a recognized watcher revision");
75
+ const directory = path.join(root, job), owner = await fs.lstat(directory);
76
+ if (!owner.isDirectory())
77
+ throw new Error("Revision is not a real directory");
78
+ const names = (await fs.readdir(directory)).sort();
79
+ if (!names.includes("optimized.epub") ||
80
+ !names.includes("completed.json") ||
81
+ !names.includes("report.json") ||
82
+ names.some((name) => !FILES.has(name)))
83
+ throw new Error("Incomplete revision or unrecognized files preserved");
84
+ const parts = [identity(owner)];
85
+ let bytes = 0;
86
+ for (const name of names) {
87
+ const file = path.join(directory, name), stat = await fs.lstat(file);
88
+ if (!stat.isFile() || stat.nlink !== 1)
89
+ throw new Error("Symlinks, directories and hard links are protected");
90
+ bytes += stat.size;
91
+ parts.push(`${name}:${version(stat)}`);
92
+ }
93
+ const completed = object(await readJson(path.join(directory, "completed.json"), 65536));
94
+ const report = object(await readJson(path.join(directory, "report.json"), 1024 * 1024));
95
+ if (typeof completed.input !== "string" ||
96
+ !path.isAbsolute(completed.input) ||
97
+ inside(path.resolve(completed.input), root) ||
98
+ completed.inputSha256 !== match[1] ||
99
+ completed.settings !== job.slice(-16) ||
100
+ typeof completed.outputSha256 !== "string" ||
101
+ !/^[a-f0-9]{64}$/.test(completed.outputSha256))
102
+ throw new Error("Invalid completion ownership record");
103
+ const validation = object(report.validation), totals = object(validation.totals);
104
+ if (report.success !== true ||
105
+ validation.exitCode !== 0 ||
106
+ totals.errors !== 0 ||
107
+ totals.fatals !== 0)
108
+ throw new Error("Failed or unvalidated revision preserved");
109
+ if ((await hashFile(path.join(directory, "optimized.epub"))) !== completed.outputSha256)
110
+ throw new Error("Output checksum changed; preserving revision");
111
+ await assertOwner(directory, identity(owner));
112
+ const stamp = await fs.lstat(path.join(directory, "completed.json"));
113
+ return {
114
+ job,
115
+ input: completed.input,
116
+ completedMs: stamp.mtimeMs,
117
+ bytes,
118
+ signature: createHash("sha256")
119
+ .update(parts.join("\n") + completed.outputSha256)
120
+ .digest("hex"),
121
+ };
122
+ }
123
+ /** Read-only inventory and plan. Unknown/failed jobs and originals are never purge candidates. */
124
+ export async function planStorage(directory, keepRevisions = 2) {
125
+ if (!Number.isSafeInteger(keepRevisions) || keepRevisions < 1)
126
+ throw new Error("Keep at least one successful revision per original");
127
+ directory = path.resolve(directory);
128
+ const stat = await fs.lstat(directory);
129
+ if (!stat.isDirectory())
130
+ throw new Error("Storage root must be a real directory, not a symbolic link");
131
+ const canonical = await fs.realpath(directory);
132
+ const plan = {
133
+ schema: 1,
134
+ directory: canonical,
135
+ identity: identity(stat),
136
+ keepRevisions,
137
+ createdAt: new Date().toISOString(),
138
+ verifiedRevisionBytes: 0,
139
+ candidateBytes: 0,
140
+ candidates: [],
141
+ retained: [],
142
+ protected: [],
143
+ };
144
+ const revisions = [];
145
+ for (const entry of (await fs.readdir(canonical, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
146
+ if (entry.name.startsWith(".epub-watch") || entry.name === "index.html")
147
+ continue;
148
+ if (!entry.isDirectory() || !JOB.test(entry.name)) {
149
+ plan.protected.push({ name: entry.name, reason: "Unrecognized entry preserved" });
150
+ continue;
151
+ }
152
+ try {
153
+ const revision = await inspectRevision(canonical, entry.name);
154
+ revisions.push(revision);
155
+ plan.verifiedRevisionBytes += revision.bytes;
156
+ }
157
+ catch (error) {
158
+ plan.protected.push({
159
+ name: entry.name,
160
+ reason: error instanceof Error ? error.message : String(error),
161
+ });
162
+ }
163
+ }
164
+ const groups = new Map();
165
+ for (const revision of revisions) {
166
+ const group = groups.get(revision.input) ?? [];
167
+ group.push(revision);
168
+ groups.set(revision.input, group);
169
+ }
170
+ for (const group of groups.values()) {
171
+ group.sort((a, b) => b.completedMs - a.completedMs || a.job.localeCompare(b.job));
172
+ plan.retained.push(...group.slice(0, keepRevisions));
173
+ plan.candidates.push(...group.slice(keepRevisions));
174
+ }
175
+ plan.candidates.sort((a, b) => a.job.localeCompare(b.job));
176
+ plan.retained.sort((a, b) => a.job.localeCompare(b.job));
177
+ plan.candidateBytes = plan.candidates.reduce((sum, item) => sum + item.bytes, 0);
178
+ await assertOwner(canonical, plan.identity);
179
+ return plan;
180
+ }
181
+ export async function saveStoragePlan(plan, destination) {
182
+ const relative = path.relative(plan.directory, path.resolve(destination));
183
+ if (inside(path.resolve(destination), plan.directory) &&
184
+ (relative.split(path.sep).some((part) => JOB.test(part)) ||
185
+ relative.startsWith(".epub-watch") ||
186
+ relative === "index.html"))
187
+ throw new Error("Plan must not replace watcher resources");
188
+ await fs.writeFile(destination, JSON.stringify(plan, null, 2) + "\n", {
189
+ flag: "wx",
190
+ mode: 0o600,
191
+ });
192
+ }
193
+ /** Applying requires a saved preview and a fresh plan identical under the watcher lock. */
194
+ export async function applyStoragePlan(file) {
195
+ const saved = object(await readJson(file, 8 * 1024 * 1024));
196
+ if (saved.schema !== 1 ||
197
+ typeof saved.directory !== "string" ||
198
+ typeof saved.identity !== "string" ||
199
+ typeof saved.keepRevisions !== "number" ||
200
+ !Array.isArray(saved.candidates))
201
+ throw new Error("Invalid storage plan");
202
+ const directory = saved.directory;
203
+ await assertOwner(directory, saved.identity);
204
+ const kernel = await acquireKernelWatchLock(directory), lockPath = path.join(directory, ".epub-watch.lock");
205
+ let lock;
206
+ try {
207
+ if (kernel)
208
+ await clearRecoverableWatchRecord(lockPath, kernel.identity);
209
+ lock = await open(lockPath, "wx", 0o600);
210
+ }
211
+ catch (error) {
212
+ await kernel?.release();
213
+ throw error;
214
+ }
215
+ const owner = await lock.stat();
216
+ const removed = [];
217
+ try {
218
+ await lock.writeFile(JSON.stringify({
219
+ pid: process.pid,
220
+ operation: "storage-maintenance",
221
+ method: kernel ? "linux-flock-v1" : "exclusive-file-v1",
222
+ guard: kernel?.identity,
223
+ }));
224
+ const current = await planStorage(directory, saved.keepRevisions);
225
+ if (current.identity !== saved.identity ||
226
+ JSON.stringify(current.candidates) !== JSON.stringify(saved.candidates))
227
+ throw new Error("Storage changed since preview; generate a new plan");
228
+ for (const item of current.candidates) {
229
+ await assertOwner(directory, saved.identity);
230
+ const verified = await inspectRevision(directory, item.job);
231
+ if (verified.signature !== item.signature)
232
+ throw new Error("Revision changed before deletion");
233
+ const original = path.join(directory, item.job), quarantine = path.join(directory, `.epub-prune-${randomUUID()}`);
234
+ const before = await fs.lstat(original);
235
+ await fs.rename(original, quarantine);
236
+ await assertOwner(quarantine, identity(before));
237
+ // Validate every resource before removing any; never recursively traverse a job.
238
+ const names = await fs.readdir(quarantine);
239
+ try {
240
+ for (const name of names) {
241
+ const stat = await fs.lstat(path.join(quarantine, name));
242
+ if (!FILES.has(name) || !stat.isFile() || stat.nlink !== 1)
243
+ throw new Error("Changed quarantine resource preserved");
244
+ }
245
+ }
246
+ catch (error) {
247
+ // Restore only if the original name is still vacant.
248
+ if (!(await fs.pathExists(original)))
249
+ await fs.rename(quarantine, original);
250
+ throw error;
251
+ }
252
+ for (const name of names) {
253
+ if (!FILES.has(name))
254
+ throw new Error("Unexpected quarantine file preserved");
255
+ await assertOwner(quarantine, identity(before));
256
+ const target = path.join(quarantine, name), stat = await fs.lstat(target);
257
+ if (!stat.isFile() || stat.nlink !== 1)
258
+ throw new Error("Changed quarantine resource preserved");
259
+ await fs.unlink(target);
260
+ }
261
+ await fs.rmdir(quarantine);
262
+ removed.push(item.job);
263
+ }
264
+ await refreshWatchSummary(directory);
265
+ return { removed, fileBytes: current.candidateBytes };
266
+ }
267
+ catch (error) {
268
+ throw new Error(`Storage purge stopped after ${removed.length} complete revision(s) removed. Inspect any .epub-prune-* recovery directory. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
269
+ }
270
+ finally {
271
+ try {
272
+ await lock.close();
273
+ await assertOwner(directory, saved.identity);
274
+ await removeOwnedLock(lockPath, identity(owner));
275
+ }
276
+ finally {
277
+ await kernel?.release();
278
+ }
279
+ }
280
+ }
281
+ async function removeOwnedLock(file, expected) {
282
+ const stat = await fs.lstat(file);
283
+ if (!stat.isFile() || identity(stat) !== expected)
284
+ throw new Error("Maintenance lock replaced; refusing cleanup");
285
+ await fs.unlink(file);
286
+ }
@@ -0,0 +1,51 @@
1
+ export type Preset = "balanced" | "lossless" | "author";
2
+ export interface Args {
3
+ input: string;
4
+ batch?: string;
5
+ /** Maximum concurrent books in batch mode; defaults to 1. */
6
+ jobs?: number;
7
+ storage?: string;
8
+ storagePlan?: string;
9
+ applyStoragePlan?: string;
10
+ keepRevisions?: number;
11
+ watch?: string;
12
+ watchSettleMs?: number;
13
+ outputDir?: string;
14
+ output: string;
15
+ temp: string;
16
+ clean: boolean;
17
+ "jpg-quality": number;
18
+ jpgQuality: number;
19
+ "png-quality": number;
20
+ pngQuality: number;
21
+ /** Optional opaque #RRGGBB background for eligible PNG-to-JPEG conversion. */
22
+ pngBackground?: string;
23
+ "png-background"?: string;
24
+ fonts: boolean;
25
+ "author-workflow": boolean;
26
+ authorWorkflow: boolean;
27
+ "author-config"?: string;
28
+ authorConfig?: string;
29
+ repair: boolean;
30
+ strict: boolean;
31
+ validationTimeout?: number;
32
+ imageConcurrency?: number;
33
+ profile: boolean;
34
+ preset: Preset;
35
+ "report-json"?: string;
36
+ reportJson?: string;
37
+ "report-html"?: string;
38
+ reportHtml?: string;
39
+ doctor: boolean;
40
+ inspect: boolean;
41
+ "max-image-dim": number;
42
+ maxImageDim: number;
43
+ "convert-png": boolean;
44
+ convertPng: boolean;
45
+ "lazy-loading": boolean;
46
+ lazyLoading: boolean;
47
+ lossless: boolean;
48
+ lang: string;
49
+ _: (string | number)[];
50
+ $0: string;
51
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ export interface AuthorWorkflowConfig {
2
+ summaryHref: string;
3
+ coverHref: string;
4
+ coverSpineId: string;
5
+ chapterClasses: readonly string[];
6
+ sectionClasses: readonly string[];
7
+ summaryEntryClass: string;
8
+ coverNavClass: string;
9
+ sectionNavClass: string;
10
+ }
11
+ export declare const DEFAULT_AUTHOR_WORKFLOW_CONFIG: Readonly<AuthorWorkflowConfig>;
12
+ export declare function resolveAuthorWorkflowConfig(overrides?: Partial<AuthorWorkflowConfig>): AuthorWorkflowConfig;
13
+ export declare function loadAuthorWorkflowConfig(configPath?: string): Promise<AuthorWorkflowConfig>;
14
+ export declare function resolveAuthorWorkflowHref(contentDir: string, href: string, label: string): string;
15
+ export declare function createOwnerRelativeHref(ownerFile: string, targetFile: string): string;
16
+ export declare function referenceTargetsFile(epubDir: string, ownerFile: string, reference: string | undefined, targetFile: string): boolean;
17
+ export declare function hasAnyClass(classValue: string | undefined, classes: readonly string[]): boolean;