@intentic/fileq 1.430.0 → 1.432.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/NOTICE +58 -1
  2. package/README.md +29 -1
  3. package/bin/fileq-rg-pre +6 -2
  4. package/dist/app.d.ts.map +1 -1
  5. package/dist/app.js +4 -1
  6. package/dist/app.js.map +1 -1
  7. package/dist/commands/check.command.d.ts.map +1 -1
  8. package/dist/commands/check.command.js +12 -5
  9. package/dist/commands/check.command.js.map +1 -1
  10. package/dist/commands/derive.command.d.ts.map +1 -1
  11. package/dist/commands/derive.command.js +3 -2
  12. package/dist/commands/derive.command.js.map +1 -1
  13. package/dist/commands/read.command.d.ts.map +1 -1
  14. package/dist/commands/read.command.js +42 -7
  15. package/dist/commands/read.command.js.map +1 -1
  16. package/dist/commands/render.command.d.ts.map +1 -1
  17. package/dist/commands/render.command.js +23 -10
  18. package/dist/commands/render.command.js.map +1 -1
  19. package/dist/lib/derivers/docx-math-symbols.d.ts +14 -0
  20. package/dist/lib/derivers/docx-math-symbols.d.ts.map +1 -0
  21. package/dist/lib/derivers/docx-math-symbols.js +160 -0
  22. package/dist/lib/derivers/docx-math-symbols.js.map +1 -0
  23. package/dist/lib/derivers/docx-math.d.ts +15 -0
  24. package/dist/lib/derivers/docx-math.d.ts.map +1 -0
  25. package/dist/lib/derivers/docx-math.js +252 -0
  26. package/dist/lib/derivers/docx-math.js.map +1 -0
  27. package/dist/lib/derivers/docx.d.ts.map +1 -1
  28. package/dist/lib/derivers/docx.js +3 -2
  29. package/dist/lib/derivers/docx.js.map +1 -1
  30. package/dist/lib/derivers/pdf-furniture.d.ts.map +1 -1
  31. package/dist/lib/derivers/pdf-furniture.js +3 -0
  32. package/dist/lib/derivers/pdf-furniture.js.map +1 -1
  33. package/dist/lib/derivers/pdf-tables.d.ts +9 -0
  34. package/dist/lib/derivers/pdf-tables.d.ts.map +1 -0
  35. package/dist/lib/derivers/pdf-tables.js +319 -0
  36. package/dist/lib/derivers/pdf-tables.js.map +1 -0
  37. package/dist/lib/derivers/pdf.d.ts.map +1 -1
  38. package/dist/lib/derivers/pdf.js +77 -38
  39. package/dist/lib/derivers/pdf.js.map +1 -1
  40. package/dist/lib/ocr-slots.d.ts +8 -0
  41. package/dist/lib/ocr-slots.d.ts.map +1 -0
  42. package/dist/lib/ocr-slots.js +35 -0
  43. package/dist/lib/ocr-slots.js.map +1 -0
  44. package/dist/skill.d.ts.map +1 -1
  45. package/dist/skill.js +7 -2
  46. package/dist/skill.js.map +1 -1
  47. package/package.json +7 -7
  48. package/src/app.ts +4 -1
  49. package/src/cli.integration.test.ts +30 -8
  50. package/src/commands/check.command.ts +20 -5
  51. package/src/commands/derive.command.ts +3 -2
  52. package/src/commands/read.command.ts +56 -8
  53. package/src/commands/render.command.ts +33 -11
  54. package/src/derivers.integration.test.ts +131 -11
  55. package/src/lib/derivers/docx-math-symbols.ts +197 -0
  56. package/src/lib/derivers/docx-math.test.ts +131 -0
  57. package/src/lib/derivers/docx-math.ts +355 -0
  58. package/src/lib/derivers/docx.ts +5 -3
  59. package/src/lib/derivers/image.ts +2 -2
  60. package/src/lib/derivers/pdf-furniture.test.ts +9 -0
  61. package/src/lib/derivers/pdf-furniture.ts +5 -0
  62. package/src/lib/derivers/pdf-tables.test.ts +292 -0
  63. package/src/lib/derivers/pdf-tables.ts +465 -0
  64. package/src/lib/derivers/pdf.ts +94 -40
  65. package/src/lib/ocr-slots.integration.test.ts +64 -0
  66. package/src/lib/ocr-slots.ts +61 -0
  67. package/src/lib/sidecar.ts +1 -1
  68. package/src/render.integration.test.ts +5 -4
  69. package/src/skill.ts +10 -5
