Skip to content

A fast, helpful, and open-source document parser

fix(node): batch-parse output collisions, unsupported extensions, --version

Osama Ansar2f7ad185a022
diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.ts
index 88d9007..7ec619b 100644
--- a/packages/node/src/cli.ts
+++ b/packages/node/src/cli.ts
@@ -7,10 +7,34 @@ import { formatText } from "./cli-text.js";
import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from "node:fs";
import { join, relative, parse as parsePath } from "node:path";
+/**
+ * The package version, read from the package.json that ships next to `dist/`
+ * (`dist/cli.js` -> `../package.json`, both in a checkout and when installed),
+ * so `--version` can never drift from the published version.
+ */
+function readPackageVersion(): string {
+ try {
+ const pkg: unknown = JSON.parse(
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
+ );
+ if (
+ typeof pkg === "object" &&
+ pkg !== null &&
+ "version" in pkg &&
+ typeof pkg.version === "string"
+ ) {
+ return pkg.version;
+ }
+ } catch {
+ // Fall through: an unreadable package.json must not break every command.
+ }
+ return "unknown";
+}
+
program
.name("liteparse")
.description("Fast, lightweight PDF and document parsing")
- .version("2.0.0");
+ .version(readPackageVersion());
/**
* Resolve a CLI `<file>` argument into a parser input. `-` means read the
@@ -439,6 +463,12 @@ program
);
}
+ // Outputs are named `<stem><ext>`, so `report.pdf` and `report.png`
+ // would both land on `report.txt` and the later one would silently
+ // overwrite the earlier one. Refuse up front, before parsing or
+ // writing anything.
+ assertNoOutputCollisions(files, inputDir, outputDir, outExt);
+
let success = 0;
let errors = 0;
@@ -446,11 +476,7 @@ program
const t0 = Date.now();
const rel = relative(inputDir, filePath);
const parsed = parsePath(rel);
- const outPath = join(
- outputDir,
- parsed.dir,
- parsed.name + outExt,
- );
+ const outPath = batchOutputPath(filePath, inputDir, outputDir, outExt);
mkdirSync(join(outputDir, parsed.dir), { recursive: true });
try {
@@ -496,15 +522,66 @@ program
},
);
+// Keep in sync with the extension lists in crates/liteparse/src/conversion.rs.
+// Plain-text formats (.txt, .md, .markdown, .log) are deliberately absent: the
+// parser rejects them ("unsupported file format"), so scanning them would only
+// turn every such file in a directory into a reported failure.
const SUPPORTED_EXTENSIONS = new Set([
".pdf",
".doc", ".docx", ".docm", ".dot", ".dotm", ".dotx", ".odt", ".ott", ".rtf", ".pages",
".ppt", ".pptx", ".pptm", ".pot", ".potm", ".potx", ".odp", ".otp", ".key",
".xls", ".xlsx", ".xlsm", ".xlsb", ".ods", ".ots", ".csv", ".tsv", ".numbers",
".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif", ".webp", ".svg",
- ".txt", ".md", ".markdown", ".log",
]);
+/** Where `batch-parse` writes the output for `filePath`. */
+function batchOutputPath(
+ filePath: string,
+ inputDir: string,
+ outputDir: string,
+ outExt: string,
+): string {
+ const parsed = parsePath(relative(inputDir, filePath));
+ return join(outputDir, parsed.dir, parsed.name + outExt);
+}
+
+/**
+ * Throw if two inputs would be written to the same output file. Paths are
+ * compared case-insensitively on Windows and macOS, whose default file systems
+ * would make `Report.txt` and `report.txt` the same file.
+ */
+function assertNoOutputCollisions(
+ files: string[],
+ inputDir: string,
+ outputDir: string,
+ outExt: string,
+): void {
+ const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
+ const byOutput = new Map<string, { outPath: string; inputs: string[] }>();
+ for (const filePath of files) {
+ const outPath = batchOutputPath(filePath, inputDir, outputDir, outExt);
+ const key = caseInsensitive ? outPath.toLowerCase() : outPath;
+ const entry = byOutput.get(key);
+ if (entry) entry.inputs.push(filePath);
+ else byOutput.set(key, { outPath, inputs: [filePath] });
+ }
+
+ const collisions = [...byOutput.values()].filter((entry) => entry.inputs.length > 1);
+ if (collisions.length === 0) return;
+
+ const shown = collisions
+ .slice(0, 10)
+ .map(({ outPath, inputs }) => ` ${outPath} <- ${inputs.join(", ")}`);
+ if (collisions.length > shown.length) {
+ shown.push(` ... and ${collisions.length - shown.length} more`);
+ }
+ throw new Error(
+ `output path collision: multiple input files would be written to the same output file:\n` +
+ `${shown.join("\n")}\n` +
+ `Rename the inputs, or process one file type at a time with --extension (e.g. --extension pdf).`,
+ );
+}
+
function collectFiles(
dir: string,
recursive: boolean,
diff --git a/packages/node/tests/cli-batch.test.mjs b/packages/node/tests/cli-batch.test.mjs
new file mode 100644
index 0000000..db7721e
--- /dev/null
+++ b/packages/node/tests/cli-batch.test.mjs
@@ -0,0 +1,129 @@
+// `batch-parse` input selection / output naming and `--version`.
+//
+// These drive the built CLI (dist/cli.js) like cli-text.test.mjs does.
+
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import {
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const packageDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const repoRoot = resolve(packageDir, "..", "..");
+const cliPath = join(packageDir, "dist", "cli.js");
+const samplePdf = join(repoRoot, "integration_tests_data", "sample.pdf");
+const sampleImage = join(repoRoot, "integration_tests_data", "receipt.png");
+
+function runCli(args) {
+ // The timeout keeps a regression from hanging the suite.
+ return spawnSync(process.execPath, [cliPath, ...args], { encoding: "utf8", timeout: 60_000 });
+}
+
+function batchParse(inputDir, outputDir, ...extra) {
+ return runCli(["batch-parse", inputDir, outputDir, "--no-ocr", "--max-pages", "1", ...extra]);
+}
+
+function withTempDirs(fn) {
+ const dir = mkdtempSync(join(tmpdir(), "liteparse-cli-batch-"));
+ const inputDir = join(dir, "input");
+ const outputDir = join(dir, "output");
+ mkdirSync(inputDir);
+ try {
+ return fn(inputDir, outputDir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test("--version reports the version in package.json", () => {
+ const { version } = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
+ const result = runCli(["--version"]);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.trim(), version);
+});
+
+test("batch-parse refuses inputs that map to the same output file", () => {
+ withTempDirs((inputDir, outputDir) => {
+ copyFileSync(samplePdf, join(inputDir, "report.pdf"));
+ copyFileSync(sampleImage, join(inputDir, "report.png"));
+
+ const result = batchParse(inputDir, outputDir);
+
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(result.stderr, /output path collision/);
+ assert.match(result.stderr, /report\.pdf/);
+ assert.match(result.stderr, /report\.png/);
+ // Nothing was parsed or written.
+ assert.deepEqual(readdirSync(outputDir), []);
+ });
+});
+
+test("batch-parse --extension avoids a stem collision", () => {
+ withTempDirs((inputDir, outputDir) => {
+ copyFileSync(samplePdf, join(inputDir, "report.pdf"));
+ copyFileSync(sampleImage, join(inputDir, "report.png"));
+
+ const result = batchParse(inputDir, outputDir, "--extension", "pdf", "--quiet");
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(readdirSync(outputDir), ["report.txt"]);
+ });
+});
+
+test("batch-parse allows the same stem in different directories", () => {
+ withTempDirs((inputDir, outputDir) => {
+ for (const sub of ["a", "b"]) {
+ mkdirSync(join(inputDir, sub));
+ copyFileSync(samplePdf, join(inputDir, sub, "report.pdf"));
+ }
+
+ const result = batchParse(inputDir, outputDir, "--recursive", "--quiet");
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(existsSync(join(outputDir, "a", "report.txt")), true);
+ assert.equal(existsSync(join(outputDir, "b", "report.txt")), true);
+ });
+});
+
+test(
+ "batch-parse detects collisions that differ only by case on case-insensitive file systems",
+ { skip: process.platform !== "win32" && process.platform !== "darwin" },
+ () => {
+ withTempDirs((inputDir, outputDir) => {
+ copyFileSync(samplePdf, join(inputDir, "Report.pdf"));
+ copyFileSync(sampleImage, join(inputDir, "report.png"));
+
+ const result = batchParse(inputDir, outputDir);
+
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(result.stderr, /output path collision/);
+ });
+ }
+);
+
+test("batch-parse skips plain-text files the parser cannot handle", () => {
+ withTempDirs((inputDir, outputDir) => {
+ copyFileSync(samplePdf, join(inputDir, "doc.pdf"));
+ for (const name of ["notes.txt", "README.md", "CHANGES.markdown", "run.log"]) {
+ writeFileSync(join(inputDir, name), "plain text\n");
+ }
+
+ const result = batchParse(inputDir, outputDir);
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stderr, /found 1 files to process/);
+ assert.match(result.stderr, /batch complete: 1 succeeded, 0 failed/);
+ assert.deepEqual(readdirSync(outputDir), ["doc.txt"]);
+ });
+});