@blackbelt-technology/pi-dashboard-document-converter 0.5.4
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/.pi/skills/document-converter/SKILL.md +79 -0
- package/README.md +106 -0
- package/engine/.dockerignore +4 -0
- package/engine/Dockerfile +75 -0
- package/engine/IMAGE_VERSION +1 -0
- package/engine/README.md +65 -0
- package/engine/VENDOR.md +40 -0
- package/engine/build-image.sh +29 -0
- package/engine/document_converter/LICENSE +21 -0
- package/engine/document_converter/__init__.py +365 -0
- package/engine/document_converter/__main__.py +5 -0
- package/engine/document_converter/asciidoc_converter.py +534 -0
- package/engine/document_converter/cli.py +751 -0
- package/engine/document_converter/code_renderer.py +356 -0
- package/engine/document_converter/converter.py +928 -0
- package/engine/document_converter/cover_page.py +448 -0
- package/engine/document_converter/diagram_resizer.py +311 -0
- package/engine/document_converter/diagram_sizing.py +357 -0
- package/engine/document_converter/docx_reader.py +627 -0
- package/engine/document_converter/field_updater.py +277 -0
- package/engine/document_converter/font_manager.py +850 -0
- package/engine/document_converter/frontmatter_parser.py +644 -0
- package/engine/document_converter/graphviz_renderer.py +354 -0
- package/engine/document_converter/image_extractor.py +281 -0
- package/engine/document_converter/image_style.py +237 -0
- package/engine/document_converter/logo_manager.py +1021 -0
- package/engine/document_converter/manifest_manager.py +288 -0
- package/engine/document_converter/mermaid_renderer.py +371 -0
- package/engine/document_converter/meta_mapper.py +398 -0
- package/engine/document_converter/pandoc_styles.py +222 -0
- package/engine/document_converter/pdf_converter.py +735 -0
- package/engine/document_converter/pdf_server.py +283 -0
- package/engine/document_converter/plantuml_renderer.py +460 -0
- package/engine/document_converter/plantuml_server.py +273 -0
- package/engine/document_converter/pyproject.toml +80 -0
- package/engine/document_converter/round_trip.py +312 -0
- package/engine/document_converter/spacing_applier.py +332 -0
- package/engine/document_converter/spacing_config.py +323 -0
- package/engine/document_converter/style_extractor.py +420 -0
- package/engine/document_converter/svg_embedder.py +294 -0
- package/engine/document_converter/system_variables.py +158 -0
- package/engine/document_converter/table_formatter.py +450 -0
- package/engine/document_converter/template_extractor.py +1334 -0
- package/engine/document_converter/template_manager.py +427 -0
- package/engine/document_converter/textbox_extractor.py +551 -0
- package/engine/document_converter/toc_generator.py +559 -0
- package/engine/document_converter/toc_style.py +290 -0
- package/engine/document_converter/tree_renderer.py +328 -0
- package/engine/document_converter/utils.py +134 -0
- package/engine/document_converter/variable_manager.py +394 -0
- package/engine/engine_cli.py +371 -0
- package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
- package/engine/frontmatter_filler/fill.py +517 -0
- package/engine/markdown_table_profiler/profile.py +442 -0
- package/engine/nano-banana-styles.yaml +59 -0
- package/engine/tests/test_styled_diagrams.py +109 -0
- package/package.json +32 -0
- package/src/__tests__/engine.test.ts +72 -0
- package/src/__tests__/facade.test.ts +120 -0
- package/src/__tests__/integration.test.ts +101 -0
- package/src/__tests__/ocr.test.ts +34 -0
- package/src/__tests__/provenance.test.ts +89 -0
- package/src/__tests__/routing.test.ts +40 -0
- package/src/engine.ts +187 -0
- package/src/errors.ts +43 -0
- package/src/index.ts +179 -0
- package/src/ocr.ts +43 -0
- package/src/provenance.ts +79 -0
- package/src/routing.ts +49 -0
- package/src/schema.json +69 -0
- package/src/schema.ts +107 -0
- package/src/types.ts +90 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { runEngine, type EngineRunner } from "../engine.js";
|
|
3
|
+
import { DocConverterError } from "../errors.js";
|
|
4
|
+
|
|
5
|
+
const okRunner =
|
|
6
|
+
(payload: object): EngineRunner =>
|
|
7
|
+
async () => ({ stdout: JSON.stringify({ ok: true, ...payload }), stderr: "", exitCode: 0 });
|
|
8
|
+
|
|
9
|
+
describe("runEngine envelope handling", () => {
|
|
10
|
+
it("returns the ok envelope minus the ok flag", async () => {
|
|
11
|
+
const res = await runEngine(
|
|
12
|
+
{ image: "pi-doc-engine:test", runner: okRunner({ output: "/out.docx" }) },
|
|
13
|
+
{ command: "renderDocx", input: "/in.md", output: "/out.docx" },
|
|
14
|
+
);
|
|
15
|
+
expect(res).toEqual({ output: "/out.docx" });
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("maps an error envelope to a typed DocConverterError", async () => {
|
|
19
|
+
const runner: EngineRunner = async () => ({
|
|
20
|
+
stdout: JSON.stringify({
|
|
21
|
+
ok: false,
|
|
22
|
+
error: { code: "INGEST_FAILED", message: "boom", stderr: "trace" },
|
|
23
|
+
}),
|
|
24
|
+
stderr: "",
|
|
25
|
+
exitCode: 1,
|
|
26
|
+
});
|
|
27
|
+
await expect(
|
|
28
|
+
runEngine({ image: "x", runner }, { command: "convertToMarkdown", input: "/a.pdf" }),
|
|
29
|
+
).rejects.toMatchObject({ code: "INGEST_FAILED", message: "boom", stderr: "trace" });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("rejects non-JSON stdout with BAD_RESPONSE on clean exit", async () => {
|
|
33
|
+
const runner: EngineRunner = async () => ({ stdout: "not json", stderr: "", exitCode: 0 });
|
|
34
|
+
await expect(
|
|
35
|
+
runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
|
|
36
|
+
).rejects.toMatchObject({ code: "BAD_RESPONSE" });
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("rejects non-JSON stdout with ENGINE_NONZERO on bad exit", async () => {
|
|
40
|
+
const runner: EngineRunner = async () => ({ stdout: "", stderr: "docker: not found", exitCode: 127 });
|
|
41
|
+
await expect(
|
|
42
|
+
runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
|
|
43
|
+
).rejects.toMatchObject({ code: "ENGINE_NONZERO", exitCode: 127 });
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("builds path-identical bind mounts for every referenced path", async () => {
|
|
47
|
+
const runner = vi.fn<EngineRunner>(async () => ({
|
|
48
|
+
stdout: JSON.stringify({ ok: true }),
|
|
49
|
+
stderr: "",
|
|
50
|
+
exitCode: 0,
|
|
51
|
+
}));
|
|
52
|
+
await runEngine(
|
|
53
|
+
{ image: "pi-doc-engine:test", runner, mounts: [] },
|
|
54
|
+
{ command: "renderDocx", input: "/work/in.md", output: "/work/out.docx" },
|
|
55
|
+
);
|
|
56
|
+
const argv = runner.mock.calls[0][0];
|
|
57
|
+
expect(argv).toContain("-v");
|
|
58
|
+
expect(argv).toContain("/work:/work");
|
|
59
|
+
expect(argv).toContain("pi-doc-engine:test");
|
|
60
|
+
// mount appears once even though two paths share /work
|
|
61
|
+
expect(argv.filter((a) => a === "/work:/work")).toHaveLength(1);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("surfaces DOCKER_UNAVAILABLE when the runner cannot spawn", async () => {
|
|
65
|
+
const runner: EngineRunner = async () => {
|
|
66
|
+
throw new DocConverterError({ code: "DOCKER_UNAVAILABLE", message: "no docker" });
|
|
67
|
+
};
|
|
68
|
+
await expect(
|
|
69
|
+
runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
|
|
70
|
+
).rejects.toMatchObject({ code: "DOCKER_UNAVAILABLE" });
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { createDocumentConverter } from "../index.js";
|
|
6
|
+
import type { EngineRunner } from "../engine.js";
|
|
7
|
+
|
|
8
|
+
const tmps: string[] = [];
|
|
9
|
+
async function workdir(): Promise<string> {
|
|
10
|
+
const d = await mkdtemp(join(tmpdir(), "docconv-"));
|
|
11
|
+
tmps.push(d);
|
|
12
|
+
return d;
|
|
13
|
+
}
|
|
14
|
+
afterEach(async () => {
|
|
15
|
+
await Promise.all(tmps.splice(0).map((d) => rm(d, { recursive: true, force: true })));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/** Fake runner that records the parsed request and returns a canned ok payload. */
|
|
19
|
+
function recordingRunner(payload: object): { runner: EngineRunner; reqs: any[] } {
|
|
20
|
+
const reqs: any[] = [];
|
|
21
|
+
const runner: EngineRunner = async (_argv, stdin) => {
|
|
22
|
+
reqs.push(JSON.parse(stdin));
|
|
23
|
+
return { stdout: JSON.stringify({ ok: true, ...payload }), stderr: "", exitCode: 0 };
|
|
24
|
+
};
|
|
25
|
+
return { runner, reqs };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe("facade: convertToMarkdown", () => {
|
|
29
|
+
it("stamps provenance and writes markdown to the staging dir", async () => {
|
|
30
|
+
const dir = await workdir();
|
|
31
|
+
const staging = join(dir, "staging");
|
|
32
|
+
const pdf = join(dir, "report.pdf");
|
|
33
|
+
await writeFile(pdf, "fake-pdf-bytes");
|
|
34
|
+
|
|
35
|
+
const { runner, reqs } = recordingRunner({ markdown: "# Report\n\ncontent" });
|
|
36
|
+
const dc = createDocumentConverter({
|
|
37
|
+
image: "pi-doc-engine:test",
|
|
38
|
+
stagingDir: staging,
|
|
39
|
+
engine: { runner },
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const res = await dc.convertToMarkdown(pdf, { ocr: { lang: ["hungarian"], engine: "tesseract" } });
|
|
43
|
+
|
|
44
|
+
// OCR canonical name was mapped to the per-engine code before the engine saw it.
|
|
45
|
+
expect(reqs[0].command).toBe("convertToMarkdown");
|
|
46
|
+
expect(reqs[0].ocr).toEqual({ mode: "auto", engine: "tesseract", codes: ["hun"] });
|
|
47
|
+
|
|
48
|
+
const written = await readFile(res.output, "utf-8");
|
|
49
|
+
expect(written).toContain("provenance:");
|
|
50
|
+
expect(written).toContain("doc_type: pdf");
|
|
51
|
+
expect(written).toContain(`source_path: ${pdf}`);
|
|
52
|
+
expect(written).toContain("# Report");
|
|
53
|
+
expect(res.provenance.sha256).toMatch(/^[0-9a-f]{64}$/);
|
|
54
|
+
expect(res.output).toBe(join(staging, "report.md"));
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("rejects unsupported input formats before calling the engine", async () => {
|
|
58
|
+
const dir = await workdir();
|
|
59
|
+
const { runner, reqs } = recordingRunner({ markdown: "x" });
|
|
60
|
+
const dc = createDocumentConverter({
|
|
61
|
+
image: "x",
|
|
62
|
+
stagingDir: join(dir, "staging"),
|
|
63
|
+
engine: { runner },
|
|
64
|
+
});
|
|
65
|
+
await expect(dc.convertToMarkdown(join(dir, "a.txt"))).rejects.toMatchObject({
|
|
66
|
+
code: "UNSUPPORTED_FORMAT",
|
|
67
|
+
});
|
|
68
|
+
expect(reqs).toHaveLength(0);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("rejects an unsupported OCR language before calling the engine", async () => {
|
|
72
|
+
const dir = await workdir();
|
|
73
|
+
const pdf = join(dir, "a.pdf");
|
|
74
|
+
await writeFile(pdf, "x");
|
|
75
|
+
const { runner, reqs } = recordingRunner({ markdown: "x" });
|
|
76
|
+
const dc = createDocumentConverter({
|
|
77
|
+
image: "x",
|
|
78
|
+
stagingDir: join(dir, "staging"),
|
|
79
|
+
engine: { runner },
|
|
80
|
+
});
|
|
81
|
+
await expect(
|
|
82
|
+
dc.convertToMarkdown(pdf, { ocr: { lang: ["klingon"], engine: "easyocr" } }),
|
|
83
|
+
).rejects.toMatchObject({ code: "OCR_LANG_UNSUPPORTED" });
|
|
84
|
+
expect(reqs).toHaveLength(0);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe("facade: produce", () => {
|
|
89
|
+
it("forwards the nano_banana flag and template to the engine on renderDocx", async () => {
|
|
90
|
+
const { runner, reqs } = recordingRunner({ output: "/out.docx" });
|
|
91
|
+
const dc = createDocumentConverter({
|
|
92
|
+
image: "x",
|
|
93
|
+
stagingDir: "/staging",
|
|
94
|
+
engine: { runner },
|
|
95
|
+
});
|
|
96
|
+
await dc.renderDocx("/in.md", {
|
|
97
|
+
output: "/out.docx",
|
|
98
|
+
template: "default",
|
|
99
|
+
nanoBanana: { enabled: true, style: "ros-3d" },
|
|
100
|
+
});
|
|
101
|
+
expect(reqs[0]).toMatchObject({
|
|
102
|
+
command: "renderDocx",
|
|
103
|
+
input: "/in.md",
|
|
104
|
+
output: "/out.docx",
|
|
105
|
+
template: "default",
|
|
106
|
+
nano_banana: { enabled: true, style: "ros-3d" },
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("returns the extract result with a document_meta path", async () => {
|
|
111
|
+
const { runner } = recordingRunner({ output: "/edit.md", meta: "/document_meta.xml" });
|
|
112
|
+
const dc = createDocumentConverter({
|
|
113
|
+
image: "x",
|
|
114
|
+
stagingDir: "/staging",
|
|
115
|
+
engine: { runner },
|
|
116
|
+
});
|
|
117
|
+
const res = await dc.extractForEdit("/in.docx", "/edit.md");
|
|
118
|
+
expect(res).toEqual({ output: "/edit.md", meta: "/document_meta.xml" });
|
|
119
|
+
});
|
|
120
|
+
});
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration test — one real conversion per direction against the built image.
|
|
3
|
+
* VERIFIED green against `pi-doc-engine:0.1.0` (ingest PDF→md→kb; produce
|
|
4
|
+
* md→DOCX with template + mmdc diagram).
|
|
5
|
+
*
|
|
6
|
+
* Opt-in only (heavy image: docling ML models + LibreOffice + pandoc). Skipped
|
|
7
|
+
* unless `docker` is on PATH and these env vars are set:
|
|
8
|
+
* DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 built + loadable image tag
|
|
9
|
+
* DOC_ENGINE_PDF=/abs/sample.pdf a digital PDF fixture (ingest case)
|
|
10
|
+
* DOC_ENGINE_TEMPLATES=/abs/templates dir with <template>/template.docx (produce case)
|
|
11
|
+
* Never runs in the default `npm test`.
|
|
12
|
+
*
|
|
13
|
+
* DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 DOC_ENGINE_PDF=… DOC_ENGINE_TEMPLATES=… \
|
|
14
|
+
* npx vitest run integration
|
|
15
|
+
*/
|
|
16
|
+
import { execFileSync } from "node:child_process";
|
|
17
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
18
|
+
import { tmpdir } from "node:os";
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
21
|
+
import { createDocumentConverter } from "../index.js";
|
|
22
|
+
|
|
23
|
+
const IMAGE = process.env.DOC_ENGINE_IMAGE;
|
|
24
|
+
|
|
25
|
+
function dockerOk(): boolean {
|
|
26
|
+
if (!IMAGE) return false;
|
|
27
|
+
try {
|
|
28
|
+
execFileSync("docker", ["image", "inspect", IMAGE], { stdio: "ignore" });
|
|
29
|
+
return true;
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const ENABLED = dockerOk();
|
|
36
|
+
let work: string;
|
|
37
|
+
|
|
38
|
+
beforeAll(async () => {
|
|
39
|
+
if (!ENABLED) return;
|
|
40
|
+
work = await mkdtemp(join(tmpdir(), "docconv-it-"));
|
|
41
|
+
});
|
|
42
|
+
afterAll(async () => {
|
|
43
|
+
if (work) await rm(work, { recursive: true, force: true });
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe.skipIf(!ENABLED)("pi-doc-engine integration", () => {
|
|
47
|
+
it("ingest: PDF -> Markdown with provenance, indexable by kb", async () => {
|
|
48
|
+
const dc = createDocumentConverter({ image: IMAGE!, stagingDir: join(work, "staging") });
|
|
49
|
+
// A trivial single-page PDF fixture must exist; integration fixtures are
|
|
50
|
+
// provided alongside the built image. Point at it via DOC_ENGINE_PDF.
|
|
51
|
+
const pdf = process.env.DOC_ENGINE_PDF;
|
|
52
|
+
expect(pdf, "set DOC_ENGINE_PDF to a sample PDF").toBeTruthy();
|
|
53
|
+
|
|
54
|
+
const { output, provenance } = await dc.convertToMarkdown(pdf!);
|
|
55
|
+
const md = await readFile(output, "utf-8");
|
|
56
|
+
expect(md).toContain("provenance:");
|
|
57
|
+
expect(provenance.doc_type).toBe("pdf");
|
|
58
|
+
expect(provenance.sha256).toMatch(/^[0-9a-f]{64}$/);
|
|
59
|
+
}, 120_000);
|
|
60
|
+
|
|
61
|
+
it("produce: Markdown -> DOCX with template + diagram", async () => {
|
|
62
|
+
// Templates are runtime-mounted, not baked into the image (design Q4). Point
|
|
63
|
+
// DOC_ENGINE_TEMPLATES at a dir containing `<template>/template.docx`.
|
|
64
|
+
const templatesDir = process.env.DOC_ENGINE_TEMPLATES;
|
|
65
|
+
expect(templatesDir, "set DOC_ENGINE_TEMPLATES to a templates dir").toBeTruthy();
|
|
66
|
+
|
|
67
|
+
const dc = createDocumentConverter({
|
|
68
|
+
image: IMAGE!,
|
|
69
|
+
stagingDir: join(work, "staging"),
|
|
70
|
+
mounts: [templatesDir!],
|
|
71
|
+
});
|
|
72
|
+
const md = join(work, "spec.md");
|
|
73
|
+
await writeFile(
|
|
74
|
+
md,
|
|
75
|
+
[
|
|
76
|
+
"---",
|
|
77
|
+
"template: default",
|
|
78
|
+
"---",
|
|
79
|
+
"",
|
|
80
|
+
"# Spec",
|
|
81
|
+
"",
|
|
82
|
+
"Hello world.",
|
|
83
|
+
"",
|
|
84
|
+
"```mermaid",
|
|
85
|
+
"graph TD; A-->B",
|
|
86
|
+
"```",
|
|
87
|
+
"",
|
|
88
|
+
].join("\n"),
|
|
89
|
+
"utf-8",
|
|
90
|
+
);
|
|
91
|
+
const out = join(work, "spec.docx");
|
|
92
|
+
const res = await dc.renderDocx(md, {
|
|
93
|
+
output: out,
|
|
94
|
+
template: "default",
|
|
95
|
+
templatesDir: templatesDir!,
|
|
96
|
+
});
|
|
97
|
+
expect(res.output).toBe(out);
|
|
98
|
+
const bytes = await readFile(out);
|
|
99
|
+
expect(bytes.byteLength).toBeGreaterThan(1000); // non-trivial DOCX
|
|
100
|
+
}, 180_000);
|
|
101
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { mapOcrCodes, SUPPORTED_LANGUAGES } from "../ocr.js";
|
|
3
|
+
import { DocConverterError } from "../errors.js";
|
|
4
|
+
|
|
5
|
+
describe("OCR canonical-name -> per-engine-code mapping", () => {
|
|
6
|
+
it("maps the same language to different codes per engine", () => {
|
|
7
|
+
expect(mapOcrCodes(["hungarian"], "easyocr")).toEqual(["hu"]);
|
|
8
|
+
expect(mapOcrCodes(["hungarian"], "tesseract")).toEqual(["hun"]);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("is case- and whitespace-insensitive", () => {
|
|
12
|
+
expect(mapOcrCodes([" English ", "GERMAN"], "tesseract")).toEqual(["eng", "deu"]);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it("rapidocr ignores language codes", () => {
|
|
16
|
+
expect(mapOcrCodes(["hungarian"], "rapidocr")).toEqual([]);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("throws OCR_LANG_UNSUPPORTED for an unknown language", () => {
|
|
20
|
+
try {
|
|
21
|
+
mapOcrCodes(["klingon"], "easyocr");
|
|
22
|
+
throw new Error("should have thrown");
|
|
23
|
+
} catch (e) {
|
|
24
|
+
expect(e).toBeInstanceOf(DocConverterError);
|
|
25
|
+
expect((e as DocConverterError).code).toBe("OCR_LANG_UNSUPPORTED");
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("throws when a known language is unsupported by the chosen engine path", () => {
|
|
30
|
+
// ocrmac has no italian entry mapping? It does; use a language absent for ocrmac.
|
|
31
|
+
expect(() => mapOcrCodes(["hungarian"], "easyocr")).not.toThrow();
|
|
32
|
+
expect(SUPPORTED_LANGUAGES).toContain("hungarian");
|
|
33
|
+
});
|
|
34
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
buildProvenance,
|
|
4
|
+
provenanceFrontmatter,
|
|
5
|
+
stampProvenance,
|
|
6
|
+
} from "../provenance.js";
|
|
7
|
+
|
|
8
|
+
const FIXED = "2026-06-24T00:00:00.000Z";
|
|
9
|
+
|
|
10
|
+
describe("provenance frontmatter", () => {
|
|
11
|
+
it("builds a deterministic record with a fixed timestamp", () => {
|
|
12
|
+
const prov = buildProvenance({
|
|
13
|
+
sourcePath: "/docs/a.pdf",
|
|
14
|
+
sha256: "abc123",
|
|
15
|
+
docType: "pdf",
|
|
16
|
+
convertedAt: FIXED,
|
|
17
|
+
});
|
|
18
|
+
expect(prov).toEqual({
|
|
19
|
+
source_path: "/docs/a.pdf",
|
|
20
|
+
sha256: "abc123",
|
|
21
|
+
doc_type: "pdf",
|
|
22
|
+
converted_at: FIXED,
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("includes page/slide only when provided", () => {
|
|
27
|
+
const prov = buildProvenance({
|
|
28
|
+
sourcePath: "/a.pptx",
|
|
29
|
+
sha256: "x",
|
|
30
|
+
docType: "pptx",
|
|
31
|
+
convertedAt: FIXED,
|
|
32
|
+
slide: 3,
|
|
33
|
+
});
|
|
34
|
+
expect(prov.slide).toBe(3);
|
|
35
|
+
expect(prov.page).toBeUndefined();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("prepends a frontmatter block to a bare body", () => {
|
|
39
|
+
const prov = buildProvenance({
|
|
40
|
+
sourcePath: "/a.pdf",
|
|
41
|
+
sha256: "deadbeef",
|
|
42
|
+
docType: "pdf",
|
|
43
|
+
convertedAt: FIXED,
|
|
44
|
+
});
|
|
45
|
+
const out = stampProvenance("# Title\n\nbody", prov);
|
|
46
|
+
expect(out.startsWith("---\nprovenance:\n")).toBe(true);
|
|
47
|
+
expect(out).toContain("sha256: deadbeef");
|
|
48
|
+
expect(out.trimEnd().endsWith("body")).toBe(true);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("injects into existing frontmatter without clobbering keys", () => {
|
|
52
|
+
const prov = buildProvenance({
|
|
53
|
+
sourcePath: "/a.pdf",
|
|
54
|
+
sha256: "h",
|
|
55
|
+
docType: "pdf",
|
|
56
|
+
convertedAt: FIXED,
|
|
57
|
+
});
|
|
58
|
+
const existing = "---\ntitle: Hello\n---\n\nbody\n";
|
|
59
|
+
const out = stampProvenance(existing, prov);
|
|
60
|
+
expect(out).toContain("provenance:");
|
|
61
|
+
expect(out).toContain("title: Hello");
|
|
62
|
+
// Single opening fence only.
|
|
63
|
+
expect(out.match(/^---\n/)).toBeTruthy();
|
|
64
|
+
expect(out.indexOf("---", 4)).toBeGreaterThan(0);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("re-stamping the same hash is byte-identical (idempotent)", () => {
|
|
68
|
+
const prov = buildProvenance({
|
|
69
|
+
sourcePath: "/a.pdf",
|
|
70
|
+
sha256: "same",
|
|
71
|
+
docType: "pdf",
|
|
72
|
+
convertedAt: FIXED,
|
|
73
|
+
});
|
|
74
|
+
const a = stampProvenance("body", prov);
|
|
75
|
+
const b = stampProvenance("body", prov);
|
|
76
|
+
expect(a).toBe(b);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("quotes scalars that could be misparsed", () => {
|
|
80
|
+
const prov = buildProvenance({
|
|
81
|
+
sourcePath: "/path with spaces/a.pdf",
|
|
82
|
+
sha256: "h",
|
|
83
|
+
docType: "pdf",
|
|
84
|
+
convertedAt: FIXED,
|
|
85
|
+
});
|
|
86
|
+
const fm = provenanceFrontmatter(prov);
|
|
87
|
+
expect(fm).toContain('"/path with spaces/a.pdf"');
|
|
88
|
+
});
|
|
89
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { docTypeOf, ingestDocType, isIngestable } from "../routing.js";
|
|
3
|
+
import { DocConverterError } from "../errors.js";
|
|
4
|
+
|
|
5
|
+
describe("routing", () => {
|
|
6
|
+
it("maps known extensions to doc types", () => {
|
|
7
|
+
expect(docTypeOf("/a/b.pdf")).toBe("pdf");
|
|
8
|
+
expect(docTypeOf("/a/b.DOCX")).toBe("docx");
|
|
9
|
+
expect(docTypeOf("report.pptx")).toBe("pptx");
|
|
10
|
+
expect(docTypeOf("sheet.xlsx")).toBe("xlsx");
|
|
11
|
+
expect(docTypeOf("notes.md")).toBe("md");
|
|
12
|
+
expect(docTypeOf("notes.markdown")).toBe("md");
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it("throws UNSUPPORTED_FORMAT for unknown extensions", () => {
|
|
16
|
+
expect(() => docTypeOf("/a/b.txt")).toThrowError(DocConverterError);
|
|
17
|
+
try {
|
|
18
|
+
docTypeOf("/a/b");
|
|
19
|
+
} catch (e) {
|
|
20
|
+
expect((e as DocConverterError).code).toBe("UNSUPPORTED_FORMAT");
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it("classifies ingestable formats", () => {
|
|
25
|
+
expect(isIngestable("a.pdf")).toBe(true);
|
|
26
|
+
expect(isIngestable("a.docx")).toBe(true);
|
|
27
|
+
expect(isIngestable("a.md")).toBe(false); // md is not ingested, it IS the target
|
|
28
|
+
expect(isIngestable("a.txt")).toBe(false);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("ingestDocType rejects markdown", () => {
|
|
32
|
+
expect(ingestDocType("a.pdf")).toBe("pdf");
|
|
33
|
+
try {
|
|
34
|
+
ingestDocType("a.md");
|
|
35
|
+
throw new Error("should have thrown");
|
|
36
|
+
} catch (e) {
|
|
37
|
+
expect((e as DocConverterError).code).toBe("UNSUPPORTED_FORMAT");
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
});
|
package/src/engine.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Docker invocation layer.
|
|
3
|
+
*
|
|
4
|
+
* Spawns `docker run -i pi-doc-engine`, pipes one JSON request to stdin, reads
|
|
5
|
+
* one JSON response from stdout, and maps exit codes + the response envelope to
|
|
6
|
+
* typed errors. Mounts are **path-identical** (`-v dir:dir -w dir`) so host
|
|
7
|
+
* paths equal container paths — no path rewriting needed.
|
|
8
|
+
*
|
|
9
|
+
* The raw runner is injectable so unit tests can mock the Docker boundary
|
|
10
|
+
* without a container.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
13
|
+
import { dirname } from "node:path";
|
|
14
|
+
import { DocConverterError } from "./errors.js";
|
|
15
|
+
|
|
16
|
+
/** One JSON request to the engine. `command` selects the handler. */
|
|
17
|
+
export interface EngineRequest {
|
|
18
|
+
command: string;
|
|
19
|
+
[key: string]: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Successful engine envelope. */
|
|
23
|
+
interface EngineOkResponse {
|
|
24
|
+
ok: true;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Failure envelope. */
|
|
29
|
+
interface EngineErrResponse {
|
|
30
|
+
ok: false;
|
|
31
|
+
error: { code: string; message: string; stderr?: string };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type EngineResponse = EngineOkResponse | EngineErrResponse;
|
|
35
|
+
|
|
36
|
+
/** Low-level process result. */
|
|
37
|
+
export interface RunnerResult {
|
|
38
|
+
stdout: string;
|
|
39
|
+
stderr: string;
|
|
40
|
+
exitCode: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Raw runner: given the full argv and the stdin payload, run the process and
|
|
45
|
+
* return its captured output. Default uses `docker`; tests inject a fake.
|
|
46
|
+
*/
|
|
47
|
+
export type EngineRunner = (argv: string[], stdin: string) => Promise<RunnerResult>;
|
|
48
|
+
|
|
49
|
+
export interface EngineConfig {
|
|
50
|
+
/** Image tag, e.g. `pi-doc-engine:0.1.0`. */
|
|
51
|
+
image: string;
|
|
52
|
+
/** Host dirs to bind-mount path-identically (parents of all referenced files). */
|
|
53
|
+
mounts?: string[];
|
|
54
|
+
/** Passed through to `docker run -e GEMINI_API_KEY` when set in env. */
|
|
55
|
+
passEnv?: string[];
|
|
56
|
+
/** Override the process runner (tests). */
|
|
57
|
+
runner?: EngineRunner;
|
|
58
|
+
/** docker binary (default `docker`). */
|
|
59
|
+
dockerBin?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const defaultRunner: EngineRunner = (argv, stdin) =>
|
|
63
|
+
new Promise((resolve, reject) => {
|
|
64
|
+
const [bin, ...args] = argv;
|
|
65
|
+
const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
66
|
+
if (!child.stdout || !child.stderr || !child.stdin) {
|
|
67
|
+
reject(
|
|
68
|
+
new DocConverterError({
|
|
69
|
+
code: "DOCKER_UNAVAILABLE",
|
|
70
|
+
message: `spawned ${bin} without piped stdio`,
|
|
71
|
+
}),
|
|
72
|
+
);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
let stdout = "";
|
|
76
|
+
let stderr = "";
|
|
77
|
+
child.stdout.on("data", (d) => (stdout += d.toString()));
|
|
78
|
+
child.stderr.on("data", (d) => (stderr += d.toString()));
|
|
79
|
+
child.on("error", (err) => {
|
|
80
|
+
reject(
|
|
81
|
+
new DocConverterError({
|
|
82
|
+
code: "DOCKER_UNAVAILABLE",
|
|
83
|
+
message: `failed to spawn ${bin}: ${(err as Error).message}`,
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
child.on("close", (code) => resolve({ stdout, stderr, exitCode: code ?? -1 }));
|
|
88
|
+
child.stdin.end(stdin);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
/** Build the `docker run` argv for a request. */
|
|
92
|
+
function buildArgv(cfg: EngineConfig, mounts: Set<string>): string[] {
|
|
93
|
+
const argv = [cfg.dockerBin ?? "docker", "run", "--rm", "-i"];
|
|
94
|
+
for (const m of mounts) argv.push("-v", `${m}:${m}`);
|
|
95
|
+
for (const key of cfg.passEnv ?? ["GEMINI_API_KEY"]) {
|
|
96
|
+
if (process.env[key] !== undefined) argv.push("-e", key);
|
|
97
|
+
}
|
|
98
|
+
argv.push(cfg.image);
|
|
99
|
+
return argv;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Collect every filesystem path referenced by a request so we can mount its dir. */
|
|
103
|
+
function collectMountDirs(cfg: EngineConfig, req: EngineRequest): Set<string> {
|
|
104
|
+
const dirs = new Set<string>(cfg.mounts ?? []);
|
|
105
|
+
const add = (p: unknown) => {
|
|
106
|
+
if (typeof p === "string" && p.startsWith("/")) dirs.add(dirname(p));
|
|
107
|
+
};
|
|
108
|
+
for (const [k, v] of Object.entries(req)) {
|
|
109
|
+
if (k === "command") continue;
|
|
110
|
+
if (Array.isArray(v)) v.forEach(add);
|
|
111
|
+
else add(v);
|
|
112
|
+
}
|
|
113
|
+
return dirs;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Run one engine command. Resolves with the `ok:true` envelope (minus `ok`),
|
|
118
|
+
* rejects with a `DocConverterError` on any failure.
|
|
119
|
+
*/
|
|
120
|
+
export async function runEngine<T = Record<string, unknown>>(
|
|
121
|
+
cfg: EngineConfig,
|
|
122
|
+
req: EngineRequest,
|
|
123
|
+
): Promise<T> {
|
|
124
|
+
const runner = cfg.runner ?? defaultRunner;
|
|
125
|
+
const argv = buildArgv(cfg, collectMountDirs(cfg, req));
|
|
126
|
+
const { stdout, stderr, exitCode } = await runner(argv, JSON.stringify(req));
|
|
127
|
+
|
|
128
|
+
let parsed: EngineResponse | undefined;
|
|
129
|
+
try {
|
|
130
|
+
parsed = JSON.parse(stdout) as EngineResponse;
|
|
131
|
+
} catch {
|
|
132
|
+
// No parsable envelope — surface the raw failure.
|
|
133
|
+
throw new DocConverterError({
|
|
134
|
+
code: exitCode === 0 ? "BAD_RESPONSE" : "ENGINE_NONZERO",
|
|
135
|
+
message:
|
|
136
|
+
exitCode === 0
|
|
137
|
+
? "engine returned non-JSON output"
|
|
138
|
+
: `engine exited ${exitCode}`,
|
|
139
|
+
stderr: stderr || stdout,
|
|
140
|
+
exitCode,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (parsed.ok === false) {
|
|
145
|
+
const { code, message, stderr: estderr } = parsed.error;
|
|
146
|
+
throw new DocConverterError({
|
|
147
|
+
code: mapEngineCode(code),
|
|
148
|
+
message,
|
|
149
|
+
stderr: estderr ?? stderr,
|
|
150
|
+
exitCode,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (exitCode !== 0) {
|
|
155
|
+
throw new DocConverterError({
|
|
156
|
+
code: "ENGINE_NONZERO",
|
|
157
|
+
message: `engine exited ${exitCode} despite ok envelope`,
|
|
158
|
+
stderr,
|
|
159
|
+
exitCode,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const { ok: _ok, ...rest } = parsed;
|
|
164
|
+
return rest as T;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Map engine-side error codes to facade error codes. */
|
|
168
|
+
function mapEngineCode(code: string): DocConverterError["code"] {
|
|
169
|
+
switch (code) {
|
|
170
|
+
case "INPUT_NOT_FOUND":
|
|
171
|
+
return "INPUT_NOT_FOUND";
|
|
172
|
+
case "OCR_ENGINE_UNKNOWN":
|
|
173
|
+
return "OCR_ENGINE_UNKNOWN";
|
|
174
|
+
case "INGEST_FAILED":
|
|
175
|
+
case "DOCLING_UNAVAILABLE":
|
|
176
|
+
return "INGEST_FAILED";
|
|
177
|
+
case "PRODUCE_FAILED":
|
|
178
|
+
case "MMDC_FAILED":
|
|
179
|
+
return "PRODUCE_FAILED";
|
|
180
|
+
case "FILL_FAILED":
|
|
181
|
+
return "FILL_FAILED";
|
|
182
|
+
case "PROFILE_FAILED":
|
|
183
|
+
return "PROFILE_FAILED";
|
|
184
|
+
default:
|
|
185
|
+
return "INTERNAL";
|
|
186
|
+
}
|
|
187
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed errors for the facade. Every engine failure surfaces as one of these so
|
|
3
|
+
* callers never parse stderr strings.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Stable error codes the engine + facade emit. */
|
|
7
|
+
export type DocConverterErrorCode =
|
|
8
|
+
| "DOCKER_UNAVAILABLE" // docker binary missing or daemon down
|
|
9
|
+
| "ENGINE_NONZERO" // engine process exited non-zero
|
|
10
|
+
| "BAD_RESPONSE" // engine stdout was not the expected JSON envelope
|
|
11
|
+
| "INPUT_NOT_FOUND" // input file missing
|
|
12
|
+
| "OCR_LANG_UNSUPPORTED" // canonical lang not supported by chosen engine
|
|
13
|
+
| "OCR_ENGINE_UNKNOWN" // unknown OCR engine
|
|
14
|
+
| "UNSUPPORTED_FORMAT" // extension not routable to a command
|
|
15
|
+
| "INGEST_FAILED"
|
|
16
|
+
| "PRODUCE_FAILED"
|
|
17
|
+
| "FILL_FAILED"
|
|
18
|
+
| "PROFILE_FAILED"
|
|
19
|
+
| "INTERNAL";
|
|
20
|
+
|
|
21
|
+
export interface DocConverterErrorInit {
|
|
22
|
+
code: DocConverterErrorCode;
|
|
23
|
+
message: string;
|
|
24
|
+
/** Engine stderr, when the failure came from the engine process. */
|
|
25
|
+
stderr?: string;
|
|
26
|
+
/** Engine process exit code, when applicable. */
|
|
27
|
+
exitCode?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The single error type the facade rejects with. */
|
|
31
|
+
export class DocConverterError extends Error {
|
|
32
|
+
readonly code: DocConverterErrorCode;
|
|
33
|
+
readonly stderr?: string;
|
|
34
|
+
readonly exitCode?: number;
|
|
35
|
+
|
|
36
|
+
constructor(init: DocConverterErrorInit) {
|
|
37
|
+
super(init.message);
|
|
38
|
+
this.name = "DocConverterError";
|
|
39
|
+
this.code = init.code;
|
|
40
|
+
this.stderr = init.stderr;
|
|
41
|
+
this.exitCode = init.exitCode;
|
|
42
|
+
}
|
|
43
|
+
}
|