@@ -0,0 +1,355 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
3
+ import { childrenNamed, isElement, parseXml, type XmlElement } from "../check/xml-tree.js";
4
+ import {
5
+ ACCENTS,
6
+ BAR_POSITIONS,
7
+ BIG_OPERATORS,
8
+ DEFAULT_ACCENT,
9
+ DEFAULT_BAR,
10
+ DEFAULT_BIG_OPERATOR,
11
+ DEFAULT_GROUP_CHR,
12
+ FRACTIONS,
13
+ FUNCTIONS,
14
+ LATEX_SPECIALS,
15
+ LIMIT_OPERATORS,
16
+ LINE_BREAK,
17
+ SYMBOLS,
18
+ } from "./docx-math-symbols.js";
19
+
20
+ // Word's equations (Office Math, OMML) as LaTeX: mammoth skips m:oMath and m:oMathPara with a warning, so "For m=1,"
21
+ // read "For ,". Before mammoth sees the document, each equation in the parts it reads is replaced by a plain text run
22
+ // holding its LaTeX, `$…$` inline and `$$…$$` for a display equation; a document with no equation is handed to mammoth
23
+ // untouched. Ported from markitdown's converter_utils/docx/pre_process.py and math/omml.py
24
+ // (https://github.com/microsoft/markitdown, MIT, Copyright (c) Microsoft Corporation), which adapt dwml's
25
+ // dwml/omml.py (https://github.com/xiilei/dwml, Apache-2.0, by xilei; ../../../NOTICE). What differs: an equation the converter
26
+ // cannot read falls back to its text alone rather than dropping every equation in the document; a delimiter keeps all
27
+ // of its arguments, joined by its separator, rather than the last; a pre-sub-superscript and a border box keep their
28
+ // content; an n-ary with no operator character is an integral, as Word draws it; and a display equation's runs stay
29
+ // inside the paragraph that held them rather than becoming a paragraph nested in it.
30
+
31
+ const MATH_NAMESPACES = ["http://schemas.openxmlformats.org/officeDocument/2006/math", "http://purl.oclc.org/ooxml/officeDocument/math"];
32
+ const WORD_NAMESPACES = ["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"];
33
+
34
+ // The parts mammoth reads that can hold an equation, as markitdown pre-processes them.
35
+ const MATH_PARTS = new Set(["word/document.xml", "word/footnotes.xml", "word/endnotes.xml"]);
36
+
37
+ // Elements whose LaTeX is simply their children's, in order.
38
+ const TRANSPARENT = new Set(["box", "borderBox", "sSub", "sSup", "sSubSup", "num", "den", "deg", "e"]);
39
+
40
+ /** An element converted: its LaTeX, and for a property element (`m:fPr`, `m:dPr`…) the values it sets. */
41
+ interface Converted {
42
+ /** A property element's text is the line breaks it carries, which dwml sets before the object. */
43
+ readonly text: string;
44
+ readonly val?: (name: string) => string | undefined;
45
+ }
46
+
47
+ const NO_PROPS: Converted = { text: "", val: () => undefined };
48
+
49
+ interface Child {
50
+ readonly tag: string;
51
+ readonly value: Converted;
52
+ }
53
+
54
+ /** Converts one equation tree; `prefix` is the namespace prefix the document wrote Office Math under. */
55
+ class OmmlToLatex {
56
+ constructor(private readonly prefix: string) {}
57
+
58
+ private local(element: XmlElement): string | undefined {
59
+ return element.name.startsWith(`${this.prefix}:`) ? element.name.slice(this.prefix.length + 1) : undefined;
60
+ }
61
+
62
+ // The math children of an element converted, in order; Word's own elements inside them (w:rPr) carry no math.
63
+ private children(element: XmlElement, include?: readonly string[]): Child[] {
64
+ return element.children.filter(isElement).flatMap((child) => {
65
+ const tag = this.local(child);
66
+ if (tag === undefined || (include !== undefined && !include.includes(tag))) {
67
+ return [];
68
+ }
69
+ const value = this.convert(child, tag);
70
+ return value === undefined ? [] : [{ tag, value }];
71
+ });
72
+ }
73
+
74
+ private joined(element: XmlElement, include?: readonly string[]): string {
75
+ return this.children(element, include)
76
+ .map((child) => child.value.text)
77
+ .join("");
78
+ }
79
+
80
+ // The last child of each kind, as dwml reads an object's parts (its `e`, its `fPr`).
81
+ private parts(element: XmlElement): Map<string, Converted> {
82
+ return new Map(this.children(element).map((child) => [child.tag, child.value]));
83
+ }
84
+
85
+ private part(element: XmlElement, tag: string): string {
86
+ return this.parts(element).get(tag)?.text ?? "";
87
+ }
88
+
89
+ private props(element: XmlElement, tag: string): Converted {
90
+ const value = this.parts(element).get(tag);
91
+ return value?.val === undefined ? NO_PROPS : value;
92
+ }
93
+
94
+ private readProps(element: XmlElement): Converted {
95
+ const vals = new Map<string, string>();
96
+ for (const child of element.children.filter(isElement)) {
97
+ const tag = this.local(child);
98
+ const value = child.attrs[`${this.prefix}:val`];
99
+ if (tag !== undefined && value !== undefined) {
100
+ vals.set(tag, value);
101
+ }
102
+ }
103
+ const breaks = element.children.filter((child) => isElement(child) && this.local(child) === "brk").length;
104
+ return { text: LINE_BREAK.repeat(breaks), val: (name) => vals.get(name) };
105
+ }
106
+
107
+ /** The LaTeX of an `m:oMath`. */
108
+ latex(element: XmlElement): string {
109
+ return this.joined(element);
110
+ }
111
+
112
+ private convert(element: XmlElement, tag: string): Converted | undefined {
113
+ const handler = this.handlers.get(tag);
114
+ if (handler !== undefined) {
115
+ return { text: handler(element) };
116
+ }
117
+ if (TRANSPARENT.has(tag)) {
118
+ return { text: this.joined(element) };
119
+ }
120
+ return tag.endsWith("Pr") ? this.readProps(element) : undefined;
121
+ }
122
+
123
+ private readonly handlers = new Map<string, (element: XmlElement) => string>([
124
+ ["r", (element) => this.run(element)],
125
+ ["acc", (element) => `${macro(ACCENTS, this.props(element, "accPr").val?.("chr"), DEFAULT_ACCENT)}{${this.part(element, "e")}}`],
126
+ ["bar", (element) => this.decorated(element, "barPr", "pos", BAR_POSITIONS, DEFAULT_BAR)],
127
+ ["groupChr", (element) => this.decorated(element, "groupChrPr", "chr", ACCENTS, DEFAULT_GROUP_CHR)],
128
+ ["d", (element) => this.delimiter(element)],
129
+ ["sub", (element) => `_{${this.joined(element)}}`],
130
+ ["sup", (element) => `^{${this.joined(element)}}`],
131
+ ["sPre", (element) => `{}_{${this.part(element, "sub")}}^{${this.part(element, "sup")}}${this.part(element, "e")}`],
132
+ ["f", (element) => this.fraction(element)],
133
+ ["func", (element) => this.part(element, "fName").replace(FUNCTION_ARGUMENT, () => this.part(element, "e"))],
134
+ ["fName", (element) => this.functionName(element)],
135
+ ["rad", (element) => this.radical(element)],
136
+ ["eqArr", (element) => `\\begin{array}{c}${this.list(element, "e", LINE_BREAK)}\\end{array}`],
137
+ ["limLow", (element) => this.lowerLimit(element)],
138
+ ["limUpp", (element) => `\\overset{${this.part(element, "lim")}}{${this.part(element, "e")}}`],
139
+ ["lim", (element) => this.joined(element).replaceAll("\\rightarrow", "\\to")],
140
+ ["m", (element) => `\\begin{matrix}${this.list(element, "mr", LINE_BREAK)}\\end{matrix}`],
141
+ ["mr", (element) => this.list(element, "e", "&")],
142
+ ["nary", (element) => this.nary(element)],
143
+ ]);
144
+
145
+ // A bar or a group character: its macro, from the property `key` of `propsTag`, over the base.
146
+ private decorated(element: XmlElement, propsTag: string, key: string, table: ReadonlyMap<string, string>, fallback: string): string {
147
+ const props = this.props(element, propsTag);
148
+ return `${props.text}${macro(table, props.val?.(key), fallback)}{${this.part(element, "e")}}`;
149
+ }
150
+
151
+ private fraction(element: XmlElement): string {
152
+ const props = this.props(element, "fPr");
153
+ const set = FRACTIONS.get(props.val?.("type") ?? "bar") ?? FRACTIONS.get("bar");
154
+ return props.text + (set?.(this.part(element, "num"), this.part(element, "den")) ?? "");
155
+ }
156
+
157
+ private radical(element: XmlElement): string {
158
+ const degree = this.part(element, "deg");
159
+ return degree === "" ? `\\sqrt{${this.part(element, "e")}}` : `\\sqrt[${degree}]{${this.part(element, "e")}}`;
160
+ }
161
+
162
+ // A lower limit under lim, max or min is that operator's subscript; under anything else it is set beneath it.
163
+ private lowerLimit(element: XmlElement): string {
164
+ const base = this.part(element, "e");
165
+ const limit = this.part(element, "lim");
166
+ const operator = LIMIT_OPERATORS.get(base);
167
+ return operator === undefined ? `\\underset{${limit}}{${base}}` : `${operator}_{${limit}}`;
168
+ }
169
+
170
+ private list(element: XmlElement, tag: string, separator: string): string {
171
+ return this.children(element, [tag])
172
+ .map((child) => child.value.text)
173
+ .join(separator);
174
+ }
175
+
176
+ // A run's text, each character mapped to its LaTeX symbol and LaTeX's own syntax characters escaped.
177
+ private run(element: XmlElement): string {
178
+ const [t] = childrenNamed(element, `${this.prefix}:t`);
179
+ const raw = (t?.children ?? []).filter((child): child is string => !isElement(child)).join("");
180
+ return escapeLatex([...raw].map((char) => SYMBOLS.get(char) ?? char).join(""));
181
+ }
182
+
183
+ private delimiter(element: XmlElement): string {
184
+ const props = this.props(element, "dPr");
185
+ const side = (key: string, fallback: string): string => {
186
+ const char = props.val?.(key) ?? fallback;
187
+ return char === "" ? "." : escapeLatex(SYMBOLS.get(char) ?? char);
188
+ };
189
+ const separator = escapeLatex(props.val?.("sepChr") ?? "|");
190
+ return `${props.text}\\left${side("begChr", "(")}${this.list(element, "e", separator)}\\right${side("endChr", ")")}`;
191
+ }
192
+
193
+ // A function's name: runs joined first (Word splits a name at a formatting boundary), then looked up, the argument
194
+ // left as a placeholder `func` fills.
195
+ private functionName(element: XmlElement): string {
196
+ const out: string[] = [];
197
+ let name = "";
198
+ const flush = (): void => {
199
+ if (name !== "") {
200
+ out.push(`${FUNCTIONS.get(name) ?? `\\operatorname{${name}}`}(${FUNCTION_ARGUMENT})`);
201
+ name = "";
202
+ }
203
+ };
204
+ for (const child of this.children(element)) {
205
+ if (child.tag === "r") {
206
+ name += child.value.text;
207
+ } else {
208
+ flush();
209
+ out.push(child.value.text);
210
+ }
211
+ }
212
+ flush();
213
+ const joined = out.join("");
214
+ return joined.includes(FUNCTION_ARGUMENT) ? joined : `${joined}${FUNCTION_ARGUMENT}`;
215
+ }
216
+
217
+ private nary(element: XmlElement): string {
218
+ let operator = DEFAULT_BIG_OPERATOR;
219
+ const rest: string[] = [];
220
+ for (const child of this.children(element)) {
221
+ if (child.tag === "naryPr") {
222
+ const char = child.value.val?.("chr");
223
+ operator = char === undefined ? DEFAULT_BIG_OPERATOR : (BIG_OPERATORS.get(char) ?? char);
224
+ } else {
225
+ rest.push(child.value.text);
226
+ }
227
+ }
228
+ const body = rest.join("");
229
+ // A letter straight after the operator would extend its name (\sumx).
230
+ return /^[a-z]/i.test(body) ? `${operator} ${body}` : `${operator}${body}`;
231
+ }
232
+ }
233
+
234
+ const FUNCTION_ARGUMENT = "{fe}";
235
+
236
+ const macro = (table: ReadonlyMap<string, string>, char: string | undefined, fallback: string): string =>
237
+ char === undefined ? fallback : (table.get(char) ?? fallback);
238
+
239
+ /** LaTeX's syntax characters in an equation's text escaped, unless a backslash already escapes them; exported for tests. */
240
+ export const escapeLatex = (raw: string): string => {
241
+ let out = "";
242
+ let last = "";
243
+ for (const char of raw.replaceAll("\\\\", "\\")) {
244
+ out += LATEX_SPECIALS.has(char) && last !== "\\" ? `\\${char}` : char;
245
+ last = char;
246
+ }
247
+ return out;
248
+ };
249
+
250
+ const plainText = (element: XmlElement): string => element.children.map((child) => (isElement(child) ? plainText(child) : child)).join("");
251
+
252
+ /** The LaTeX of one `m:oMath` element, or of a fragment holding one; exported for tests. */
253
+ export const ommlToLatex = (element: XmlElement, prefix = "m"): string => {
254
+ try {
255
+ return new OmmlToLatex(prefix).latex(element);
256
+ } catch {
257
+ // An equation the converter cannot read still says what it says.
258
+ return escapeLatex(plainText(element).replaceAll(/\s+/g, " ").trim());
259
+ }
260
+ };
261
+
262
+ const xmlText = (value: string): string => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
263
+
264
+ const prefixFor = (xml: string, namespaces: readonly string[]): string | undefined => {
265
+ for (const match of xml.matchAll(/\sxmlns:([\w.-]+)\s*=\s*["']([^"']*)["']/g)) {
266
+ if (namespaces.includes(match[2] ?? "")) {
267
+ return match[1];
268
+ }
269
+ }
270
+ return undefined;
271
+ };
272
+
273
+ interface EquationSpan {
274
+ readonly start: number;
275
+ readonly end: number;
276
+ /** An m:oMathPara (one or more display equations) rather than an inline m:oMath. */
277
+ readonly display: boolean;
278
+ }
279
+
280
+ /** The outermost equations in a part, display and inline, in document order. */
281
+ const equationSpans = (xml: string, prefix: string): EquationSpan[] => {
282
+ const tag = new RegExp(`<(/?)${prefix.replaceAll(".", "\\.")}:(oMathPara|oMath)(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^'">])*?(/?)>`, "g");
283
+ const spans: EquationSpan[] = [];
284
+ let depth = 0;
285
+ let open: { start: number; display: boolean } | undefined;
286
+ for (const match of xml.matchAll(tag)) {
287
+ const [whole, closing, name, selfClosing] = match;
288
+ if (closing === "" && depth === 0) {
289
+ open = { start: match.index, display: name === "oMathPara" };
290
+ }
291
+ depth += closing === "/" ? -1 : selfClosing === "/" ? 0 : 1;
292
+ if (depth <= 0 && open !== undefined) {
293
+ spans.push({ ...open, end: match.index + whole.length });
294
+ open = undefined;
295
+ depth = 0;
296
+ }
297
+ }
298
+ return spans;
299
+ };
300
+
301
+ interface RewrittenPart {
302
+ readonly xml: string;
303
+ /** How many equations became LaTeX; none means the part came back as it was. */
304
+ readonly equations: number;
305
+ }
306
+
307
+ /**
308
+ * A part's XML with each equation replaced by a run of its LaTeX: `$…$` inline, `$$…$$` for each equation of a display
309
+ * paragraph. Exported for tests; a part with no Office Math comes back as it was.
310
+ */
311
+ export const withEquationsAsLatex = (xml: string): RewrittenPart => {
312
+ const math = prefixFor(xml, MATH_NAMESPACES);
313
+ if (math === undefined) {
314
+ return { xml, equations: 0 };
315
+ }
316
+ const word = prefixFor(xml, WORD_NAMESPACES) ?? "w";
317
+ const run = (latex: string): string => `<${word}:r><${word}:t xml:space="preserve">${xmlText(latex)}</${word}:t></${word}:r>`;
318
+ let out = "";
319
+ let cursor = 0;
320
+ let equations = 0;
321
+ for (const span of equationSpans(xml, math)) {
322
+ const root = parseXml(xml.slice(span.start, span.end));
323
+ const each = span.display ? childrenNamed(root, `${math}:oMath`) : [root];
324
+ out += xml.slice(cursor, span.start) + each.map((equation) => run(span.display ? `$$${ommlToLatex(equation, math)}$$` : `$${ommlToLatex(equation, math)}$`)).join(`<${word}:r><${word}:br/></${word}:r>`);
325
+ cursor = span.end;
326
+ equations += each.length;
327
+ }
328
+ return { xml: out + xml.slice(cursor), equations };
329
+ };
330
+
331
+ /**
332
+ * What to hand mammoth for a Word document: its path when no part holds an equation (the conversion is then exactly
333
+ * what it always was), else the document rebuilt in memory with every equation as LaTeX text.
334
+ */
335
+ export const mammothInput = async (absPath: string): Promise<{ path: string } | { buffer: Buffer }> => {
336
+ const bytes = new Uint8Array(await readFile(absPath));
337
+ const parts = unzipSync(bytes, { filter: (file) => MATH_PARTS.has(file.name) });
338
+ const rewritten = Object.entries(parts).flatMap(([name, data]): [string, string][] => {
339
+ const xml = strFromU8(data);
340
+ if (!xml.includes(":oMath")) {
341
+ return [];
342
+ }
343
+ const converted = withEquationsAsLatex(xml);
344
+ return converted.equations === 0 ? [] : [[name, converted.xml]];
345
+ });
346
+ if (rewritten.length === 0) {
347
+ return { path: absPath };
348
+ }
349
+ const files = unzipSync(bytes);
350
+ for (const [name, xml] of rewritten) {
351
+ files[name] = strToU8(xml);
352
+ }
353
+ // Stored rather than deflated: the archive lives only as long as mammoth's read of it.
354
+ return { buffer: Buffer.from(zipSync(files, { level: 0 })) };
355
+ };
@@ -1,8 +1,10 @@
1
1
  import { bodyOf, parseHtml } from "@intentic/webq/dom";
2
2
  import { renderMarkdown } from "@intentic/webq/markdown";
3
3
  import type { DerivedDoc, Deriver } from "./deriver.js";
4
+ import { mammothInput } from "./docx-math.js";
4
5
 
5
- /* Word documents: mammoth maps the docx to semantic HTML (headings, lists, tables — its whole reason to exist). */
6
+ /* Word documents: mammoth maps the docx to semantic HTML (headings, lists, tables — its whole reason to exist). It skips
7
+ Word's equations, so a document holding any is handed over with each one rewritten as LaTeX text (docx-math.ts). */
6
8
 
7
9
  // mammoth is 0.26s to load, and only a Word document needs it; see xlsx.ts for why that is loaded inside derive().
8
10
 
@@ -33,10 +35,10 @@ export const notesOf = (messages: readonly { readonly message: string }[]): stri
33
35
 
34
36
  export const docxDeriver: Deriver = {
35
37
  name: "docx",
36
- version: 2,
38
+ version: 3,
37
39
  derive: async (absPath): Promise<DerivedDoc> => {
38
40
  const { default: mammoth } = await import("mammoth");
39
- const converted = await mammoth.convertToHtml({ path: absPath });
41
+ const converted = await mammoth.convertToHtml(await mammothInput(absPath));
40
42
  const body = bodyOf(parseHtml(converted.value));
41
43
  const markdown = body === undefined ? "" : renderMarkdown(body);
42
44
  return { markdown, notes: notesOf(converted.messages) };
@@ -4,8 +4,8 @@ import { imageSize } from "image-size";
4
4
  import type { DerivedDoc, Deriver } from "./deriver.js";
5
5
 
6
6
  // exifr is CommonJS behind a `main` field with no exports map, so a named `import { parse }` type-checks but throws at
7
- // load; the default import is its module.exports under Node and under a bundler alike (the Claude Code plugin bundles
8
- // fileq, and so does the desktop app's compiled file server, and a `createRequire` call is the one form a bundle cannot
7
+ // load; the default import is its module.exports under Node and under a bundler alike (the desktop app's compiled file server
8
+ // bundles fileq, and a `createRequire` call is the one form a bundle cannot
9
9
  // follow: there it failed every derive with "Cannot find module 'exifr'").
10
10
  // oxlint-disable-next-line import/no-named-as-default-member -- the named import this rule asks for is the one that throws at load.
11
11
  const { parse: parseExif } = exifr;
@@ -49,6 +49,15 @@ describe("stripRunningFurniture", () => {
49
49
  expect(stripRunningFurniture(questions).removed).toBe(0);
50
50
  });
51
51
 
52
+ test("keeps a table's header row and separator that every page repeats, while the running header above them goes", () => {
53
+ const pages = [1, 2, 3, 4].map((n) =>
54
+ ["Inventory report", "| SKU | Bin | Count |", "| --- | --- | --- |", `| SKU-${n} | A-${n} | ${n * 10} |`, `Closing note ${WORDS[n]}.`].join("\n"),
55
+ );
56
+ const { pages: kept, removed } = stripRunningFurniture(pages);
57
+ expect(removed).toBe(4);
58
+ expect(kept[1]).toBe("| SKU | Bin | Count |\n| --- | --- | --- |\n| SKU-2 | A-2 | 20 |\nClosing note beta.");
59
+ });
60
+
52
61
  test("a page holding only furniture comes back empty, and the others keep their places", () => {
53
62
  const pages = [1, 2, 3, 4, 5].map((n) => page(n, `Body of ${WORDS[n]}.`));
54
63
  pages[3] = "RFC 9110 HTTP Semantics June 2022\nFielding, et al. Standards Track [Page 4]";
@@ -4,6 +4,8 @@
4
4
  // delete content, so they are left out.
5
5
  // A line is furniture when it sits near a page edge AND recurs at that same edge on most pages (verbatim, or with its
6
6
  // numbers counting with the pages), or it is a page number. Content is never judged by what it says.
7
+ // A markdown table row (pdf-tables.ts) is never furniture: a table carried over pages repeats its header row and
8
+ // separator at the top of each, and taking them would leave the rows below without the header that makes them a table.
7
9
 
8
10
  // How many non-blank lines at each edge of a page can be furniture.
9
11
  const EDGE_LINES = 3;
@@ -100,6 +102,9 @@ export const stripRunningFurniture = (pages: readonly string[]): Destripped => {
100
102
  (running: Set<string>) =>
101
103
  (index: number): boolean => {
102
104
  const line = (lines[index] ?? "").trim();
105
+ if (line.startsWith("|")) {
106
+ return false;
107
+ }
103
108
  const folio = offset !== undefined && BARE_NUMBER.test(line) && Number(line) - page === offset;
104
109
  return folio || signaturesOf(line, page).some((signature) => running.has(signature)) || PAGE_NUMBER.some((shape) => shape.test(line));
105
110
  };