pdf-skryba 0.10.2 → 1.0.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 (112) hide show
  1. package/CHANGELOG.md +58 -3
  2. package/README.md +22 -20
  3. package/dist/first-party/reader.js +1346 -1157
  4. package/dist/first-party/reader.js.map +4 -4
  5. package/dist/first-party.js +8 -7
  6. package/dist/first-party.js.map +2 -2
  7. package/dist/index.js +1370 -1181
  8. package/dist/index.js.map +4 -4
  9. package/dist/index.min.js +4 -4
  10. package/dist/light.js +7 -6
  11. package/dist/light.js.map +3 -3
  12. package/dist/light.min.js +1 -1
  13. package/dist/types/extractor/codecs/ccitt-fax.d.ts +3 -3
  14. package/dist/types/extractor/document-cache.d.ts +1 -1
  15. package/dist/types/extractor/extraction-cost.d.ts +2 -2
  16. package/dist/types/extractor/font-weight.d.ts +1 -6
  17. package/dist/types/extractor/glyph-positions.d.ts +14 -14
  18. package/dist/types/extractor/glyph-runs.d.ts +4 -4
  19. package/dist/types/extractor/glyph-window.d.ts +2 -2
  20. package/dist/types/extractor/pdf-aside-figures.d.ts +1 -1
  21. package/dist/types/extractor/pdf-bands.d.ts +3 -2
  22. package/dist/types/extractor/pdf-ccitt-images.d.ts +1 -1
  23. package/dist/types/extractor/pdf-colour-ours.d.ts +4 -4
  24. package/dist/types/extractor/pdf-decrypt.d.ts +1 -1
  25. package/dist/types/extractor/pdf-document-info.d.ts +4 -4
  26. package/dist/types/extractor/pdf-document-scale.d.ts +1 -1
  27. package/dist/types/extractor/pdf-embedded-images.d.ts +1 -1
  28. package/dist/types/extractor/pdf-facts.d.ts +3 -3
  29. package/dist/types/extractor/pdf-flate-images.d.ts +1 -1
  30. package/dist/types/extractor/pdf-font-bridge.d.ts +3 -3
  31. package/dist/types/extractor/pdf-font-objects.d.ts +6 -7
  32. package/dist/types/extractor/pdf-fonts/font-text.d.ts +6 -6
  33. package/dist/types/extractor/pdf-fonts/predefined-cmaps.d.ts +6 -6
  34. package/dist/types/extractor/pdf-fonts/type1-encoding.d.ts +1 -1
  35. package/dist/types/extractor/pdf-fonts/widths.d.ts +2 -2
  36. package/dist/types/extractor/pdf-glyph-source.d.ts +14 -15
  37. package/dist/types/extractor/pdf-hidden-text.d.ts +1 -5
  38. package/dist/types/extractor/pdf-image-anchors.d.ts +1 -1
  39. package/dist/types/extractor/pdf-image-pixels.d.ts +13 -13
  40. package/dist/types/extractor/pdf-image-refusal.d.ts +2 -2
  41. package/dist/types/extractor/pdf-images.d.ts +4 -4
  42. package/dist/types/extractor/pdf-jpeg-images.d.ts +1 -1
  43. package/dist/types/extractor/pdf-layers.d.ts +1 -1
  44. package/dist/types/extractor/pdf-letter-spacing.d.ts +1 -1
  45. package/dist/types/extractor/pdf-line-breaks.d.ts +2 -2
  46. package/dist/types/extractor/pdf-lines.d.ts +2 -0
  47. package/dist/types/extractor/pdf-links-ours.d.ts +2 -2
  48. package/dist/types/extractor/pdf-links.d.ts +2 -2
  49. package/dist/types/extractor/pdf-model.d.ts +8 -8
  50. package/dist/types/extractor/pdf-objects/bounds.d.ts +4 -4
  51. package/dist/types/extractor/pdf-objects/content.d.ts +4 -4
  52. package/dist/types/extractor/pdf-objects/document.d.ts +14 -14
  53. package/dist/types/extractor/pdf-objects/objects.d.ts +10 -10
  54. package/dist/types/extractor/pdf-objects/parse.d.ts +4 -4
  55. package/dist/types/extractor/pdf-objects/refusal.d.ts +3 -3
  56. package/dist/types/extractor/pdf-objects/streams.d.ts +4 -4
  57. package/dist/types/extractor/pdf-objects/xref.d.ts +3 -3
  58. package/dist/types/extractor/pdf-objstm-guard.d.ts +1 -1
  59. package/dist/types/extractor/pdf-objstm-source.d.ts +1 -1
  60. package/dist/types/extractor/pdf-open.d.ts +1 -1
  61. package/dist/types/extractor/pdf-ops-ours.d.ts +4 -3
  62. package/dist/types/extractor/pdf-ops.d.ts +9 -9
  63. package/dist/types/extractor/pdf-outline.d.ts +3 -3
  64. package/dist/types/extractor/pdf-page-content.d.ts +2 -2
  65. package/dist/types/extractor/pdf-page-figures.d.ts +1 -1
  66. package/dist/types/extractor/pdf-page-plan.d.ts +7 -3
  67. package/dist/types/extractor/pdf-page-stages.d.ts +2 -2
  68. package/dist/types/extractor/pdf-paragraphs.d.ts +1 -1
  69. package/dist/types/extractor/pdf-paths-ours.d.ts +4 -8
  70. package/dist/types/extractor/pdf-reading-order.d.ts +7 -0
  71. package/dist/types/extractor/pdf-reference-ours.d.ts +2 -2
  72. package/dist/types/extractor/pdf-region-order.d.ts +2 -2
  73. package/dist/types/extractor/pdf-scanned.d.ts +2 -2
  74. package/dist/types/extractor/pdf-smask.d.ts +3 -3
  75. package/dist/types/extractor/pdf-source.d.ts +33 -32
  76. package/dist/types/extractor/pdf-stencil-images.d.ts +1 -1
  77. package/dist/types/extractor/pdf-structure.d.ts +1 -1
  78. package/dist/types/extractor/pdf-symbol-page.d.ts +2 -2
  79. package/dist/types/extractor/pdf-symbol-verdict.d.ts +3 -3
  80. package/dist/types/extractor/pdf-table-detector.d.ts +6 -6
  81. package/dist/types/extractor/pdf-table-render.d.ts +1 -1
  82. package/dist/types/extractor/text-writing-direction.d.ts +1 -1
  83. package/dist/types/layout/cell-text.d.ts +1 -1
  84. package/dist/types/layout/column-discriminant.d.ts +2 -2
  85. package/dist/types/layout/column-grid.d.ts +4 -4
  86. package/dist/types/layout/cut-word.d.ts +3 -3
  87. package/dist/types/layout/geometry.d.ts +3 -3
  88. package/dist/types/layout/grid-band.d.ts +3 -3
  89. package/dist/types/layout/gutter.d.ts +6 -6
  90. package/dist/types/layout/heading-sizes.d.ts +2 -2
  91. package/dist/types/layout/hidden-repaints.d.ts +1 -1
  92. package/dist/types/layout/hyphenation.d.ts +1 -1
  93. package/dist/types/layout/image-frontier.d.ts +1 -1
  94. package/dist/types/layout/induced-markers.d.ts +2 -2
  95. package/dist/types/layout/intervals.d.ts +3 -3
  96. package/dist/types/layout/list.d.ts +9 -9
  97. package/dist/types/layout/merged-cells.d.ts +1 -1
  98. package/dist/types/layout/mode.d.ts +2 -2
  99. package/dist/types/layout/superscript.d.ts +1 -1
  100. package/dist/types/layout/text-size.d.ts +1 -1
  101. package/dist/types/layout/vector-grid.d.ts +5 -5
  102. package/dist/types/lib/chunk.d.ts +1 -1
  103. package/dist/types/lib/extent.d.ts +2 -2
  104. package/dist/types/lib/link-schemes.d.ts +1 -1
  105. package/dist/types/lib/pdf-first-party.d.ts +4 -4
  106. package/dist/types/lib/pdf-light.d.ts +2 -2
  107. package/dist/types/lib/reader-options.d.ts +3 -3
  108. package/dist/types/lib/table-leading-bands.d.ts +2 -2
  109. package/dist/types/pipeline/cut-paragraph-repair.d.ts +1 -1
  110. package/dist/types/pipeline/glued-word-repair.d.ts +1 -1
  111. package/dist/types/pipeline/pdf-conservation-source.d.ts +8 -8
  112. package/package.json +1 -1
package/dist/light.js CHANGED
@@ -55,6 +55,7 @@ var findSpaceInsertions = (blocks, respacing) => {
55
55
  const token = findGluedToken(blocks, respacing);
56
56
  if (token === void 0) return void 0;
57
57
  const sourceKeys = respacing.sourceWords.map(conservationKey);
58
+ if (sourceKeys.some((key) => key.length === 0)) return void 0;
58
59
  const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(""));
59
60
  if (token.map((codePoint) => codePoint.key).join("") !== tokenKey || sourceKeys.join("") !== tokenKey)
60
61
  return void 0;
@@ -99,7 +100,7 @@ function gluedWordEdits(page, respacings) {
99
100
  return { edits, repaired };
100
101
  }
101
102
  var countSplitWords = (verdict) => verdict.respacings.filter((respacing) => respacing.kind === "split").length;
102
- var noWorse = (before, after, repaired) => after.lostLetters <= before.lostLetters && (after.decision !== "lost" || before.decision === "lost") && after.decision !== "abstain" && after.gluedWords <= before.gluedWords - repaired && after.unmatchedPageWords <= before.unmatchedPageWords && countSplitWords(after) <= countSplitWords(before);
103
+ var isGluedRepairNoWorse = (before, after, repaired) => after.lostLetters <= before.lostLetters && (after.decision !== "lost" || before.decision === "lost") && after.decision !== "abstain" && after.gluedWords <= before.gluedWords - repaired && after.unmatchedPageWords <= before.unmatchedPageWords && countSplitWords(after) <= countSplitWords(before);
103
104
 
104
105
  // src/pipeline/cut-paragraph-repair.ts
105
106
  import { collapseBlanks } from "doc-ir/internal";
@@ -111,7 +112,7 @@ var DASH = /^\s*[-–—]\s+/u;
111
112
  var NUMBERED = /^\s*(\d{1,2})[.)]\s+/u;
112
113
  var LETTERED = /^\s*[a-zA-Z][.)]\s+/u;
113
114
  var ROMAN = /^\s*[IVXivx]{1,4}[.)]\s+/u;
114
- function markerOf(text) {
115
+ function readMarker(text) {
115
116
  const numbered = NUMBERED.exec(text);
116
117
  if (numbered !== null) return { kind: "ordered", length: numbered[0].length, value: Number(numbered[1]) };
117
118
  for (const [pattern, kind] of [
@@ -150,10 +151,10 @@ var isReadInARow = (tail, head) => {
150
151
  var hasContinuationShape = (firstText, secondText) => {
151
152
  if (firstText.length === 0 || SENTENCE_END.test(firstText)) return false;
152
153
  if (!startsLowercaseWord(secondText)) return false;
153
- if (markerOf(secondText) !== void 0) return false;
154
+ if (readMarker(secondText) !== void 0) return false;
154
155
  return !startsWithSingleLetterToken(secondText);
155
156
  };
156
- var noWorse2 = (before, after) => after.decision !== "abstain" && (after.decision !== "lost" || before.decision === "lost") && after.lostLetters <= before.lostLetters && after.gluedWords <= before.gluedWords && after.unmatchedPageWords <= before.unmatchedPageWords;
157
+ var isParagraphJoinNoWorse = (before, after) => after.decision !== "abstain" && (after.decision !== "lost" || before.decision === "lost") && after.lostLetters <= before.lostLetters && after.gluedWords <= before.gluedWords && after.unmatchedPageWords <= before.unmatchedPageWords;
157
158
  function cutParagraphEdits(page, verdict) {
158
159
  const units = page.units;
159
160
  if (units === void 0 || verdict.decision === "abstain") return { edits: [], joined: 0 };
@@ -245,9 +246,9 @@ export {
245
246
  conservationKey4 as conservationKey,
246
247
  cutParagraphEdits,
247
248
  gluedWordEdits,
248
- noWorse2 as joinNoWorse,
249
+ isGluedRepairNoWorse,
250
+ isParagraphJoinNoWorse,
249
251
  lostWords,
250
- noWorse,
251
252
  placeLostPassages,
252
253
  textConservation,
253
254
  wordKeysOf2 as wordKeysOf
package/dist/light.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/pdf-light.ts", "../src/pipeline/glued-word-repair.ts", "../src/pipeline/cut-paragraph-repair.ts", "../src/layout/list.ts", "../src/pipeline/lost-text-repair.ts"],
4
- "sourcesContent": ["/**\n * The reader-free half of the package (`pdf-skryba/light`): the conservation check of a PDF and the types it speaks\n * in. It must load no PDF reader, no zip and no XML, so that a consumer checking text pays for none of them.\n *\n * How a consumer checks a PDF: it hands back the text it published, block by block (`PublishedPage`), and gets what\n * was lost, invented, glued or split, in the coordinates of its own blocks, never in its markup. The three repairs come\n * back as `PageEdit`s the caller applies itself: the library proves what changes and where; writing the page is the\n * caller's job, since only the caller knows its markup.\n */\n\nexport { conservationKey, lostWords, textConservation, wordKeysOf } from \"doc-ir\";\nexport type {\n ConservationRule,\n ConservationRun,\n ConservationVerdict,\n PageEdit,\n PageWordAt,\n PublishedPage,\n Respacing,\n SourceWordLink,\n} from \"doc-ir\";\n\n/** The three repairs, as DECISIONS: each says what to change and where, and writes nothing. */\nexport { gluedWordEdits, noWorse } from \"../pipeline/glued-word-repair\";\nexport { cutParagraphEdits, noWorse as joinNoWorse } from \"../pipeline/cut-paragraph-repair\";\nexport { placeLostPassages } from \"../pipeline/lost-text-repair\";\nexport type { LostPassage } from \"doc-ir\";\nexport type { LostTextAbstention, LostTextInsertion } from \"../pipeline/lost-text-repair\";\n\n/** The document the reader hands back, and what it could not publish. */\nexport type { IRBlock, IRDoc, IRTab, ImageRef, Inline, InlineMark, TableData } from \"doc-ir\";\nexport type { DocumentNotice, PageLanguage, PdfTextUnreadReason, PictureRefusal } from \"doc-ir\";\nexport { ReaderError } from \"doc-ir\";\nexport type { ReaderCountDetail } from \"doc-ir\";\nexport type { ReaderLimits } from \"doc-ir\";\nexport { MAX_PAYLOAD_BYTES } from \"doc-ir\";\nexport type { VisionPort, VisionResult } from \"doc-ir\";\nexport type { PageLabelOverride } from \"doc-ir\";\n", "/**\n * Proves where a glued page word should be split again, from the PDF's own reading, and hands the spaces back to the\n * caller as edits. The caller applies them and re-checks the page with `noWorse`.\n *\n * THE RULE. A page token is split only when its letters, as the conservation check normalises them, are exactly the\n * concatenation of the two or more consecutive source words the word reading proved. A space goes at each boundary the\n * source gives, and nothing else changes. Anything less certain is left alone and stays counted as glued.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the first of the next, the page may carry\n * non-letters (\u00AB IV.1.1)Vrsta \u00BB). They are split as the source words carry them: the first word's trailing characters,\n * then the next word's leading ones. When the page's characters there are not exactly those, the token is left alone\n * rather than guessed.\n *\n * Offsets are indices in the text the caller published, block by block, so the decision holds for any markup.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One code point of a published block: its text, its letters as the check normalises them, and where it ends in\n * that block's text. */\ninterface CodePoint {\n readonly text: string;\n readonly key: string;\n readonly end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole surrogate pair), so that `end` is a UTF-16 index usable\n * with `slice`. */\nconst CODE_POINT = /[\\s\\S]/gu;\n\nconst splitCodePoints = (text: string): CodePoint[] =>\n [...text.matchAll(CODE_POINT)].map((match) => ({\n text: match[0],\n key: conservationKey(match[0]),\n end: match.index + match[0].length,\n }));\n\n/** The block's words as the check splits them: runs of non-space code points holding at least one letter. The same\n * split as doc-ir's `wordKeysOf`, kept by code point so that offsets can be located. */\nconst splitWords = (codePoints: readonly CodePoint[]): CodePoint[][] => {\n const words: CodePoint[][] = [];\n let current: CodePoint[] = [];\n const closeWord = (): void => {\n if (conservationKey(current.map((codePoint) => codePoint.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const codePoint of codePoints) {\n if (/^\\s+$/u.test(codePoint.text)) closeWord();\n else current.push(codePoint);\n }\n closeWord();\n return words;\n};\n\n/** The leading or trailing characters of a source word that carry no letter. */\nconst readNonLetterEdge = (word: string, side: \"lead\" | \"trail\"): string => {\n const characters = [...word];\n const ordered = side === \"lead\" ? characters : [...characters].reverse();\n const edge: string[] = [];\n for (const character of ordered) {\n if (conservationKey(character).length > 0) break;\n edge.push(character);\n }\n return (side === \"lead\" ? edge : [...edge].reverse()).join(\"\");\n};\n\n/** A renderer may put a zero-width space before a superscript glued to a word. It carries nothing the source says:\n * it is passed over between the words, and the space goes before it. */\nconst removeZeroWidthSpaces = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** The page token a respacing points at, or `undefined` when the respacing is not one glued page word made of two or\n * more source words. */\nconst findGluedToken = (blocks: readonly string[], respacing: Respacing): CodePoint[] | undefined => {\n const pageWord = respacing.pageWords[0];\n if (\n respacing.kind !== \"glued\" ||\n respacing.pageWords.length !== 1 ||\n pageWord === undefined ||\n respacing.sourceWords.length < 2\n )\n return undefined;\n const text = blocks[pageWord.block];\n if (text === undefined) return undefined;\n return splitWords(splitCodePoints(text))[pageWord.word];\n};\n\n/** How many of the non-letter code points between two source words belong to the first word, or `undefined` when they\n * are not exactly the first word's trailing characters followed by the next word's leading ones. */\nconst countTrailingCodePoints = (between: readonly CodePoint[], trail: string, lead: string): number | undefined => {\n if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join(\"\")) !== trail + lead) return undefined;\n let taken = \"\";\n let takenCount = 0;\n while (taken.length < trail.length && takenCount < between.length) {\n taken += removeZeroWidthSpaces(between[takenCount++]!.text);\n }\n return taken === trail ? takenCount : undefined;\n};\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst findSpaceInsertions = (blocks: readonly string[], respacing: Respacing): number[] | undefined => {\n const token = findGluedToken(blocks, respacing);\n if (token === undefined) return undefined;\n const sourceKeys = respacing.sourceWords.map(conservationKey);\n const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(\"\"));\n // Code point by code point, the letters must add up to the token's own (NFKC can join across characters), and the\n // token must be exactly the source words.\n if (token.map((codePoint) => codePoint.key).join(\"\") !== tokenKey || sourceKeys.join(\"\") !== tokenKey)\n return undefined;\n\n const offsets: number[] = [];\n let position = 0;\n let letterCount = 0;\n for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {\n const boundary = letterCount + sourceKeys[sourceIndex]!.length;\n // The code point carrying the first word's last letter must end exactly at the boundary.\n while (position < token.length && letterCount + token[position]!.key.length <= boundary && letterCount < boundary)\n letterCount += token[position++]!.key.length;\n if (letterCount !== boundary) return undefined;\n // The non-letters up to the next word's first letter, split as the source says.\n let nextLetter = position;\n while (nextLetter < token.length && token[nextLetter]!.key.length === 0) nextLetter++;\n const takenCount = countTrailingCodePoints(\n token.slice(position, nextLetter),\n readNonLetterEdge(respacing.sourceWords[sourceIndex]!, \"trail\"),\n readNonLetterEdge(respacing.sourceWords[sourceIndex + 1]!, \"lead\"),\n );\n if (takenCount === undefined) return undefined;\n offsets.push(token[position + takenCount - 1]!.end);\n position += takenCount;\n }\n return offsets;\n};\n\n/** The spaces this check proves, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. It writes nothing: composing a page is the caller's job. */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((respacing) => respacing.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const takenOffsets = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const respacing of glued) {\n const block = respacing.pageWords[0]?.block;\n const offsets = findSpaceInsertions(page.blocks, respacing);\n if (\n offsets === undefined ||\n block === undefined ||\n offsets.some((offset) => takenOffsets.has(`${block}:${offset}`))\n )\n continue;\n for (const atChar of offsets) {\n takenOffsets.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** How many respacings of the verdict are splits: a source word published as several page words. */\nconst countSplitWords = (verdict: ConservationVerdict): number =>\n verdict.respacings.filter((respacing) => respacing.kind === \"split\").length;\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the edits and re-checks,\n * because it writes the page; the rule for keeping or undoing a repair stays here, so that no caller keeps a page\n * that lost a letter. A repair is kept whole or not at all. */\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict, repaired: number): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n countSplitWords(after) <= countSplitWords(before);\n", "/**\n * Proves where two adjacent paragraphs of a published page should be one: the render cut a sentence between them.\n * The edits go back to the caller, who applies them and re-checks the page with `noWorse`.\n *\n * THE RULE. Two units of the page, adjacent and both joinable, become one only when two independent readings agree:\n * - the shape of the published text: the first does not end a sentence and the second starts with a word all in\n * lower case. A second unit that opens on a list marker (\u00AB a. \u00BB, \u00AB iv) \u00BB, \u00AB \u2013 \u00BB) or on a token of one letter is\n * never a continuation;\n * - the PDF itself: the last three words of the first and the first three of the second are six source words in a\n * row in the content stream reading, and the two edge words are set at the same font size. The link from page word\n * to source word is the conservation check's own, so nothing is read twice.\n * Anything else stays as it is. A paragraph cut in two is still all there and searchable; two paragraphs joined by\n * mistake make a sentence that never existed.\n *\n * WHY THE CALLER DECIDES WHAT IS JOINABLE. Measured inside table cells, where each line is a paragraph, the same rule\n * gave 65 joins on 39 French and English PDFs, one of them wrong: two items of a list whose bullet is drawn, not in\n * the text layer, so the second opens on a lower-case word the PDF reads right after the first. A cell packs items\n * without markers far more often than prose does. The paragraphs of one list item, and two cells side by side, stay\n * apart for the same reason.\n *\n * WHY A TOKEN OF ONE LETTER STOPS THE JOIN. A bullet drawn with a symbol font reads as \u00AB x \u00BB in the text layer, a\n * lower-case word the PDF reads right after the line before; the list marker reader does not catch it. Refusing a\n * one-letter opening cost none of the right joins measured. The accepted limit: a real continuation opening on \u00AB il \u00BB,\n * \u00AB y \u00BB, \u00AB \u00E0 \u00BB or \u00AB a \u00BB is refused too.\n * Tried and set aside: reading the font of the opening glyph to recognise a drawn bullet. It needs the font of each run\n * carried through `ConservationRun`, for two joins on one document.\n *\n * The one wrong join left: a page of search results where a snippet is joined to the next result's title, which is\n * in lower case and read right after it. Nothing separates the two without reading the meaning.\n * Two consecutive headings are not joined: measured, the rule would join a report title with \u00AB Executive Summary \u00BB.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { collapseBlanks } from \"doc-ir/internal\";\nimport { markerOf } from \"../layout/list\";\nimport {\n conservationKey,\n type ConservationVerdict,\n type PageEdit,\n type PublishedPage,\n type SourceWordLink,\n} from \"doc-ir\";\n\n/** How many words each side of the cut must bring, read in a row by the PDF (fewer when the unit has fewer).\n * Simulated on 39 French and English PDFs: 41 joins with three words, 48 with one; the stricter window is kept. */\nconst EDGE_WORD_COUNT = 3;\n\nconst SENTENCE_END = /[.:;!?\u00BB\"\u2026)]$/u;\n/** \u00AB suite de la phrase \u00BB yes, \u00AB iPhone \u00BB no. */\nconst startsLowercaseWord = (text: string): boolean => /^\\p{Ll}+(?![\\p{L}\\p{N}])/u.test(text);\n\n/** A unit opening on a token of one letter: a bullet drawn with a symbol font, not a word carried over. */\nconst startsWithSingleLetterToken = (text: string): boolean => conservationKey(text.split(/\\s+/)[0] ?? \"\").length <= 1;\n\n/** The text of one unit as this rule reads it: the texts of its blocks joined by a space, since a line break inside\n * a paragraph ends a block. */\nconst readUnitText = (page: PublishedPage, blocks: readonly number[]): string =>\n collapseBlanks(blocks.map((blockIndex) => page.blocks[blockIndex] ?? \"\").join(\" \"));\n\n/** Whether a page word is linked to a source word; `null` marks a page word the conservation check could not link. */\nconst isSourceWordLink = (link: SourceWordLink | null): link is SourceWordLink => link !== null;\n\n/** Whether the PDF reads `tail` then `head` as source words in a row, the two edge words at one size. */\nconst isReadInARow = (tail: readonly (SourceWordLink | null)[], head: readonly (SourceWordLink | null)[]): boolean => {\n if (tail.length === 0 || head.length === 0) return false;\n const links = [...tail, ...head];\n if (!links.every(isSourceWordLink)) return false;\n for (let index = 1; index < links.length; index++) {\n if (links[index]!.index !== links[index - 1]!.index + 1) return false;\n }\n const tailLast = links[tail.length - 1]!;\n const headFirst = links[tail.length]!;\n return Math.abs(tailLast.lastSize - headFirst.firstSize) < 0.01;\n};\n\n/** Whether the published text reads as one sentence cut in two: the first unit does not end it and the second carries\n * it on, opening neither on a list marker nor on a token of one letter. */\nconst hasContinuationShape = (firstText: string, secondText: string): boolean => {\n if (firstText.length === 0 || SENTENCE_END.test(firstText)) return false;\n if (!startsLowercaseWord(secondText)) return false;\n if (markerOf(secondText) !== undefined) return false;\n return !startsWithSingleLetterToken(secondText);\n};\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the joins and re-checks,\n * because it writes the page; the rule for keeping or undoing them stays here, so that no caller keeps a page that\n * lost a letter. */\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict): boolean =>\n after.decision !== \"abstain\" &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.lostLetters <= before.lostLetters &&\n after.gluedWords <= before.gluedWords &&\n after.unmatchedPageWords <= before.unmatchedPageWords;\n\n/**\n * The joins this rule proves, as edits for the caller to apply to its own page; it writes nothing, since joining two\n * paragraphs is knowledge of one markup.\n *\n * It abstains with no `units` from the caller (it cannot know what a unit is on its own), with a verdict that abstains\n * (the links between page words and source words are then not trusted), for a unit the caller did not mark\n * `joinable`, and when anything of the page sits between the two units.\n */\nexport function cutParagraphEdits(\n page: PublishedPage,\n verdict: ConservationVerdict,\n): { edits: PageEdit[]; joined: number } {\n const units = page.units;\n if (units === undefined || verdict.decision === \"abstain\") return { edits: [], joined: 0 };\n\n const unitSourceLinks: readonly (readonly (SourceWordLink | null)[])[] = units.map((unit) =>\n unit.blocks.flatMap((blockIndex) => verdict.sourceOfPageWords[blockIndex] ?? []),\n );\n\n const isCutAfter = (unitIndex: number): boolean => {\n const firstUnit = units[unitIndex]!;\n const secondUnit = units[unitIndex + 1]!;\n if (!firstUnit.joinable || !secondUnit.joinable || !firstUnit.adjacentToNext) return false;\n const firstText = readUnitText(page, firstUnit.blocks);\n const secondText = readUnitText(page, secondUnit.blocks);\n if (!hasContinuationShape(firstText, secondText)) return false;\n return isReadInARow(\n unitSourceLinks[unitIndex]!.slice(-EDGE_WORD_COUNT),\n unitSourceLinks[unitIndex + 1]!.slice(0, EDGE_WORD_COUNT),\n );\n };\n\n // Right to left, so that applying a join never shifts a unit still to be looked at.\n const edits: PageEdit[] = [];\n for (let unitIndex = units.length - 2; unitIndex >= 0; unitIndex--) {\n if (isCutAfter(unitIndex)) edits.push({ kind: \"join-units\", unit: unitIndex });\n }\n return { edits, joined: edits.length };\n}\n", "/** The lists a PDF never declares, found in the markers and the hanging indent of its lines.\n * Not here: how a list becomes document blocks, nor paragraph grouping, both in `extractor/pdf-paragraphs.ts`. */\nimport { maxOf } from \"../lib/extent\";\nimport { SAME_LINE_PT } from \"./tolerances\";\n\n/**\n * The lists of a PDF, without a model.\n *\n * The rule: an item is a line indented against the body; a list is a run of at least two items, at least half of\n * which carry a readable marker.\n * A marker alone is not enough: a dash opening a sentence, a reference number or a date carry one. The indent alone\n * is not enough either: it finds far too many runs.\n * Chosen bias: the rule under-detects. A missed list loses no text; an invented list lies about the structure.\n * Not kept: the nesting level, drawn from successive quantised indents.\n *\n * BULLETS: A LIST ONLY IN THE SIMPLE CASE. A bullet is what this reader reads worst (a symbol-font letter, a dash glued\n * to its word, a vector disc, a wrapped line taken for an item), and the list is what lets the marker be REMOVED, so a\n * misread marker would make a false list. `listRuns` therefore publishes no run of bullets or dashes: such a run stays\n * paragraphs, the marker kept in the text (nothing removed, nothing lost). Only `bulletRuns` publishes a bulleted list,\n * under its own conditions. Measured on 51 French and English PDFs: 84 lists, 318 items, 0 invented list.\n */\n\n/**\n * The markers. The bullet character is often absent from the text layer (drawn beside it), so the pattern never\n * decides alone: the indent carries the signal and the marker confirms.\n *\n * And when the character IS there, it can be wrong (see the written limits below): a symbol font writes its bullet as\n * \u00AB x \u00BB or as a private code point, and only the font would tell. The font is not read here.\n */\n/** The bullet characters the list reader knows, once. */\nconst BULLET_CHARS = \"\u2022\u25AA\u25E6\u2023\u00B7\u25CF\u2043\";\n/** A line opening on a bullet. Its behaviour, with the four other marker patterns below, is frozen as a matrix in\n * `./list.markers.test.ts`: one line per example, one column per rule, so a drift shows as a cell. */\nexport const BULLET = new RegExp(`^\\\\s*[${BULLET_CHARS}]\\\\s*`, \"u\");\n/**\n * THE BLANK AFTER THE DASH IS REQUIRED, AND THAT IS A DECISION. Word 2007 glues its dash to its word (\u00AB -Ensures\n * Safety of the patient \u00BB), so such items publish as paragraphs.\n *\n * Accepting a glued dash was built and measured, then dropped. Over 39 French and English PDFs, 22 lines open on a\n * dash with NO blank after it, in 3 documents:\n * \u00B7 7 REAL items, where the dash IS the bullet (read on the page image);\n * \u00B7 15 that are not, and the two conditions already hold every one of them out of any list on their own: two\n * wrapped lines continuing \u00AB ALK\u2013positive \u00BB (not indented), \u00AB -30- \u00BB (the end mark of a press release, not\n * indented), and a timeline (\u00AB -Jan 2014--CAAS approves\u2026 \u00BB, 11 lines, never two indented in a row).\n * So the rule produced no false list at all, and it was still dropped. The text of the 7 items already comes out one\n * item per line: the list was a comfort, and its only effect on the text was to REMOVE the leading dash from 7 items.\n * A character of the document less, for nothing findable more. To reopen the day a document really loses something\n * here.\n */\nexport const DASH = /^\\s*[-\u2013\u2014]\\s+/u;\nexport const NUMBERED = /^\\s*(\\d{1,2})[.)]\\s+/u;\nexport const LETTERED = /^\\s*[a-zA-Z][.)]\\s+/u;\nexport const ROMAN = /^\\s*[IVXivx]{1,4}[.)]\\s+/u;\n\n/** The indent is quantised: two lines at 53.8 and 54.1 are at the same level. */\nconst INDENT_QUANTUM_PT = 3;\n/** A lone item is not a list: it is an indented paragraph. */\nconst MIN_ITEMS = 2;\n\n/*\n * WRITTEN LIMIT, NOT A DEFECT TO FIX. A labelling re-read of French and English documents found 35 items published as\n * plain paragraphs, in 8 documents, in three shapes: marked items that are NOT indented (20), several items fused into\n * one block (8), and word markers such as \u00AB Pas 1 : \u00BB (7). No text is lost; it stays searchable.\n * Tried and set aside: a run of CONSECUTIVE numbers (n, n+1\u2026) standing in for the indent. Measured over 34 French and\n * English PDFs: 7 runs, 17 items, no false list, and roughly half of the 20 unindented items, since any block slipped\n * between two items breaks the run. Too much mechanism for that gain. To reopen only if a real document loses\n * something because of a missed list.\n *\n * THREE MORE FAMILIES OF BULLET, MEASURED AND LEFT ALONE (the text already comes out line by line in all three, so the\n * drawn bullet is a comfort, and a marker that is not read is a marker that cannot be removed by mistake). The glued\n * dash is a fourth, written at `DASH` above.\n *\n * 1. **A BULLET PAINTED IN A SYMBOL FONT.** The same glyph comes out three different ways, because a symbol font's\n * glyphs have no character identity and the Unicode value a reader gives them is an accident of the font's cmap (a\n * symbolic TrueType (3,0) cmap maps to 0xF000 + code; ISO 32000-1 \u00A79.6.6.4):\n * SymbolMT 0xB7 \u2192 \u00AB \u2022 \u00BB U+2022, 68 runs, 6 documents: read\n * Wingdings 0xFC \u2192 U+F0FC, 17 runs, 1 document: a private code point, published as a tofu box\n * SymbolMT 0x78 \u2192 \u00AB x \u00BB U+0078, 24 runs, 1 document: a LETTER\n * The character cannot be the test, so the FONT would have to be: over 39 French and English PDFs, every run painted\n * in a font named for a symbol family is 116 runs, 9 fonts, 8 documents, ALL of ONE character and ALL bullets: 0 run\n * of prose, 0 run longer than one character. The discriminant is clean; its price is not. It needs the font name\n * resolved, a new field on every text run, and a new field on every line. Built and measured that way, it gave ONE\n * list of 6 items whose 6 lines already come out one per line. To reopen only if a document loses text for it.\n * Also tried: the private-use range U+E000\u2013U+F8FF as the test, which PyMuPDF4LLM does with U+F0B7 and U+F0A7\n * hard-coded. No new reading, 17 lines on the corpus, all bullets, 0 false; but it catches only the Wingdings\n * shape, not the \u00AB x \u00BB, and it publishes a list in place of lines that are already right.\n *\n * 2. **A DISC DRAWN IN VECTOR, not written.** One document marks 37 lines with a filled circle of 3.7 to 3.8 pt; all 37\n * sit 8.2 to 8.4 pt to the left of their line, on its baseline band (dy 2.1 to 2.6 pt): geometry clean enough to\n * attach. What stops it is elsewhere and it is bigger: every page of that document publishes as ONE TABLE, and a\n * table cell's blocks are built without the paragraph grouping, so no list is ever looked for inside a cell. The\n * marker would change nothing. And the size is no discriminant on its own: another document draws a watch with 484\n * small paths of 26 different sizes, 1.2 to 6.3 pt, 15 of which sit just left of a line.\n * 3. **A WRAPPED LINE TAKEN FOR AN ITEM.** A date published as an item of its own: it is the end of the line above,\n * indented like the items around it and carrying no marker, which the \u00AB half of them marked \u00BB rule lets in. Counted\n * over every item the 39 French and English PDFs publish (78), it is the ONLY one. One case is not a family, and no\n * text is lost.\n */\n\nexport const quantiseIndent = (x: number): number => Math.round(x / INDENT_QUANTUM_PT) * INDENT_QUANTUM_PT;\n\n/**\n * `letter` is a letter or a Roman numeral: \u00AB a. \u00BB, \u00AB iv) \u00BB. It counts as a marker for the list rule, but it never\n * leaves the text. A document list has no marker type, so the only ordered rendering counts 1, 2, 3: stripping \u00AB a. \u00BB\n * would replace every letter with a number, and the letters would be lost. A run of letters is therefore a BULLET list\n * whose items keep \u00AB a. \u00BB in their text: the simplest form that loses nothing and still says \"these are items\". Set\n * aside: no list at all (the items would then read as loose paragraphs), and a marker type in the document model (a\n * change to every renderer for one document).\n */\ntype MarkerKind = \"bullet\" | \"ordered\" | \"letter\";\n\nexport interface Marker {\n kind: MarkerKind;\n /** What the marker occupies at the head of the text, removed from the rendering only when the list's own marker\n * replaces it. */\n length: number;\n /** The number read, on an ordered marker that carries one. */\n value?: number;\n}\n\n/**\n * The marker at the head of a line, if any. A marker is read, not interpreted: \"ordered\" is what a number says, not\n * an inference on intent.\n *\n * It reads the text and nothing else: a marker the text cannot name is a written limit here, not a parameter (see\n * above).\n */\nexport function markerOf(text: string): Marker | undefined {\n const numbered = NUMBERED.exec(text);\n if (numbered !== null) return { kind: \"ordered\", length: numbered[0].length, value: Number(numbered[1]) };\n for (const [pattern, kind] of [\n [BULLET, \"bullet\"],\n [DASH, \"bullet\"],\n [ROMAN, \"letter\"],\n [LETTERED, \"letter\"],\n ] as const) {\n const match = pattern.exec(text);\n if (match !== null) return { kind, length: match[0].length };\n }\n return undefined;\n}\n\nexport interface ListCandidate {\n /** Indented against the document's body: the necessary condition. */\n indented: boolean;\n marker: Marker | undefined;\n /** The block's left edge, its marker INCLUDED: the lowest left of its lines. */\n left?: number;\n /** Where a numbered block's text starts (`itemTextLeft`). Absent: no reading,\n * or two readings that disagree. */\n textLeft?: number;\n /** Present on a paragraph block: where it sits on the page (`blockReading`). */\n geometry?: BlockGeometry;\n /** Present when the block opens on a real bullet character of its own (`blockReading`). */\n bullet?: BulletLead;\n}\n\ninterface ListRun {\n /** Inclusive. */\n start: number;\n /** Inclusive. */\n end: number;\n ordered: boolean;\n}\n\n/**\n * The runs of items in a sequence of consecutive blocks.\n *\n * A block joins the current run when it is indented; the run closes at the first block that is not. It is kept only\n * with at least `MIN_ITEMS` blocks, at least half of them marked. `ordered` follows the majority of the markers read.\n *\n * Tried and set aside: requiring the run's MARKED blocks to share one quantised indent (the literature's \u00AB bullet\n * partner detection AT THE SAME LEVEL \u00BB, of which only the partner is kept). It was written to hold back the one false\n * list the symbol-font marker produced (eight booklet pages imposed on one sheet, columns not cut, markers at 138,\n * 144, 312 and 318 pt). With the markers actually read, the level changes NOTHING over 39 French and English PDFs. A\n * guard that guards nothing is mechanism, so it is not here: to reopen with the page that needs it.\n */\nexport function listRuns(candidates: readonly ListCandidate[]): ListRun[] {\n const runs: ListRun[] = [];\n let start: number | undefined;\n\n const closeRun = (end: number): void => {\n if (start === undefined) return;\n const runCandidates = candidates.slice(start, end + 1);\n const marked = runCandidates.filter((candidate) => candidate.marker !== undefined);\n const countOfKind = (kind: MarkerKind): number =>\n marked.filter((candidate) => candidate.marker?.kind === kind).length;\n // A run of bullets or dashes is no list here (see the header; the simple bulleted case goes through `bulletRuns`).\n // The majority decides, as for `ordered`, and a tie falls on the side of ABSTENTION.\n const isBulleted = countOfKind(\"bullet\") * 2 >= marked.length;\n if (runCandidates.length >= MIN_ITEMS && marked.length * 2 >= runCandidates.length && !isBulleted) {\n const ordered = countOfKind(\"ordered\") * 2 > marked.length;\n runs.push({ start, end, ordered });\n }\n start = undefined;\n };\n\n for (const [index, candidate] of candidates.entries()) {\n if (candidate.indented) {\n start ??= index;\n continue;\n }\n closeRun(index - 1);\n }\n closeRun(candidates.length - 1);\n return runs;\n}\n\n/**\n * THE SIMPLE BULLETED RUN. A run of consecutive paragraph blocks is a bulleted list when ALL of these hold:\n * - at least `MIN_ITEMS` items, each opening on a real bullet character\n * (\u2022 \u25AA \u25E6 \u2023 \u25CF) that is a run of its own: not a dash, not a symbol-font letter\n * (\u00AB x \u00BB), not glued to its text (`blockReading`);\n * - the markers are at one x, the item texts at one x right of the marker, and\n * every wrapped line of an item is at the item-text x, never back at the\n * marker x (each within `BULLET_RUN_MAX_DRIFT_PT`);\n * - GUARD 1: no item carries a second bullet character (bullets laid out in two\n * columns: \u00AB \u25AA Safe Operations \u25AA Delivery of high-quality\u2026 \u00BB);\n * - indentation is NOT required.\n * Anything else stays paragraphs, marker kept in the text.\n *\n * GUARD 2, THE TAIL: an unmarked block at exactly the item-text x directly under the last item, no further below than\n * the list's own line spacing, is that item's continuation (a last item cut in two blocks) and is returned as `tail`.\n * The list's line spacing is the largest line pitch inside its own wrapped items; with none to measure it from, the\n * whole list is REJECTED (bias: abstain). Beyond that spacing the block is a paragraph of its own and the list stays.\n *\n * BULLET_RUN_MAX_DRIFT_PT = 1 pt, starting value to calibrate (the coordinate noise of `SAME_LINE_PT`). Measured over\n * 51 French and English PDFs: 84 runs (318 items) kept, every marker, text and wrapped line within 1 pt; the 14 runs\n * rejected fail on wrapped lines that are not at the text x (12), on item texts at 86.2 against 89.5 pt (1) and on a\n * bullet glued to its text (1); two of them also hold a bullet line inside an item.\n */\nconst BULLET_RUN_MAX_DRIFT_PT = SAME_LINE_PT;\n/** How much farther than the list's own line pitch a tail may start, in points: the same noise. Starting value to calibrate. */\nconst BULLET_TAIL_MAX_GAP_SLACK_PT = 1;\n\nconst BULLET_LEAD_CHARS = new Set([\"\u2022\", \"\u25AA\", \"\u25E6\", \"\u2023\", \"\u25CF\"]);\nconst ANY_BULLET_LEAD = /[\u2022\u25AA\u25E6\u2023\u25CF]/u;\n\n/** The pieces of a line `blockReading` needs: its text, left edge, baseline (decreasing down the page) and its first two items. */\nexport interface BlockLine {\n text: string;\n left: number;\n y: number;\n lead?: { text: string; nextLeft: number };\n}\n\nexport interface BlockGeometry {\n firstLeft: number;\n /** Baseline of the first line, and of the last. */\n firstY: number;\n lastY: number;\n /** The largest distance between two consecutive lines of the block; absent for a one-line block. */\n pitch?: number;\n}\n\nexport interface BulletLead {\n markerLeft: number;\n textLeft: number;\n /** The left edge of every line after the first. */\n continuationLefts: number[];\n /** Another bullet character after the first one, anywhere in the block. */\n secondBullet: boolean;\n}\n\n/** What the simple-bullet rule reads of a block's lines: where the block sits, and its bullet if it opens on a real one of its own. */\nexport function blockReading(lines: readonly BlockLine[]): { geometry?: BlockGeometry; bullet?: BulletLead } {\n const firstLine = lines[0];\n if (firstLine === undefined) return {};\n const lastLine = lines[lines.length - 1]!;\n const pitches = lines.slice(1).map((line, index) => lines[index]!.y - line.y);\n const geometry: BlockGeometry = {\n firstLeft: firstLine.left,\n firstY: firstLine.y,\n lastY: lastLine.y,\n ...(pitches.length > 0 ? { pitch: maxOf(pitches, (pitch) => pitch) } : {}),\n };\n const leadText = firstLine.lead?.text.trim();\n if (\n firstLine.lead === undefined ||\n leadText === undefined ||\n !BULLET_LEAD_CHARS.has(leadText) ||\n !firstLine.text.trimStart().startsWith(leadText)\n )\n return { geometry };\n const textAfterLead = lines\n .map((line) => line.text)\n .join(\" \")\n .trimStart()\n .slice(leadText.length);\n return {\n geometry,\n bullet: {\n markerLeft: firstLine.left,\n textLeft: firstLine.lead.nextLeft,\n continuationLefts: lines.slice(1).map((line) => line.left),\n secondBullet: ANY_BULLET_LEAD.test(textAfterLead),\n },\n };\n}\n\nexport interface BulletRun {\n /** First and last item, inclusive. */\n start: number;\n end: number;\n /** The index of the unmarked block that goes on with the last item, when there is one. */\n tail?: number;\n}\n\nconst isNear = (a: number, b: number): boolean => Math.abs(a - b) <= BULLET_RUN_MAX_DRIFT_PT;\n\n/** The simple bulleted runs among consecutive blocks: see the rule above. */\nexport function bulletRuns(candidates: readonly ListCandidate[]): BulletRun[] {\n const runs: BulletRun[] = [];\n let index = 0;\n while (index < candidates.length) {\n if (candidates[index]!.bullet === undefined) {\n index++;\n continue;\n }\n let end = index;\n while (candidates[end + 1]?.bullet !== undefined) end++;\n const run = checkBulletRun(candidates, index, end);\n if (run !== undefined) runs.push(run);\n index = end + 1;\n }\n return runs;\n}\n\n/** The largest value of a list, or `undefined` for an empty one. */\nconst largestOf = (values: readonly number[]): number | undefined =>\n values.length > 0 ? maxOf(values, (value) => value) : undefined;\n\n/** Are the items' markers at one x, their texts at one x right of the marker, every wrapped line at the text's x, and\n * no second bullet inside an item? */\nconst isSimpleBulletRun = (items: readonly BulletLead[], markerLeft: number, textLeft: number): boolean =>\n textLeft - markerLeft > BULLET_RUN_MAX_DRIFT_PT &&\n items.every(\n (item) =>\n isNear(item.markerLeft, markerLeft) &&\n isNear(item.textLeft, textLeft) &&\n !item.secondBullet &&\n item.continuationLefts.every((left) => isNear(left, textLeft)),\n );\n\n/** The bulleted run from `start` to `end` with its tail, or `undefined` when the run is not simple. */\nconst checkBulletRun = (candidates: readonly ListCandidate[], start: number, end: number): BulletRun | undefined => {\n if (end - start + 1 < MIN_ITEMS) return undefined;\n const items = candidates.slice(start, end + 1).map((candidate) => candidate.bullet!);\n const { markerLeft, textLeft } = items[0]!;\n if (!isSimpleBulletRun(items, markerLeft, textLeft)) return undefined;\n\n const nextCandidate = candidates[end + 1];\n if (\n nextCandidate?.geometry === undefined ||\n nextCandidate.marker !== undefined ||\n nextCandidate.bullet !== undefined ||\n !isNear(nextCandidate.geometry.firstLeft, textLeft)\n )\n return { start, end };\n const pitches = candidates.slice(start, end + 1).flatMap((candidate) => candidate.geometry?.pitch ?? []);\n // ITEMS WITHOUT A WRAPPED LINE STILL HAVE A LINE SPACING: the pitch between two consecutive one-line items\n // (five one-line questions followed by a block at the text's x must stay a list).\n const itemPitches = candidates.slice(start, end).flatMap((candidate, index) => {\n const below = candidates[start + index + 1]!.geometry;\n const itemGeometry = candidate.geometry;\n return itemGeometry === undefined || below === undefined\n ? []\n : [itemGeometry.lastY - below.firstY].filter((distance) => distance > 0);\n });\n const spacing = largestOf(pitches) ?? largestOf(itemPitches);\n if (spacing === undefined) return undefined;\n const gap = candidates[end]!.geometry!.lastY - nextCandidate.geometry.firstY;\n // The tail lies BELOW the last item: a block read after a jump up the page (another column) is never one.\n return gap > 0 && gap <= spacing + BULLET_TAIL_MAX_GAP_SLACK_PT ? { start, end, tail: end + 1 } : { start, end };\n};\n\n/**\n * HOW FAR A BLOCK MAY SIT FROM AN ITEM'S TEXT AND STILL BE ALIGNED ON IT. Starting value to calibrate: 1 pt, the\n * coordinate-noise tolerance. Measured on French and English PDFs:\n * - aligned: an item's text start read twice (after its marker, on its second line) agrees to 0.05 pt on 53 of 64\n * items; the one unnumbered block that belongs to an item (the last line of an item split off) is 0.0 pt from its\n * item's text;\n * - not aligned: the nearest disagreement is 1.3 pt, on a form, and the nearest block after an item that does not\n * continue it is 6.7 pt away.\n * Gap between the two populations: 0.05 to 1.3 pt.\n */\nconst ITEM_ALIGN_TOLERANCE_PT = SAME_LINE_PT;\n\n/**\n * WHERE AN ITEM'S TEXT STARTS, from two independent readings: where the text resumes after the marker on the first\n * line, and the left of the second line (a hanging indent). Both present, they must agree, or this abstains; one\n * present, it stands alone. Abstaining means no block can continue the item.\n */\nexport function itemTextLeft(readings: {\n afterMarker?: number | undefined;\n secondLine?: number | undefined;\n}): number | undefined {\n const { afterMarker, secondLine } = readings;\n if (afterMarker !== undefined && secondLine !== undefined)\n return Math.abs(afterMarker - secondLine) <= ITEM_ALIGN_TOLERANCE_PT ? afterMarker : undefined;\n return afterMarker ?? secondLine;\n}\n\n/** What an ordered run becomes: blocks left as paragraphs, and lists whose items\n * are block indices, a numbered block first. */\nexport type OrderedPiece = { kind: \"paragraph\"; index: number } | { kind: \"list\"; first: number; items: number[][] };\n\n/**\n * AN ORDERED RUN PUBLISHES THE DOCUMENT'S OWN NUMBERS.\n *\n * An ordered list counts its items, so an unnumbered block let in as an item shifts every number after it (\u00AB 1. \u00BB to\n * \u00AB 5. \u00BB published as 3 to 7). The left edge of a block includes its marker, and an unnumbered block (a letter or a\n * bullet has no number) is never an item of its own:\n * - aligned on the TEXT of the item before it (the number further left), it is that item's next paragraph;\n * - otherwise it closes the list; before the first number it stays a paragraph.\n * GUARD: a list is kept only when its numbers follow exactly (first, first+1\u2026, no gap, no duplicate) over at least\n * `MIN_ITEMS` items. Otherwise every block stays a paragraph, its written number in its text. The PDF libraries\n * studied keep the written number; none checks the sequence.\n *\n * Set aside: letting in a NON-indented block aligned on the item's text. It would put a \u00AB b) \u00BB and a \u00AB c) \u00BB back into\n * their item, but the same geometry is a body paragraph after a list whose markers hang in the margin (three body\n * paragraphs 0.0 pt from the text of the bullet before them). Nothing tells the two apart, so only blocks already in\n * the run are candidates.\n */\nexport function orderedPieces(candidates: readonly ListCandidate[], start: number, end: number): OrderedPiece[] {\n const pieces: OrderedPiece[] = [];\n let items: number[][] = [];\n let numbers: number[] = [];\n let openingItem: ListCandidate | undefined;\n\n const closeList = (): void => {\n const isExactSequence = numbers.every((number, index) => number === numbers[0]! + index);\n if (items.length >= MIN_ITEMS && isExactSequence) pieces.push({ kind: \"list\", first: numbers[0]!, items });\n else for (const index of items.flat()) pieces.push({ kind: \"paragraph\", index });\n items = [];\n numbers = [];\n openingItem = undefined;\n };\n\n for (let index = start; index <= end; index++) {\n const candidate = candidates[index]!;\n const value = candidate.marker?.kind === \"ordered\" ? candidate.marker.value : undefined;\n if (value !== undefined) {\n items.push([index]);\n numbers.push(value);\n openingItem = candidate;\n } else if (openingItem !== undefined && continuesItem(openingItem, candidate)) {\n items[items.length - 1]!.push(index);\n } else {\n closeList();\n pieces.push({ kind: \"paragraph\", index });\n }\n }\n closeList();\n return pieces;\n}\n\n/** Whether `block` is the next paragraph of `item`: aligned on the item's text, which starts right of its marker. */\nconst continuesItem = (item: ListCandidate, block: ListCandidate): boolean =>\n item.left !== undefined &&\n item.textLeft !== undefined &&\n block.left !== undefined &&\n item.textLeft - item.left > ITEM_ALIGN_TOLERANCE_PT &&\n Math.abs(block.left - item.textLeft) <= ITEM_ALIGN_TOLERANCE_PT;\n", "/**\n * Decides where a passage the render lost goes back into the published page, as its own unit between the two adjacent\n * units that hold its source neighbours. It hands the caller the edit and the letters it puts back, or why it\n * abstains; applying the edit, re-checking the page and keeping or undoing the repair are the caller's.\n *\n * THE RULE. A lost passage is a run of consecutive source words neither reading of the conservation check found. Its\n * neighbours are the source words right before and right after it. It goes back only when:\n * - each neighbour is a word the page matched (not an alternate text, a list number or a re-spacing: those have no\n * single place in the page);\n * - the neighbour before is the last word of a paragraph or heading unit, the one after the first word of the next\n * unit, with nothing between the two;\n * - at the start or the end of the document, the one neighbour opens the page's first block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB: a loss inside a paragraph, a table cell or a list, or an\n * image between the two paragraphs. A paragraph cut in the wrong place reads as if nothing were wrong; a \u00AB N characters\n * are not published \u00BB notice does not.\n *\n * THE UNDO IS THE CALLER'S. This module hands back only what the re-check needs: for each passage placed, the edit\n * and the number of letters it puts back (`LostTextInsertion`); for each passage left out, why\n * (`LostTextAbstention`). A caller that wants an exact repair keeps it only when the lost letters drop by exactly the\n * letters handed back and nothing else of the page moves.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are read in content stream order. Measured on\n * 871 paragraphs cut from 45 renders: 426 put back with the page's letters exactly as before, 22 put back elsewhere,\n * where the content stream reads them; some of those read better than the render did, some worse (a second column read\n * line by line). Tried and not kept: also requiring the blocks on each side to follow the source's order. It caught 8\n * of the 22 and cost 17 exact repairs. Text back in the page is what search needs; a paragraph slightly out of place\n * is the lesser defect.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back: a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back, for the caller's accounting. */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Whether `later` sits strictly after `earlier` in the page's reading order (block, then word). */\nconst isAfterInPageOrder = (later: PageWordAt, earlier: PageWordAt): boolean =>\n later.block > earlier.block || (later.block === earlier.block && later.word > earlier.word);\n\n/** Where each lost passage goes, as an edit for the caller to apply, or why it goes nowhere.\n *\n * It reasons on the page's units (`PublishedPage.units`), never on markup. The reason of each abstention travels to the\n * caller, so that a reader of the result knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container`, the same\n * answer as for a page whose anchors sit where a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = wordCountByBlock.length - 1;\n const findUnitOfBlock = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const findAnchorUnit = (anchor: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const unitIndex = findUnitOfBlock(anchor.block);\n if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The loss must sit at the unit's edge: the anchor before is the unit's last word, the anchor after its first.\n const neighbourBlock = side === \"before\" ? anchor.block + 1 : anchor.block - 1;\n const isAtEdge = side === \"before\" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;\n if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return \"loss-inside-block\";\n return unitIndex;\n };\n\n /** The unit the passage goes after (`-1`: before the first unit), or why it goes nowhere. */\n const placePassage = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\" && !isAfterInPageOrder(after, before))\n return \"anchors-out-of-order\";\n const unitBefore = before === \"document-edge\" ? undefined : findAnchorUnit(before, \"before\");\n if (typeof unitBefore === \"string\") return unitBefore;\n const unitAfter = after === \"document-edge\" ? undefined : findAnchorUnit(after, \"after\");\n if (typeof unitAfter === \"string\") return unitAfter;\n // At the start of the document, the passage goes before the unit that opens the page's first block.\n if (unitBefore === undefined) {\n if (unitAfter === undefined || after === \"document-edge\" || after.block !== 0) return \"no-anchor\";\n return unitAfter - 1;\n }\n // At the end of the document, the passage goes after the unit that closes the page's last block.\n if (unitAfter === undefined) {\n if (before === \"document-edge\" || before.block !== lastBlock) return \"no-anchor\";\n return unitBefore;\n }\n if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return \"blocks-not-adjacent\";\n return unitBefore;\n };\n\n for (const passage of passages) {\n const placement = placePassage(passage);\n if (typeof placement === \"string\") {\n abstentions.push(placement);\n continue;\n }\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: placement, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey(word).length, 0),\n });\n }\n return { insertions, abstentions };\n}\n"],
5
- "mappings": ";AAUA,SAAS,mBAAAA,kBAAiB,WAAW,kBAAkB,cAAAC,mBAAkB;;;ACQzE,SAAS,uBAAoG;AAY7G,IAAM,aAAa;AAEnB,IAAM,kBAAkB,CAAC,SACvB,CAAC,GAAG,KAAK,SAAS,UAAU,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,EAC7C,MAAM,MAAM,CAAC;AAAA,EACb,KAAK,gBAAgB,MAAM,CAAC,CAAC;AAAA,EAC7B,KAAK,MAAM,QAAQ,MAAM,CAAC,EAAE;AAC9B,EAAE;AAIJ,IAAM,aAAa,CAAC,eAAoD;AACtE,QAAM,QAAuB,CAAC;AAC9B,MAAI,UAAuB,CAAC;AAC5B,QAAM,YAAY,MAAY;AAC5B,QAAI,gBAAgB,QAAQ,IAAI,CAAC,cAAc,UAAU,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAG,OAAM,KAAK,OAAO;AACvG,cAAU,CAAC;AAAA,EACb;AACA,aAAW,aAAa,YAAY;AAClC,QAAI,SAAS,KAAK,UAAU,IAAI,EAAG,WAAU;AAAA,QACxC,SAAQ,KAAK,SAAS;AAAA,EAC7B;AACA,YAAU;AACV,SAAO;AACT;AAGA,IAAM,oBAAoB,CAAC,MAAc,SAAmC;AAC1E,QAAM,aAAa,CAAC,GAAG,IAAI;AAC3B,QAAM,UAAU,SAAS,SAAS,aAAa,CAAC,GAAG,UAAU,EAAE,QAAQ;AACvE,QAAM,OAAiB,CAAC;AACxB,aAAW,aAAa,SAAS;AAC/B,QAAI,gBAAgB,SAAS,EAAE,SAAS,EAAG;AAC3C,SAAK,KAAK,SAAS;AAAA,EACrB;AACA,UA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AU;AAC9B,UAAM,YAAY,aAAa,OAAO;AACtC,QAAI,OAAO,cAAc,UAAU;AACjC,kBAAY,KAAK,SAAS;AAC1B;AAAA,IACF;AACA,eAAW,KAAK;AAAA,MACd,MAAM,EAAE,MAAM,qBAAqB,MAAM,WAAW,MAAM,QAAQ,YAAY,KAAK,GAAG,EAAE;AAAA,MACxF,SAAS,QAAQ,YAAY,OAAO,CAAC,aAAa,SAAS,cAAcA,iBAAgB,IAAI,EAAE,QAAQ,CAAC;AAAA,IAC1G,CAAC;AAAA,EACH;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;;;AJ/FA,SAAS,mBAAmB;AAG5B,SAAS,yBAAyB;",
6
- "names": ["conservationKey", "wordKeysOf", "conservationKey", "noWorse", "conservationKey"]
4
+ "sourcesContent": ["/**\n * The reader-free half of the package (`pdf-skryba/light`): the conservation check of a PDF and the types it speaks\n * in. It must load no PDF reader, no zip and no XML, so that a consumer checking text pays for none of them.\n *\n * How a consumer checks a PDF: it hands back the text it published, block by block (`PublishedPage`), and gets what\n * was lost, invented, glued or split, in the coordinates of its own blocks, never in its markup. The three repairs come\n * back as `PageEdit`s the caller applies itself: the library proves what changes and where; writing the page is the\n * caller's job, since only the caller knows its markup.\n */\n\nexport { conservationKey, lostWords, textConservation, wordKeysOf } from \"doc-ir\";\nexport type {\n ConservationRule,\n ConservationRun,\n ConservationVerdict,\n PageEdit,\n PageWordAt,\n PublishedPage,\n Respacing,\n SourceWordLink,\n} from \"doc-ir\";\n\n/** The three repairs, as DECISIONS: each says what to change and where, and writes nothing. */\nexport { gluedWordEdits, isGluedRepairNoWorse } from \"../pipeline/glued-word-repair\";\nexport { cutParagraphEdits, isParagraphJoinNoWorse } from \"../pipeline/cut-paragraph-repair\";\nexport { placeLostPassages } from \"../pipeline/lost-text-repair\";\nexport type { LostPassage } from \"doc-ir\";\nexport type { LostTextAbstention, LostTextInsertion } from \"../pipeline/lost-text-repair\";\n\n/** The document the reader hands back, and what it could not publish. */\nexport type { IRBlock, IRDoc, IRTab, ImageRef, Inline, InlineMark, TableData } from \"doc-ir\";\nexport type { DocumentNotice, PageLanguage, PdfTextUnreadReason, PictureRefusal } from \"doc-ir\";\nexport { ReaderError } from \"doc-ir\";\nexport type { ReaderCountDetail } from \"doc-ir\";\nexport type { ReaderLimits } from \"doc-ir\";\nexport { MAX_PAYLOAD_BYTES } from \"doc-ir\";\nexport type { VisionPort, VisionResult } from \"doc-ir\";\nexport type { PageLabelOverride } from \"doc-ir\";\n", "/**\n * Proves where a glued page word should be split again, from the PDF's own reading, and hands the spaces back to the\n * caller as edits. The caller applies them and re-checks the page with `isGluedRepairNoWorse`.\n *\n * THE RULE. A page token is split only when its letters, as the conservation check normalises them, are exactly the\n * concatenation of the two or more consecutive source words the word reading proved. A space goes at each boundary the\n * source gives, and nothing else changes. Anything less certain is left alone and stays counted as glued.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the first of the next, the page may carry\n * non-letters (\u00AB IV.1.1)Vrsta \u00BB). They are split as the source words carry them: the first word's trailing characters,\n * then the next word's leading ones. When the page's characters there are not exactly those, the token is left alone\n * rather than guessed.\n *\n * Offsets are indices in the text the caller published, block by block, so the decision holds for any markup.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One code point of a published block: its text, its letters as the check normalises them, and where it ends in\n * that block's text. */\ninterface CodePoint {\n readonly text: string;\n readonly key: string;\n readonly end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole surrogate pair), so that `end` is a UTF-16 index usable\n * with `slice`. */\nconst CODE_POINT = /[\\s\\S]/gu;\n\nconst splitCodePoints = (text: string): CodePoint[] =>\n [...text.matchAll(CODE_POINT)].map((match) => ({\n text: match[0],\n key: conservationKey(match[0]),\n end: match.index + match[0].length,\n }));\n\n/** The block's words as the check splits them: runs of non-space code points holding at least one letter. The same\n * split as doc-ir's `wordKeysOf`, kept by code point so that offsets can be located. */\nconst splitWords = (codePoints: readonly CodePoint[]): CodePoint[][] => {\n const words: CodePoint[][] = [];\n let current: CodePoint[] = [];\n const closeWord = (): void => {\n if (conservationKey(current.map((codePoint) => codePoint.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const codePoint of codePoints) {\n if (/^\\s+$/u.test(codePoint.text)) closeWord();\n else current.push(codePoint);\n }\n closeWord();\n return words;\n};\n\n/** The leading or trailing characters of a source word that carry no letter. */\nconst readNonLetterEdge = (word: string, side: \"lead\" | \"trail\"): string => {\n const characters = [...word];\n const ordered = side === \"lead\" ? characters : [...characters].reverse();\n const edge: string[] = [];\n for (const character of ordered) {\n if (conservationKey(character).length > 0) break;\n edge.push(character);\n }\n return (side === \"lead\" ? edge : [...edge].reverse()).join(\"\");\n};\n\n/** A renderer may put a zero-width space before a superscript glued to a word. It carries nothing the source says:\n * it is passed over between the words, and the space goes before it. */\nconst removeZeroWidthSpaces = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** The page token a respacing points at, or `undefined` when the respacing is not one glued page word made of two or\n * more source words. */\nconst findGluedToken = (blocks: readonly string[], respacing: Respacing): CodePoint[] | undefined => {\n const pageWord = respacing.pageWords[0];\n if (\n respacing.kind !== \"glued\" ||\n respacing.pageWords.length !== 1 ||\n pageWord === undefined ||\n respacing.sourceWords.length < 2\n )\n return undefined;\n const text = blocks[pageWord.block];\n if (text === undefined) return undefined;\n return splitWords(splitCodePoints(text))[pageWord.word];\n};\n\n/** How many of the non-letter code points between two source words belong to the first word, or `undefined` when they\n * are not exactly the first word's trailing characters followed by the next word's leading ones. */\nconst countTrailingCodePoints = (between: readonly CodePoint[], trail: string, lead: string): number | undefined => {\n if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join(\"\")) !== trail + lead) return undefined;\n let taken = \"\";\n let takenCount = 0;\n while (taken.length < trail.length && takenCount < between.length) {\n taken += removeZeroWidthSpaces(between[takenCount++]!.text);\n }\n return taken === trail ? takenCount : undefined;\n};\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst findSpaceInsertions = (blocks: readonly string[], respacing: Respacing): number[] | undefined => {\n const token = findGluedToken(blocks, respacing);\n if (token === undefined) return undefined;\n const sourceKeys = respacing.sourceWords.map(conservationKey);\n // A source word with no letter marks no boundary of its own: first, its boundary would fall before the token's first\n // code point (no character to put a space after); between two words, it would double the space of its neighbour's.\n if (sourceKeys.some((key) => key.length === 0)) return undefined;\n const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(\"\"));\n // Code point by code point, the letters must add up to the token's own (NFKC can join across characters), and the\n // token must be exactly the source words.\n if (token.map((codePoint) => codePoint.key).join(\"\") !== tokenKey || sourceKeys.join(\"\") !== tokenKey)\n return undefined;\n\n const offsets: number[] = [];\n let position = 0;\n let letterCount = 0;\n for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {\n const boundary = letterCount + sourceKeys[sourceIndex]!.length;\n // The code point carrying the first word's last letter must end exactly at the boundary.\n while (position < token.length && letterCount + token[position]!.key.length <= boundary && letterCount < boundary)\n letterCount += token[position++]!.key.length;\n if (letterCount !== boundary) return undefined;\n // The non-letters up to the next word's first letter, split as the source says.\n let nextLetter = position;\n while (nextLetter < token.length && token[nextLetter]!.key.length === 0) nextLetter++;\n const takenCount = countTrailingCodePoints(\n token.slice(position, nextLetter),\n readNonLetterEdge(respacing.sourceWords[sourceIndex]!, \"trail\"),\n readNonLetterEdge(respacing.sourceWords[sourceIndex + 1]!, \"lead\"),\n );\n if (takenCount === undefined) return undefined;\n offsets.push(token[position + takenCount - 1]!.end);\n position += takenCount;\n }\n return offsets;\n};\n\n/** The spaces this check proves, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. It writes nothing: composing a page is the caller's job. */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((respacing) => respacing.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const takenOffsets = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const respacing of glued) {\n const block = respacing.pageWords[0]?.block;\n const offsets = findSpaceInsertions(page.blocks, respacing);\n if (\n offsets === undefined ||\n block === undefined ||\n offsets.some((offset) => takenOffsets.has(`${block}:${offset}`))\n )\n continue;\n for (const atChar of offsets) {\n takenOffsets.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** How many respacings of the verdict are splits: a source word published as several page words. */\nconst countSplitWords = (verdict: ConservationVerdict): number =>\n verdict.respacings.filter((respacing) => respacing.kind === \"split\").length;\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the edits and re-checks,\n * because it writes the page; the rule for keeping or undoing a repair stays here, so that no caller keeps a page\n * that lost a letter. A repair is kept whole or not at all. */\nexport const isGluedRepairNoWorse = (\n before: ConservationVerdict,\n after: ConservationVerdict,\n repaired: number,\n): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n countSplitWords(after) <= countSplitWords(before);\n", "/**\n * Proves where two adjacent paragraphs of a published page should be one: the render cut a sentence between them.\n * The edits go back to the caller, who applies them and re-checks the page with `isParagraphJoinNoWorse`.\n *\n * THE RULE. Two units of the page, adjacent and both joinable, become one only when two independent readings agree:\n * - the shape of the published text: the first does not end a sentence and the second starts with a word all in\n * lower case. A second unit that opens on a list marker (\u00AB a. \u00BB, \u00AB iv) \u00BB, \u00AB \u2013 \u00BB) or on a token of one letter is\n * never a continuation;\n * - the PDF itself: the last three words of the first and the first three of the second are six source words in a\n * row in the content stream reading, and the two edge words are set at the same font size. The link from page word\n * to source word is the conservation check's own, so nothing is read twice.\n * Anything else stays as it is. A paragraph cut in two is still all there and searchable; two paragraphs joined by\n * mistake make a sentence that never existed.\n *\n * WHY THE CALLER DECIDES WHAT IS JOINABLE. Measured inside table cells, where each line is a paragraph, the same rule\n * gave 65 joins on 39 French and English PDFs, one of them wrong: two items of a list whose bullet is drawn, not in\n * the text layer, so the second opens on a lower-case word the PDF reads right after the first. A cell packs items\n * without markers far more often than prose does. The paragraphs of one list item, and two cells side by side, stay\n * apart for the same reason.\n *\n * WHY A TOKEN OF ONE LETTER STOPS THE JOIN. A bullet drawn with a symbol font reads as \u00AB x \u00BB in the text layer, a\n * lower-case word the PDF reads right after the line before; the list marker reader does not catch it. Refusing a\n * one-letter opening cost none of the right joins measured. The accepted limit: a real continuation opening on \u00AB il \u00BB,\n * \u00AB y \u00BB, \u00AB \u00E0 \u00BB or \u00AB a \u00BB is refused too.\n * Tried and set aside: reading the font of the opening glyph to recognise a drawn bullet. It needs the font of each run\n * carried through `ConservationRun`, for two joins on one document.\n *\n * The one wrong join left: a page of search results where a snippet is joined to the next result's title, which is\n * in lower case and read right after it. Nothing separates the two without reading the meaning.\n * Two consecutive headings are not joined: measured, the rule would join a report title with \u00AB Executive Summary \u00BB.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { collapseBlanks } from \"doc-ir/internal\";\nimport { readMarker } from \"../layout/list\";\nimport {\n conservationKey,\n type ConservationVerdict,\n type PageEdit,\n type PublishedPage,\n type SourceWordLink,\n} from \"doc-ir\";\n\n/** How many words each side of the cut must bring, read in a row by the PDF (fewer when the unit has fewer).\n * Simulated on 39 French and English PDFs: 41 joins with three words, 48 with one; the stricter window is kept. */\nconst EDGE_WORD_COUNT = 3;\n\nconst SENTENCE_END = /[.:;!?\u00BB\"\u2026)]$/u;\n/** \u00AB suite de la phrase \u00BB yes, \u00AB iPhone \u00BB no. */\nconst startsLowercaseWord = (text: string): boolean => /^\\p{Ll}+(?![\\p{L}\\p{N}])/u.test(text);\n\n/** A unit opening on a token of one letter: a bullet drawn with a symbol font, not a word carried over. */\nconst startsWithSingleLetterToken = (text: string): boolean => conservationKey(text.split(/\\s+/)[0] ?? \"\").length <= 1;\n\n/** The text of one unit as this rule reads it: the texts of its blocks joined by a space, since a line break inside\n * a paragraph ends a block. */\nconst readUnitText = (page: PublishedPage, blocks: readonly number[]): string =>\n collapseBlanks(blocks.map((blockIndex) => page.blocks[blockIndex] ?? \"\").join(\" \"));\n\n/** Whether a page word is linked to a source word; `null` marks a page word the conservation check could not link. */\nconst isSourceWordLink = (link: SourceWordLink | null): link is SourceWordLink => link !== null;\n\n/** Whether the PDF reads `tail` then `head` as source words in a row, the two edge words at one size. */\nconst isReadInARow = (tail: readonly (SourceWordLink | null)[], head: readonly (SourceWordLink | null)[]): boolean => {\n if (tail.length === 0 || head.length === 0) return false;\n const links = [...tail, ...head];\n if (!links.every(isSourceWordLink)) return false;\n for (let index = 1; index < links.length; index++) {\n if (links[index]!.index !== links[index - 1]!.index + 1) return false;\n }\n const tailLast = links[tail.length - 1]!;\n const headFirst = links[tail.length]!;\n return Math.abs(tailLast.lastSize - headFirst.firstSize) < 0.01;\n};\n\n/** Whether the published text reads as one sentence cut in two: the first unit does not end it and the second carries\n * it on, opening neither on a list marker nor on a token of one letter. */\nconst hasContinuationShape = (firstText: string, secondText: string): boolean => {\n if (firstText.length === 0 || SENTENCE_END.test(firstText)) return false;\n if (!startsLowercaseWord(secondText)) return false;\n if (readMarker(secondText) !== undefined) return false;\n return !startsWithSingleLetterToken(secondText);\n};\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the joins and re-checks,\n * because it writes the page; the rule for keeping or undoing them stays here, so that no caller keeps a page that\n * lost a letter. */\nexport const isParagraphJoinNoWorse = (before: ConservationVerdict, after: ConservationVerdict): boolean =>\n after.decision !== \"abstain\" &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.lostLetters <= before.lostLetters &&\n after.gluedWords <= before.gluedWords &&\n after.unmatchedPageWords <= before.unmatchedPageWords;\n\n/**\n * The joins this rule proves, as edits for the caller to apply to its own page; it writes nothing, since joining two\n * paragraphs is knowledge of one markup.\n *\n * It abstains with no `units` from the caller (it cannot know what a unit is on its own), with a verdict that abstains\n * (the links between page words and source words are then not trusted), for a unit the caller did not mark\n * `joinable`, and when anything of the page sits between the two units.\n */\nexport function cutParagraphEdits(\n page: PublishedPage,\n verdict: ConservationVerdict,\n): { edits: PageEdit[]; joined: number } {\n const units = page.units;\n if (units === undefined || verdict.decision === \"abstain\") return { edits: [], joined: 0 };\n\n const unitSourceLinks: readonly (readonly (SourceWordLink | null)[])[] = units.map((unit) =>\n unit.blocks.flatMap((blockIndex) => verdict.sourceOfPageWords[blockIndex] ?? []),\n );\n\n const isCutAfter = (unitIndex: number): boolean => {\n const firstUnit = units[unitIndex]!;\n const secondUnit = units[unitIndex + 1]!;\n if (!firstUnit.joinable || !secondUnit.joinable || !firstUnit.adjacentToNext) return false;\n const firstText = readUnitText(page, firstUnit.blocks);\n const secondText = readUnitText(page, secondUnit.blocks);\n if (!hasContinuationShape(firstText, secondText)) return false;\n return isReadInARow(\n unitSourceLinks[unitIndex]!.slice(-EDGE_WORD_COUNT),\n unitSourceLinks[unitIndex + 1]!.slice(0, EDGE_WORD_COUNT),\n );\n };\n\n // Right to left, so that applying a join never shifts a unit still to be looked at.\n const edits: PageEdit[] = [];\n for (let unitIndex = units.length - 2; unitIndex >= 0; unitIndex--) {\n if (isCutAfter(unitIndex)) edits.push({ kind: \"join-units\", unit: unitIndex });\n }\n return { edits, joined: edits.length };\n}\n", "/** The lists a PDF never declares, found in the markers and the hanging indent of its lines.\n * Not here: how a list becomes document blocks, nor paragraph grouping, both in `extractor/pdf-paragraphs.ts`. */\nimport { computeMaximum } from \"../lib/extent\";\nimport { SAME_LINE_PT } from \"./tolerances\";\n\n/**\n * The lists of a PDF, without a model.\n *\n * The rule: an item is a line indented against the body; a list is a run of at least two items, at least half of\n * which carry a readable marker.\n * A marker alone is not enough: a dash opening a sentence, a reference number or a date carry one. The indent alone\n * is not enough either: it finds far too many runs.\n * Chosen bias: the rule under-detects. A missed list loses no text; an invented list lies about the structure.\n * Not kept: the nesting level, drawn from successive quantised indents.\n *\n * BULLETS: A LIST ONLY IN THE SIMPLE CASE. A bullet is what this reader reads worst (a symbol-font letter, a dash glued\n * to its word, a vector disc, a wrapped line taken for an item), and the list is what lets the marker be REMOVED, so a\n * misread marker would make a false list. `findListRuns` therefore publishes no run of bullets or dashes: such a run stays\n * paragraphs, the marker kept in the text (nothing removed, nothing lost). Only `findBulletRuns` publishes a bulleted list,\n * under its own conditions. Measured on 51 French and English PDFs: 84 lists, 318 items, 0 invented list.\n */\n\n/**\n * The markers. The bullet character is often absent from the text layer (drawn beside it), so the pattern never\n * decides alone: the indent carries the signal and the marker confirms.\n *\n * And when the character IS there, it can be wrong (see the written limits below): a symbol font writes its bullet as\n * \u00AB x \u00BB or as a private code point, and only the font would tell. The font is not read here.\n */\n/** The bullet characters the list reader knows, once. */\nconst BULLET_CHARS = \"\u2022\u25AA\u25E6\u2023\u00B7\u25CF\u2043\";\n/** A line opening on a bullet. Its behaviour, with the four other marker patterns below, is frozen as a matrix in\n * `./list.markers.test.ts`: one line per example, one column per rule, so a drift shows as a cell. */\nexport const BULLET = new RegExp(`^\\\\s*[${BULLET_CHARS}]\\\\s*`, \"u\");\n/**\n * THE BLANK AFTER THE DASH IS REQUIRED, AND THAT IS A DECISION. Word 2007 glues its dash to its word (\u00AB -Ensures\n * Safety of the patient \u00BB), so such items publish as paragraphs.\n *\n * Accepting a glued dash was built and measured, then dropped. Over 39 French and English PDFs, 22 lines open on a\n * dash with NO blank after it, in 3 documents:\n * \u00B7 7 REAL items, where the dash IS the bullet (read on the page image);\n * \u00B7 15 that are not, and the two conditions already hold every one of them out of any list on their own: two\n * wrapped lines continuing \u00AB ALK\u2013positive \u00BB (not indented), \u00AB -30- \u00BB (the end mark of a press release, not\n * indented), and a timeline (\u00AB -Jan 2014--CAAS approves\u2026 \u00BB, 11 lines, never two indented in a row).\n * So the rule produced no false list at all, and it was still dropped. The text of the 7 items already comes out one\n * item per line: the list was a comfort, and its only effect on the text was to REMOVE the leading dash from 7 items.\n * A character of the document less, for nothing findable more. To reopen the day a document really loses something\n * here.\n */\nexport const DASH = /^\\s*[-\u2013\u2014]\\s+/u;\nexport const NUMBERED = /^\\s*(\\d{1,2})[.)]\\s+/u;\nexport const LETTERED = /^\\s*[a-zA-Z][.)]\\s+/u;\nexport const ROMAN = /^\\s*[IVXivx]{1,4}[.)]\\s+/u;\n\n/** The indent is quantised: two lines at 53.8 and 54.1 are at the same level. */\nconst INDENT_QUANTUM_PT = 3;\n/** A lone item is not a list: it is an indented paragraph. */\nconst MIN_ITEMS = 2;\n\n/*\n * WRITTEN LIMIT, NOT A DEFECT TO FIX. A labelling re-read of French and English documents found 35 items published as\n * plain paragraphs, in 8 documents, in three shapes: marked items that are NOT indented (20), several items fused into\n * one block (8), and word markers such as \u00AB Pas 1 : \u00BB (7). No text is lost; it stays searchable.\n * Tried and set aside: a run of CONSECUTIVE numbers (n, n+1\u2026) standing in for the indent. Measured over 34 French and\n * English PDFs: 7 runs, 17 items, no false list, and roughly half of the 20 unindented items, since any block slipped\n * between two items breaks the run. Too much mechanism for that gain. To reopen only if a real document loses\n * something because of a missed list.\n *\n * THREE MORE FAMILIES OF BULLET, MEASURED AND LEFT ALONE (the text already comes out line by line in all three, so the\n * drawn bullet is a comfort, and a marker that is not read is a marker that cannot be removed by mistake). The glued\n * dash is a fourth, written at `DASH` above.\n *\n * 1. **A BULLET PAINTED IN A SYMBOL FONT.** The same glyph comes out three different ways, because a symbol font's\n * glyphs have no character identity and the Unicode value a reader gives them is an accident of the font's cmap (a\n * symbolic TrueType (3,0) cmap maps to 0xF000 + code; ISO 32000-1 \u00A79.6.6.4):\n * SymbolMT 0xB7 \u2192 \u00AB \u2022 \u00BB U+2022, 68 runs, 6 documents: read\n * Wingdings 0xFC \u2192 U+F0FC, 17 runs, 1 document: a private code point, published as a tofu box\n * SymbolMT 0x78 \u2192 \u00AB x \u00BB U+0078, 24 runs, 1 document: a LETTER\n * The character cannot be the test, so the FONT would have to be: over 39 French and English PDFs, every run painted\n * in a font named for a symbol family is 116 runs, 9 fonts, 8 documents, ALL of ONE character and ALL bullets: 0 run\n * of prose, 0 run longer than one character. The discriminant is clean; its price is not. It needs the font name\n * resolved, a new field on every text run, and a new field on every line. Built and measured that way, it gave ONE\n * list of 6 items whose 6 lines already come out one per line. To reopen only if a document loses text for it.\n * Also tried: the private-use range U+E000\u2013U+F8FF as the test, which PyMuPDF4LLM does with U+F0B7 and U+F0A7\n * hard-coded. No new reading, 17 lines on the corpus, all bullets, 0 false; but it catches only the Wingdings\n * shape, not the \u00AB x \u00BB, and it publishes a list in place of lines that are already right.\n *\n * 2. **A DISC DRAWN IN VECTOR, not written.** One document marks 37 lines with a filled circle of 3.7 to 3.8 pt; all 37\n * sit 8.2 to 8.4 pt to the left of their line, on its baseline band (dy 2.1 to 2.6 pt): geometry clean enough to\n * attach. What stops it is elsewhere and it is bigger: every page of that document publishes as ONE TABLE, and a\n * table cell's blocks are built without the paragraph grouping, so no list is ever looked for inside a cell. The\n * marker would change nothing. And the size is no discriminant on its own: another document draws a watch with 484\n * small paths of 26 different sizes, 1.2 to 6.3 pt, 15 of which sit just left of a line.\n * 3. **A WRAPPED LINE TAKEN FOR AN ITEM.** A date published as an item of its own: it is the end of the line above,\n * indented like the items around it and carrying no marker, which the \u00AB half of them marked \u00BB rule lets in. Counted\n * over every item the 39 French and English PDFs publish (78), it is the ONLY one. One case is not a family, and no\n * text is lost.\n */\n\nexport const quantiseIndent = (x: number): number => Math.round(x / INDENT_QUANTUM_PT) * INDENT_QUANTUM_PT;\n\n/**\n * `letter` is a letter or a Roman numeral: \u00AB a. \u00BB, \u00AB iv) \u00BB. It counts as a marker for the list rule, but it never\n * leaves the text. A document list has no marker type, so the only ordered rendering counts 1, 2, 3: stripping \u00AB a. \u00BB\n * would replace every letter with a number, and the letters would be lost. A run of letters is therefore a BULLET list\n * whose items keep \u00AB a. \u00BB in their text: the simplest form that loses nothing and still says \"these are items\". Set\n * aside: no list at all (the items would then read as loose paragraphs), and a marker type in the document model (a\n * change to every renderer for one document).\n */\ntype MarkerKind = \"bullet\" | \"ordered\" | \"letter\";\n\nexport interface Marker {\n kind: MarkerKind;\n /** What the marker occupies at the head of the text, removed from the rendering only when the list's own marker\n * replaces it. */\n length: number;\n /** The number read, on an ordered marker that carries one. */\n value?: number;\n}\n\n/**\n * The marker at the head of a line, if any. A marker is read, not interpreted: \"ordered\" is what a number says, not\n * an inference on intent.\n *\n * It reads the text and nothing else: a marker the text cannot name is a written limit here, not a parameter (see\n * above).\n */\nexport function readMarker(text: string): Marker | undefined {\n const numbered = NUMBERED.exec(text);\n if (numbered !== null) return { kind: \"ordered\", length: numbered[0].length, value: Number(numbered[1]) };\n for (const [pattern, kind] of [\n [BULLET, \"bullet\"],\n [DASH, \"bullet\"],\n [ROMAN, \"letter\"],\n [LETTERED, \"letter\"],\n ] as const) {\n const match = pattern.exec(text);\n if (match !== null) return { kind, length: match[0].length };\n }\n return undefined;\n}\n\nexport interface ListCandidate {\n /** Indented against the document's body: the necessary condition. */\n isIndented: boolean;\n marker: Marker | undefined;\n /** The block's left edge, its marker INCLUDED: the lowest left of its lines. */\n left?: number;\n /** Where a numbered block's text starts (`findItemTextLeft`). Absent: no reading,\n * or two readings that disagree. */\n textLeft?: number;\n /** Present on a paragraph block: where it sits on the page (`readBlockLayout`). */\n geometry?: BlockGeometry;\n /** Present when the block opens on a real bullet character of its own (`readBlockLayout`). */\n bullet?: BulletLead;\n}\n\ninterface ListRun {\n /** Inclusive. */\n start: number;\n /** Inclusive. */\n end: number;\n isOrdered: boolean;\n}\n\n/**\n * The runs of items in a sequence of consecutive blocks.\n *\n * A block joins the current run when it is indented; the run closes at the first block that is not. It is kept only\n * with at least `MIN_ITEMS` blocks, at least half of them marked. `ordered` follows the majority of the markers read.\n *\n * Tried and set aside: requiring the run's MARKED blocks to share one quantised indent (the literature's \u00AB bullet\n * partner detection AT THE SAME LEVEL \u00BB, of which only the partner is kept). It was written to hold back the one false\n * list the symbol-font marker produced (eight booklet pages imposed on one sheet, columns not cut, markers at 138,\n * 144, 312 and 318 pt). With the markers actually read, the level changes NOTHING over 39 French and English PDFs. A\n * guard that guards nothing is mechanism, so it is not here: to reopen with the page that needs it.\n */\nexport function findListRuns(candidates: readonly ListCandidate[]): ListRun[] {\n const runs: ListRun[] = [];\n let start: number | undefined;\n\n const closeRun = (end: number): void => {\n if (start === undefined) return;\n const runCandidates = candidates.slice(start, end + 1);\n const marked = runCandidates.filter((candidate) => candidate.marker !== undefined);\n const countOfKind = (kind: MarkerKind): number =>\n marked.filter((candidate) => candidate.marker?.kind === kind).length;\n // A run of bullets or dashes is no list here (see the header; the simple bulleted case goes through `findBulletRuns`).\n // The majority decides, as for `ordered`, and a tie falls on the side of ABSTENTION.\n const isBulleted = countOfKind(\"bullet\") * 2 >= marked.length;\n if (runCandidates.length >= MIN_ITEMS && marked.length * 2 >= runCandidates.length && !isBulleted) {\n const ordered = countOfKind(\"ordered\") * 2 > marked.length;\n runs.push({ start, end, isOrdered: ordered });\n }\n start = undefined;\n };\n\n for (const [index, candidate] of candidates.entries()) {\n if (candidate.isIndented) {\n start ??= index;\n continue;\n }\n closeRun(index - 1);\n }\n closeRun(candidates.length - 1);\n return runs;\n}\n\n/**\n * THE SIMPLE BULLETED RUN. A run of consecutive paragraph blocks is a bulleted list when ALL of these hold:\n * - at least `MIN_ITEMS` items, each opening on a real bullet character\n * (\u2022 \u25AA \u25E6 \u2023 \u25CF) that is a run of its own: not a dash, not a symbol-font letter\n * (\u00AB x \u00BB), not glued to its text (`readBlockLayout`);\n * - the markers are at one x, the item texts at one x right of the marker, and\n * every wrapped line of an item is at the item-text x, never back at the\n * marker x (each within `BULLET_RUN_MAX_DRIFT_PT`);\n * - GUARD 1: no item carries a second bullet character (bullets laid out in two\n * columns: \u00AB \u25AA Safe Operations \u25AA Delivery of high-quality\u2026 \u00BB);\n * - indentation is NOT required.\n * Anything else stays paragraphs, marker kept in the text.\n *\n * GUARD 2, THE TAIL: an unmarked block at exactly the item-text x directly under the last item, no further below than\n * the list's own line spacing, is that item's continuation (a last item cut in two blocks) and is returned as `tail`.\n * The list's line spacing is the largest line pitch inside its own wrapped items; with none to measure it from, the\n * whole list is REJECTED (bias: abstain). Beyond that spacing the block is a paragraph of its own and the list stays.\n *\n * BULLET_RUN_MAX_DRIFT_PT = 1 pt, starting value to calibrate (the coordinate noise of `SAME_LINE_PT`). Measured over\n * 51 French and English PDFs: 84 runs (318 items) kept, every marker, text and wrapped line within 1 pt; the 14 runs\n * rejected fail on wrapped lines that are not at the text x (12), on item texts at 86.2 against 89.5 pt (1) and on a\n * bullet glued to its text (1); two of them also hold a bullet line inside an item.\n */\nconst BULLET_RUN_MAX_DRIFT_PT = SAME_LINE_PT;\n/** How much farther than the list's own line pitch a tail may start, in points: the same noise. Starting value to calibrate. */\nconst BULLET_TAIL_MAX_GAP_SLACK_PT = 1;\n\nconst BULLET_LEAD_CHARS = new Set([\"\u2022\", \"\u25AA\", \"\u25E6\", \"\u2023\", \"\u25CF\"]);\nconst ANY_BULLET_LEAD = /[\u2022\u25AA\u25E6\u2023\u25CF]/u;\n\n/** The pieces of a line `readBlockLayout` needs: its text, left edge, baseline (decreasing down the page) and its first two items. */\nexport interface BlockLine {\n text: string;\n left: number;\n y: number;\n lead?: { text: string; nextLeft: number };\n}\n\nexport interface BlockGeometry {\n firstLeft: number;\n /** Baseline of the first line, and of the last. */\n firstY: number;\n lastY: number;\n /** The largest distance between two consecutive lines of the block; absent for a one-line block. */\n pitch?: number;\n}\n\nexport interface BulletLead {\n markerLeft: number;\n textLeft: number;\n /** The left edge of every line after the first. */\n continuationLefts: number[];\n /** Another bullet character after the first one, anywhere in the block. */\n hasSecondBullet: boolean;\n}\n\n/** What the simple-bullet rule reads of a block's lines: where the block sits, and its bullet if it opens on a real one of its own. */\nexport function readBlockLayout(lines: readonly BlockLine[]): { geometry?: BlockGeometry; bullet?: BulletLead } {\n const firstLine = lines[0];\n if (firstLine === undefined) return {};\n const lastLine = lines[lines.length - 1]!;\n const pitches = lines.slice(1).map((line, index) => lines[index]!.y - line.y);\n const geometry: BlockGeometry = {\n firstLeft: firstLine.left,\n firstY: firstLine.y,\n lastY: lastLine.y,\n ...(pitches.length > 0 ? { pitch: computeMaximum(pitches, (pitch) => pitch) } : {}),\n };\n const leadText = firstLine.lead?.text.trim();\n if (\n firstLine.lead === undefined ||\n leadText === undefined ||\n !BULLET_LEAD_CHARS.has(leadText) ||\n !firstLine.text.trimStart().startsWith(leadText)\n )\n return { geometry };\n const textAfterLead = lines\n .map((line) => line.text)\n .join(\" \")\n .trimStart()\n .slice(leadText.length);\n return {\n geometry,\n bullet: {\n markerLeft: firstLine.left,\n textLeft: firstLine.lead.nextLeft,\n continuationLefts: lines.slice(1).map((line) => line.left),\n hasSecondBullet: ANY_BULLET_LEAD.test(textAfterLead),\n },\n };\n}\n\nexport interface BulletRun {\n /** First and last item, inclusive. */\n start: number;\n end: number;\n /** The index of the unmarked block that goes on with the last item, when there is one. */\n tail?: number;\n}\n\nconst isNear = (a: number, b: number): boolean => Math.abs(a - b) <= BULLET_RUN_MAX_DRIFT_PT;\n\n/** The simple bulleted runs among consecutive blocks: see the rule above. */\nexport function findBulletRuns(candidates: readonly ListCandidate[]): BulletRun[] {\n const runs: BulletRun[] = [];\n let index = 0;\n while (index < candidates.length) {\n if (candidates[index]!.bullet === undefined) {\n index++;\n continue;\n }\n let end = index;\n while (candidates[end + 1]?.bullet !== undefined) end++;\n const run = checkBulletRun(candidates, index, end);\n if (run !== undefined) runs.push(run);\n index = end + 1;\n }\n return runs;\n}\n\n/** The largest value of a list, or `undefined` for an empty one. */\nconst largestOf = (values: readonly number[]): number | undefined =>\n values.length > 0 ? computeMaximum(values, (value) => value) : undefined;\n\n/** Are the items' markers at one x, their texts at one x right of the marker, every wrapped line at the text's x, and\n * no second bullet inside an item? */\nconst isSimpleBulletRun = (items: readonly BulletLead[], markerLeft: number, textLeft: number): boolean =>\n textLeft - markerLeft > BULLET_RUN_MAX_DRIFT_PT &&\n items.every(\n (item) =>\n isNear(item.markerLeft, markerLeft) &&\n isNear(item.textLeft, textLeft) &&\n !item.hasSecondBullet &&\n item.continuationLefts.every((left) => isNear(left, textLeft)),\n );\n\n/** The bulleted run from `start` to `end` with its tail, or `undefined` when the run is not simple. */\nconst checkBulletRun = (candidates: readonly ListCandidate[], start: number, end: number): BulletRun | undefined => {\n if (end - start + 1 < MIN_ITEMS) return undefined;\n const items = candidates.slice(start, end + 1).map((candidate) => candidate.bullet!);\n const { markerLeft, textLeft } = items[0]!;\n if (!isSimpleBulletRun(items, markerLeft, textLeft)) return undefined;\n\n const nextCandidate = candidates[end + 1];\n if (\n nextCandidate?.geometry === undefined ||\n nextCandidate.marker !== undefined ||\n nextCandidate.bullet !== undefined ||\n !isNear(nextCandidate.geometry.firstLeft, textLeft)\n )\n return { start, end };\n const pitches = candidates.slice(start, end + 1).flatMap((candidate) => candidate.geometry?.pitch ?? []);\n // ITEMS WITHOUT A WRAPPED LINE STILL HAVE A LINE SPACING: the pitch between two consecutive one-line items\n // (five one-line questions followed by a block at the text's x must stay a list).\n const itemPitches = candidates.slice(start, end).flatMap((candidate, index) => {\n const below = candidates[start + index + 1]!.geometry;\n const itemGeometry = candidate.geometry;\n return itemGeometry === undefined || below === undefined\n ? []\n : [itemGeometry.lastY - below.firstY].filter((distance) => distance > 0);\n });\n const spacing = largestOf(pitches) ?? largestOf(itemPitches);\n if (spacing === undefined) return undefined;\n const gap = candidates[end]!.geometry!.lastY - nextCandidate.geometry.firstY;\n // The tail lies BELOW the last item: a block read after a jump up the page (another column) is never one.\n return gap > 0 && gap <= spacing + BULLET_TAIL_MAX_GAP_SLACK_PT ? { start, end, tail: end + 1 } : { start, end };\n};\n\n/**\n * HOW FAR A BLOCK MAY SIT FROM AN ITEM'S TEXT AND STILL BE ALIGNED ON IT. Starting value to calibrate: 1 pt, the\n * coordinate-noise tolerance. Measured on French and English PDFs:\n * - aligned: an item's text start read twice (after its marker, on its second line) agrees to 0.05 pt on 53 of 64\n * items; the one unnumbered block that belongs to an item (the last line of an item split off) is 0.0 pt from its\n * item's text;\n * - not aligned: the nearest disagreement is 1.3 pt, on a form, and the nearest block after an item that does not\n * continue it is 6.7 pt away.\n * Gap between the two populations: 0.05 to 1.3 pt.\n */\nconst ITEM_ALIGN_TOLERANCE_PT = SAME_LINE_PT;\n\n/**\n * WHERE AN ITEM'S TEXT STARTS, from two independent readings: where the text resumes after the marker on the first\n * line, and the left of the second line (a hanging indent). Both present, they must agree, or this abstains; one\n * present, it stands alone. Abstaining means no block can continue the item.\n */\nexport function findItemTextLeft(readings: {\n afterMarker?: number | undefined;\n secondLine?: number | undefined;\n}): number | undefined {\n const { afterMarker, secondLine } = readings;\n if (afterMarker !== undefined && secondLine !== undefined)\n return Math.abs(afterMarker - secondLine) <= ITEM_ALIGN_TOLERANCE_PT ? afterMarker : undefined;\n return afterMarker ?? secondLine;\n}\n\n/** What an ordered run becomes: blocks left as paragraphs, and lists whose items\n * are block indices, a numbered block first. */\nexport type OrderedPiece = { kind: \"paragraph\"; index: number } | { kind: \"list\"; first: number; items: number[][] };\n\n/**\n * AN ORDERED RUN PUBLISHES THE DOCUMENT'S OWN NUMBERS.\n *\n * An ordered list counts its items, so an unnumbered block let in as an item shifts every number after it (\u00AB 1. \u00BB to\n * \u00AB 5. \u00BB published as 3 to 7). The left edge of a block includes its marker, and an unnumbered block (a letter or a\n * bullet has no number) is never an item of its own:\n * - aligned on the TEXT of the item before it (the number further left), it is that item's next paragraph;\n * - otherwise it closes the list; before the first number it stays a paragraph.\n * GUARD: a list is kept only when its numbers follow exactly (first, first+1\u2026, no gap, no duplicate) over at least\n * `MIN_ITEMS` items. Otherwise every block stays a paragraph, its written number in its text. The PDF libraries\n * studied keep the written number; none checks the sequence.\n *\n * Set aside: letting in a NON-indented block aligned on the item's text. It would put a \u00AB b) \u00BB and a \u00AB c) \u00BB back into\n * their item, but the same geometry is a body paragraph after a list whose markers hang in the margin (three body\n * paragraphs 0.0 pt from the text of the bullet before them). Nothing tells the two apart, so only blocks already in\n * the run are candidates.\n */\nexport function collectOrderedPieces(candidates: readonly ListCandidate[], start: number, end: number): OrderedPiece[] {\n const pieces: OrderedPiece[] = [];\n let items: number[][] = [];\n let numbers: number[] = [];\n let openingItem: ListCandidate | undefined;\n\n const closeList = (): void => {\n const isExactSequence = numbers.every((number, index) => number === numbers[0]! + index);\n if (items.length >= MIN_ITEMS && isExactSequence) pieces.push({ kind: \"list\", first: numbers[0]!, items });\n else for (const index of items.flat()) pieces.push({ kind: \"paragraph\", index });\n items = [];\n numbers = [];\n openingItem = undefined;\n };\n\n for (let index = start; index <= end; index++) {\n const candidate = candidates[index]!;\n const value = candidate.marker?.kind === \"ordered\" ? candidate.marker.value : undefined;\n if (value !== undefined) {\n items.push([index]);\n numbers.push(value);\n openingItem = candidate;\n } else if (openingItem !== undefined && continuesItem(openingItem, candidate)) {\n items[items.length - 1]!.push(index);\n } else {\n closeList();\n pieces.push({ kind: \"paragraph\", index });\n }\n }\n closeList();\n return pieces;\n}\n\n/** Whether `block` is the next paragraph of `item`: aligned on the item's text, which starts right of its marker. */\nconst continuesItem = (item: ListCandidate, block: ListCandidate): boolean =>\n item.left !== undefined &&\n item.textLeft !== undefined &&\n block.left !== undefined &&\n item.textLeft - item.left > ITEM_ALIGN_TOLERANCE_PT &&\n Math.abs(block.left - item.textLeft) <= ITEM_ALIGN_TOLERANCE_PT;\n", "/**\n * Decides where a passage the render lost goes back into the published page, as its own unit between the two adjacent\n * units that hold its source neighbours. It hands the caller the edit and the letters it puts back, or why it\n * abstains; applying the edit, re-checking the page and keeping or undoing the repair are the caller's.\n *\n * THE RULE. A lost passage is a run of consecutive source words neither reading of the conservation check found. Its\n * neighbours are the source words right before and right after it. It goes back only when:\n * - each neighbour is a word the page matched (not an alternate text, a list number or a re-spacing: those have no\n * single place in the page);\n * - the neighbour before is the last word of a paragraph or heading unit, the one after the first word of the next\n * unit, with nothing between the two;\n * - at the start or the end of the document, the one neighbour opens the page's first block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB: a loss inside a paragraph, a table cell or a list, or an\n * image between the two paragraphs. A paragraph cut in the wrong place reads as if nothing were wrong; a \u00AB N characters\n * are not published \u00BB notice does not.\n *\n * THE UNDO IS THE CALLER'S. This module hands back only what the re-check needs: for each passage placed, the edit\n * and the number of letters it puts back (`LostTextInsertion`); for each passage left out, why\n * (`LostTextAbstention`). A caller that wants an exact repair keeps it only when the lost letters drop by exactly the\n * letters handed back and nothing else of the page moves.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are read in content stream order. Measured on\n * 871 paragraphs cut from 45 renders: 426 put back with the page's letters exactly as before, 22 put back elsewhere,\n * where the content stream reads them; some of those read better than the render did, some worse (a second column read\n * line by line). Tried and not kept: also requiring the blocks on each side to follow the source's order. It caught 8\n * of the 22 and cost 17 exact repairs. Text back in the page is what search needs; a paragraph slightly out of place\n * is the lesser defect.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back: a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back, for the caller's accounting. */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Whether `later` sits strictly after `earlier` in the page's reading order (block, then word). */\nconst isAfterInPageOrder = (later: PageWordAt, earlier: PageWordAt): boolean =>\n later.block > earlier.block || (later.block === earlier.block && later.word > earlier.word);\n\n/** Where each lost passage goes, as an edit for the caller to apply, or why it goes nowhere.\n *\n * It reasons on the page's units (`PublishedPage.units`), never on markup. The reason of each abstention travels to the\n * caller, so that a reader of the result knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container`, the same\n * answer as for a page whose anchors sit where a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = wordCountByBlock.length - 1;\n const findUnitOfBlock = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const findAnchorUnit = (anchor: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const unitIndex = findUnitOfBlock(anchor.block);\n if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The loss must sit at the unit's edge: the anchor before is the unit's last word, the anchor after its first.\n const neighbourBlock = side === \"before\" ? anchor.block + 1 : anchor.block - 1;\n const isAtEdge = side === \"before\" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;\n if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return \"loss-inside-block\";\n return unitIndex;\n };\n\n /** The unit the passage goes after (`-1`: before the first unit), or why it goes nowhere. */\n const placePassage = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\" && !isAfterInPageOrder(after, before))\n return \"anchors-out-of-order\";\n const unitBefore = before === \"document-edge\" ? undefined : findAnchorUnit(before, \"before\");\n if (typeof unitBefore === \"string\") return unitBefore;\n const unitAfter = after === \"document-edge\" ? undefined : findAnchorUnit(after, \"after\");\n if (typeof unitAfter === \"string\") return unitAfter;\n // At the start of the document, the passage goes before the unit that opens the page's first block.\n if (unitBefore === undefined) {\n if (unitAfter === undefined || after === \"document-edge\" || after.block !== 0) return \"no-anchor\";\n return unitAfter - 1;\n }\n // At the end of the document, the passage goes after the unit that closes the page's last block.\n if (unitAfter === undefined) {\n if (before === \"document-edge\" || before.block !== lastBlock) return \"no-anchor\";\n return unitBefore;\n }\n if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return \"blocks-not-adjacent\";\n return unitBefore;\n };\n\n for (const passage of passages) {\n const placement = placePassage(passage);\n if (typeof placement === \"string\") {\n abstentions.push(placement);\n continue;\n }\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: placement, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey(word).length, 0),\n });\n }\n return { insertions, abstentions };\n}\n"],
5
+ "mappings": ";AAUA,SAAS,mBAAAA,kBAAiB,WAAW,kBAAkB,cAAAC,mBAAkB;;;ACQzE,SAAS,uBAAoG;AAY7G,IAAM,aAAa;AAEnB,IAAM,kBAAkB,CAAC,SACvB,CAAC,GAAG,KAAK,SAAS,UAAU,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,EAC7C,MAAM,MAAM,CAAC;AAAA,EACb,KAAK,gBAAgB,MAAM,CAAC,CAAC;AAAA,EAC7B,KAAK,MAAM,QAAQ,MAAM,CAAC,EAAE;AAC9B,EAAE;AAIJ,IAAM,aAAa,CAAC,eAAoD;AACtE,QAAM,QAAuB,CAAC;AAC9B,MAAI,UAAuB,CAAC;AAC5B,QAAM,YAAY,MAAY;AAC5B,QAAI,gBAAgB,QAAQ,IAAI,CAAC,cAAc,UAAU,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAG,OAAM,KAAK,OAAO;AACvG,cA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AAM,aAAa,WAAW,kBAAkB,SAAY,eAAe,QAAQ,QAAQ;AAC3F,QAAI,OAAO,eAAe,SAAU,QAAO;AAC3C,UAAM,YAAY,UAAU,kBAAkB,SAAY,eAAe,OAAO,OAAO;AACvF,QAAI,OAAO,cAAc,SAAU,QAAO;AAE1C,QAAI,eAAe,QAAW;AAC5B,UAAI,cAAc,UAAa,UAAU,mBAAmB,MAAM,UAAU,EAAG,QAAO;AACtF,aAAO,YAAY;AAAA,IACrB;AAEA,QAAI,cAAc,QAAW;AAC3B,UAAI,WAAW,mBAAmB,OAAO,UAAU,UAAW,QAAO;AACrE,aAAO;AAAA,IACT;AACA,QAAI,cAAc,aAAa,KAAK,QAAQ,UAAU,GAAG,mBAAmB,KAAM,QAAO;AACzF,WAAO;AAAA,EACT;AAEA,aAAW,WAAW,UAAU;AAC9B,UAAM,YAAY,aAAa,OAAO;AACtC,QAAI,OAAO,cAAc,UAAU;AACjC,kBAAY,KAAK,SAAS;AAC1B;AAAA,IACF;AACA,eAAW,KAAK;AAAA,MACd,MAAM,EAAE,MAAM,qBAAqB,MAAM,WAAW,MAAM,QAAQ,YAAY,KAAK,GAAG,EAAE;AAAA,MACxF,SAAS,QAAQ,YAAY,OAAO,CAAC,aAAa,SAAS,cAAcA,iBAAgB,IAAI,EAAE,QAAQ,CAAC;AAAA,IAC1G,CAAC;AAAA,EACH;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;;;AJ/FA,SAAS,mBAAmB;AAG5B,SAAS,yBAAyB;",
6
+ "names": ["conservationKey", "wordKeysOf", "conservationKey", "conservationKey"]
7
7
  }
package/dist/light.min.js CHANGED
@@ -1 +1 @@
1
- import{conservationKey as me,lostWords as ge,textConservation as pe,wordKeysOf as be}from"doc-ir";import{conservationKey as p}from"doc-ir";var P=/[\s\S]/gu,T=n=>[...n.matchAll(P)].map(e=>({text:e[0],key:p(e[0]),end:e.index+e[0].length})),E=n=>{let e=[],t=[],o=()=>{p(t.map(r=>r.text).join("")).length>0&&e.push(t),t=[]};for(let r of n)/^\s+$/u.test(r.text)?o():t.push(r);return o(),e},b=(n,e)=>{let t=[...n],o=e==="lead"?t:[...t].reverse(),r=[];for(let d of o){if(p(d).length>0)break;r.push(d)}return(e==="lead"?r:[...r].reverse()).join("")},h=n=>n.replaceAll("\u200B",""),C=(n,e)=>{let t=e.pageWords[0];if(e.kind!=="glued"||e.pageWords.length!==1||t===void 0||e.sourceWords.length<2)return;let o=n[t.block];if(o!==void 0)return E(T(o))[t.word]},W=(n,e,t)=>{if(h(n.map(d=>d.text).join(""))!==e+t)return;let o="",r=0;for(;o.length<e.length&&r<n.length;)o+=h(n[r++].text);return o===e?r:void 0},A=(n,e)=>{let t=C(n,e);if(t===void 0)return;let o=e.sourceWords.map(p),r=p(t.map(c=>c.text).join(""));if(t.map(c=>c.key).join("")!==r||o.join("")!==r)return;let d=[],i=0,l=0;for(let c=0;c<o.length-1;c++){let f=l+o[c].length;for(;i<t.length&&l+t[i].key.length<=f&&l<f;)l+=t[i++].key.length;if(l!==f)return;let s=i;for(;s<t.length&&t[s].key.length===0;)s++;let u=W(t.slice(i,s),b(e.sourceWords[c],"trail"),b(e.sourceWords[c+1],"lead"));if(u===void 0)return;d.push(t[i+u-1].end),i+=u}return d};function R(n,e){let t=e.filter(i=>i.kind==="glued");if(t.length===0)return{edits:[],repaired:0};let o=new Set,r=[],d=0;for(let i of t){let l=i.pageWords[0]?.block,c=A(n.blocks,i);if(!(c===void 0||l===void 0||c.some(f=>o.has(`${l}:${f}`)))){for(let f of c)o.add(`${l}:${f}`),r.push({kind:"insert-space",block:l,atChar:f});d+=1}}return{edits:r,repaired:d}}var x=n=>n.respacings.filter(e=>e.kind==="split").length,I=(n,e,t)=>e.lostLetters<=n.lostLetters&&(e.decision!=="lost"||n.decision==="lost")&&e.decision!=="abstain"&&e.gluedWords<=n.gluedWords-t&&e.unmatchedPageWords<=n.unmatchedPageWords&&x(e)<=x(n);import{collapseBlanks as O}from"doc-ir/internal";var B="\u2022\u25AA\u25E6\u2023\xB7\u25CF\u2043",S=new RegExp(`^\\s*[${B}]\\s*`,"u"),_=/^\s*[-–—]\s+/u,N=/^\s*(\d{1,2})[.)]\s+/u,v=/^\s*[a-zA-Z][.)]\s+/u,M=/^\s*[IVXivx]{1,4}[.)]\s+/u;function L(n){let e=N.exec(n);if(e!==null)return{kind:"ordered",length:e[0].length,value:Number(e[1])};for(let[t,o]of[[S,"bullet"],[_,"bullet"],[M,"letter"],[v,"letter"]]){let r=t.exec(n);if(r!==null)return{kind:o,length:r[0].length}}}import{conservationKey as j}from"doc-ir";var k=3,w=/[.:;!?»"…)]$/u,U=n=>new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])","u").test(n),V=n=>j(n.split(/\s+/)[0]??"").length<=1,y=(n,e)=>O(e.map(t=>n.blocks[t]??"").join(" ")),D=n=>n!==null,K=(n,e)=>{if(n.length===0||e.length===0)return!1;let t=[...n,...e];if(!t.every(D))return!1;for(let d=1;d<t.length;d++)if(t[d].index!==t[d-1].index+1)return!1;let o=t[n.length-1],r=t[n.length];return Math.abs(o.lastSize-r.firstSize)<.01},Y=(n,e)=>n.length===0||w.test(n)||!U(e)||L(e)!==void 0?!1:!V(e),G=(n,e)=>e.decision!=="abstain"&&(e.decision!=="lost"||n.decision==="lost")&&e.lostLetters<=n.lostLetters&&e.gluedWords<=n.gluedWords&&e.unmatchedPageWords<=n.unmatchedPageWords;function $(n,e){let t=n.units;if(t===void 0||e.decision==="abstain")return{edits:[],joined:0};let o=t.map(i=>i.blocks.flatMap(l=>e.sourceOfPageWords[l]??[])),r=i=>{let l=t[i],c=t[i+1];if(!l.joinable||!c.joinable||!l.adjacentToNext)return!1;let f=y(n,l.blocks),s=y(n,c.blocks);return Y(f,s)?K(o[i].slice(-k),o[i+1].slice(0,k)):!1},d=[];for(let i=t.length-2;i>=0;i--)r(i)&&d.push({kind:"join-units",unit:i});return{edits:d,joined:d.length}}import{conservationKey as F,wordKeysOf as H}from"doc-ir";var X=(n,e)=>n.block>e.block||n.block===e.block&&n.word>e.word;function z(n,e){let t=[],o=[];if(e.length===0)return{insertions:t,abstentions:o};let r=n.units,d=n.blocks.map(s=>H(s).length),i=d.length-1,l=s=>r?.findIndex(u=>u.blocks.includes(s))??-1,c=(s,u)=>{let a=l(s.block);if(a<0||r?.[a]?.paragraphOrHeading!==!0)return"anchor-in-container";let m=u==="before"?s.block+1:s.block-1;return!(u==="before"?s.word===(d[s.block]??0)-1:s.word===0)||l(m)===a?"loss-inside-block":a},f=s=>{let{before:u,after:a}=s;if(u==="unanchored"||a==="unanchored")return"anchor-unmatched";if(u==="document-edge"&&a==="document-edge")return"no-anchor";if(u!=="document-edge"&&a!=="document-edge"&&!X(a,u))return"anchors-out-of-order";let m=u==="document-edge"?void 0:c(u,"before");if(typeof m=="string")return m;let g=a==="document-edge"?void 0:c(a,"after");return typeof g=="string"?g:m===void 0?g===void 0||a==="document-edge"||a.block!==0?"no-anchor":g-1:g===void 0?u==="document-edge"||u.block!==i?"no-anchor":m:g!==m+1||r?.[m]?.adjacentToNext!==!0?"blocks-not-adjacent":m};for(let s of e){let u=f(s);if(typeof u=="string"){o.push(u);continue}t.push({edit:{kind:"insert-unit-after",unit:u,text:s.sourceWords.join(" ")},letters:s.sourceWords.reduce((a,m)=>a+F(m).length,0)})}return{insertions:t,abstentions:o}}import{ReaderError as ye}from"doc-ir";import{MAX_PAYLOAD_BYTES as Te}from"doc-ir";export{Te as MAX_PAYLOAD_BYTES,ye as ReaderError,me as conservationKey,$ as cutParagraphEdits,R as gluedWordEdits,G as joinNoWorse,ge as lostWords,I as noWorse,z as placeLostPassages,pe as textConservation,be as wordKeysOf};
1
+ import{conservationKey as me,lostWords as pe,textConservation as ge,wordKeysOf as be}from"doc-ir";import{conservationKey as g}from"doc-ir";var P=/[\s\S]/gu,T=t=>[...t.matchAll(P)].map(e=>({text:e[0],key:g(e[0]),end:e.index+e[0].length})),E=t=>{let e=[],n=[],o=()=>{g(n.map(r=>r.text).join("")).length>0&&e.push(n),n=[]};for(let r of t)/^\s+$/u.test(r.text)?o():n.push(r);return o(),e},b=(t,e)=>{let n=[...t],o=e==="lead"?n:[...n].reverse(),r=[];for(let d of o){if(g(d).length>0)break;r.push(d)}return(e==="lead"?r:[...r].reverse()).join("")},h=t=>t.replaceAll("\u200B",""),C=(t,e)=>{let n=e.pageWords[0];if(e.kind!=="glued"||e.pageWords.length!==1||n===void 0||e.sourceWords.length<2)return;let o=t[n.block];if(o!==void 0)return E(T(o))[n.word]},W=(t,e,n)=>{if(h(t.map(d=>d.text).join(""))!==e+n)return;let o="",r=0;for(;o.length<e.length&&r<t.length;)o+=h(t[r++].text);return o===e?r:void 0},A=(t,e)=>{let n=C(t,e);if(n===void 0)return;let o=e.sourceWords.map(g);if(o.some(u=>u.length===0))return;let r=g(n.map(u=>u.text).join(""));if(n.map(u=>u.key).join("")!==r||o.join("")!==r)return;let d=[],i=0,c=0;for(let u=0;u<o.length-1;u++){let f=c+o[u].length;for(;i<n.length&&c+n[i].key.length<=f&&c<f;)c+=n[i++].key.length;if(c!==f)return;let s=i;for(;s<n.length&&n[s].key.length===0;)s++;let l=W(n.slice(i,s),b(e.sourceWords[u],"trail"),b(e.sourceWords[u+1],"lead"));if(l===void 0)return;d.push(n[i+l-1].end),i+=l}return d};function R(t,e){let n=e.filter(i=>i.kind==="glued");if(n.length===0)return{edits:[],repaired:0};let o=new Set,r=[],d=0;for(let i of n){let c=i.pageWords[0]?.block,u=A(t.blocks,i);if(!(u===void 0||c===void 0||u.some(f=>o.has(`${c}:${f}`)))){for(let f of u)o.add(`${c}:${f}`),r.push({kind:"insert-space",block:c,atChar:f});d+=1}}return{edits:r,repaired:d}}var x=t=>t.respacings.filter(e=>e.kind==="split").length,I=(t,e,n)=>e.lostLetters<=t.lostLetters&&(e.decision!=="lost"||t.decision==="lost")&&e.decision!=="abstain"&&e.gluedWords<=t.gluedWords-n&&e.unmatchedPageWords<=t.unmatchedPageWords&&x(e)<=x(t);import{collapseBlanks as O}from"doc-ir/internal";var B="\u2022\u25AA\u25E6\u2023\xB7\u25CF\u2043",S=new RegExp(`^\\s*[${B}]\\s*`,"u"),N=/^\s*[-–—]\s+/u,M=/^\s*(\d{1,2})[.)]\s+/u,_=/^\s*[a-zA-Z][.)]\s+/u,v=/^\s*[IVXivx]{1,4}[.)]\s+/u;function L(t){let e=M.exec(t);if(e!==null)return{kind:"ordered",length:e[0].length,value:Number(e[1])};for(let[n,o]of[[S,"bullet"],[N,"bullet"],[v,"letter"],[_,"letter"]]){let r=n.exec(t);if(r!==null)return{kind:o,length:r[0].length}}}import{conservationKey as j}from"doc-ir";var k=3,w=/[.:;!?»"…)]$/u,U=t=>new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])","u").test(t),V=t=>j(t.split(/\s+/)[0]??"").length<=1,y=(t,e)=>O(e.map(n=>t.blocks[n]??"").join(" ")),D=t=>t!==null,G=(t,e)=>{if(t.length===0||e.length===0)return!1;let n=[...t,...e];if(!n.every(D))return!1;for(let d=1;d<n.length;d++)if(n[d].index!==n[d-1].index+1)return!1;let o=n[t.length-1],r=n[t.length];return Math.abs(o.lastSize-r.firstSize)<.01},K=(t,e)=>t.length===0||w.test(t)||!U(e)||L(e)!==void 0?!1:!V(e),Y=(t,e)=>e.decision!=="abstain"&&(e.decision!=="lost"||t.decision==="lost")&&e.lostLetters<=t.lostLetters&&e.gluedWords<=t.gluedWords&&e.unmatchedPageWords<=t.unmatchedPageWords;function $(t,e){let n=t.units;if(n===void 0||e.decision==="abstain")return{edits:[],joined:0};let o=n.map(i=>i.blocks.flatMap(c=>e.sourceOfPageWords[c]??[])),r=i=>{let c=n[i],u=n[i+1];if(!c.joinable||!u.joinable||!c.adjacentToNext)return!1;let f=y(t,c.blocks),s=y(t,u.blocks);return K(f,s)?G(o[i].slice(-k),o[i+1].slice(0,k)):!1},d=[];for(let i=n.length-2;i>=0;i--)r(i)&&d.push({kind:"join-units",unit:i});return{edits:d,joined:d.length}}import{conservationKey as F,wordKeysOf as H}from"doc-ir";var X=(t,e)=>t.block>e.block||t.block===e.block&&t.word>e.word;function z(t,e){let n=[],o=[];if(e.length===0)return{insertions:n,abstentions:o};let r=t.units,d=t.blocks.map(s=>H(s).length),i=d.length-1,c=s=>r?.findIndex(l=>l.blocks.includes(s))??-1,u=(s,l)=>{let a=c(s.block);if(a<0||r?.[a]?.paragraphOrHeading!==!0)return"anchor-in-container";let m=l==="before"?s.block+1:s.block-1;return!(l==="before"?s.word===(d[s.block]??0)-1:s.word===0)||c(m)===a?"loss-inside-block":a},f=s=>{let{before:l,after:a}=s;if(l==="unanchored"||a==="unanchored")return"anchor-unmatched";if(l==="document-edge"&&a==="document-edge")return"no-anchor";if(l!=="document-edge"&&a!=="document-edge"&&!X(a,l))return"anchors-out-of-order";let m=l==="document-edge"?void 0:u(l,"before");if(typeof m=="string")return m;let p=a==="document-edge"?void 0:u(a,"after");return typeof p=="string"?p:m===void 0?p===void 0||a==="document-edge"||a.block!==0?"no-anchor":p-1:p===void 0?l==="document-edge"||l.block!==i?"no-anchor":m:p!==m+1||r?.[m]?.adjacentToNext!==!0?"blocks-not-adjacent":m};for(let s of e){let l=f(s);if(typeof l=="string"){o.push(l);continue}n.push({edit:{kind:"insert-unit-after",unit:l,text:s.sourceWords.join(" ")},letters:s.sourceWords.reduce((a,m)=>a+F(m).length,0)})}return{insertions:n,abstentions:o}}import{ReaderError as ye}from"doc-ir";import{MAX_PAYLOAD_BYTES as Te}from"doc-ir";export{Te as MAX_PAYLOAD_BYTES,ye as ReaderError,me as conservationKey,$ as cutParagraphEdits,R as gluedWordEdits,I as isGluedRepairNoWorse,Y as isParagraphJoinNoWorse,pe as lostWords,z as placeLostPassages,ge as textConservation,be as wordKeysOf};
@@ -3,8 +3,8 @@ export interface CcittOptions {
3
3
  readonly EndOfLine: boolean;
4
4
  readonly EncodedByteAlign: boolean;
5
5
  readonly BlackIs1: boolean;
6
- readonly columns: number;
7
- readonly rows: number;
6
+ readonly Columns: number;
7
+ readonly Rows: number;
8
8
  }
9
9
  export interface CcittImage {
10
10
  readonly columns: number;
@@ -12,4 +12,4 @@ export interface CcittImage {
12
12
  readonly pitch: number;
13
13
  readonly bits: Uint8Array;
14
14
  }
15
- export declare function decodeCcittFax(src: Uint8Array, options: CcittOptions): CcittImage | undefined;
15
+ export declare function decodeCcittFax(source: Uint8Array, options: CcittOptions): CcittImage | undefined;
@@ -8,4 +8,4 @@ export declare class DocumentCache {
8
8
  getOrCompute<V>(kind: symbol, key: unknown, sizeOf: (value: V) => number, compute: () => V): V;
9
9
  get size(): number;
10
10
  }
11
- export declare function documentCacheOf(document: object): DocumentCache;
11
+ export declare function resolveDocumentCache(document: object): DocumentCache;
@@ -1,11 +1,11 @@
1
1
  export interface ExtractionCost {
2
- docOpens: number;
2
+ documentOpens: number;
3
3
  operatorsWalked: number;
4
4
  glyphFragments: number;
5
5
  pdfLibOpens: number;
6
6
  imagesRead: number;
7
7
  }
8
- export declare const emptyExtractionCost: () => ExtractionCost;
8
+ export declare const createExtractionCost: () => ExtractionCost;
9
9
  export declare const count: (cost: ExtractionCost | undefined, key: keyof ExtractionCost, by?: number) => void;
10
10
  export declare const COUNTERS: Record<keyof ExtractionCost, {
11
11
  rise: string;
@@ -1,7 +1,2 @@
1
1
  export type FontWeight = "bold" | "normal" | "unknown";
2
- export interface FontLike {
3
- name?: unknown;
4
- bold?: unknown;
5
- missingFile?: unknown;
6
- }
7
- export declare function fontWeight(font: FontLike | undefined): FontWeight;
2
+ export declare function classifyFontWeight(weightValue: number | undefined, name: string | undefined): FontWeight;
@@ -1,8 +1,8 @@
1
1
  import { ReaderError } from "doc-ir";
2
2
  import { type Matrix2D } from "../layout/geometry.js";
3
- import { GRAPHICS_STATE_MAX_DEPTH, type PdfOp } from "./pdf-ops.js";
3
+ import { GRAPHICS_STATE_MAX_DEPTH, type PdfOperator } from "./pdf-ops.js";
4
4
  export { GRAPHICS_STATE_MAX_DEPTH };
5
- export type NamedOp = PdfOp;
5
+ export type NamedOperator = PdfOperator;
6
6
  export type GlyphAbstentionTag = "vertical-writing" | "text-operator";
7
7
  export declare class GlyphBuilderAbstention extends ReaderError {
8
8
  readonly tag: GlyphAbstentionTag;
@@ -18,10 +18,10 @@ export interface GlyphFragment {
18
18
  runId: number;
19
19
  isSpace: boolean;
20
20
  paintCount: number;
21
- stroked: boolean;
21
+ isStroked: boolean;
22
22
  href?: string;
23
- hidden?: "mode" | "layer" | "paint" | "size" | "clip";
24
- unpainted?: true;
23
+ hiddenReason?: "mode" | "layer" | "paint" | "size" | "clip";
24
+ isUnpainted?: true;
25
25
  font?: string;
26
26
  rise?: {
27
27
  x: number;
@@ -29,22 +29,22 @@ export interface GlyphFragment {
29
29
  };
30
30
  section?: number;
31
31
  mcid?: number;
32
- artifact?: boolean;
33
- unreadFont?: true;
32
+ isArtifact?: boolean;
33
+ isFontUnread?: true;
34
34
  }
35
35
  export type FontScaleOf = (fontName: string) => number | undefined;
36
36
  export type SymbolFontOf = (fontName: string) => boolean;
37
37
  export declare const MIN_VISIBLE_HEIGHT = 0.25;
38
38
  export declare const NOT_PAINTED_MODES: ReadonlySet<number>;
39
39
  export declare const INVISIBLE_TEXT_MODES: ReadonlySet<number>;
40
- export declare const isGlyphDropped: (hidden: GlyphFragment["hidden"], dropModeHidden: boolean) => boolean;
40
+ export declare const isGlyphDropped: (hidden: GlyphFragment["hiddenReason"], shouldDropModeHidden: boolean) => boolean;
41
41
  export interface HidePolicy {
42
42
  isLayerVisible: (group: unknown) => boolean;
43
- dropModeHidden: boolean;
43
+ shouldDropModeHidden: boolean;
44
44
  }
45
- export declare function buildGlyphFragments(ops: readonly NamedOp[], hide?: HidePolicy, fontScaleOf?: FontScaleOf, symbolFontOf?: SymbolFontOf): GlyphFragment[];
46
- export declare function filteredGlyphs(all: GlyphFragment[], hide?: HidePolicy): GlyphFragment[];
47
- export declare function unreadFontKept(all: readonly GlyphFragment[], hide?: HidePolicy): boolean;
45
+ export declare function buildGlyphFragments(ops: readonly NamedOperator[], hide?: HidePolicy, fontScaleOf?: FontScaleOf, symbolFontOf?: SymbolFontOf): GlyphFragment[];
46
+ export declare function filterGlyphs(all: GlyphFragment[], hide?: HidePolicy): GlyphFragment[];
47
+ export declare function isUnreadFontKept(all: readonly GlyphFragment[], hide?: HidePolicy): boolean;
48
48
  export declare class MarkedContentStack {
49
49
  private readonly mcids;
50
50
  private readonly artifacts;
@@ -52,7 +52,7 @@ export declare class MarkedContentStack {
52
52
  push(mcid: number | undefined, artifact: boolean): void;
53
53
  pop(): void;
54
54
  get innermostMcid(): number | undefined;
55
- get inArtifact(): boolean;
55
+ get isInArtifact(): boolean;
56
56
  }
57
57
  export declare const MAX_SHELTER_BOXES_PER_PAGE = 20000;
58
- export declare function readGlyphs(ops: readonly NamedOp[], isLayerVisible?: (group: unknown) => boolean, fontScaleOf?: FontScaleOf, symbolFontOf?: SymbolFontOf): GlyphFragment[];
58
+ export declare function readGlyphs(ops: readonly NamedOperator[], isLayerVisible?: (group: unknown) => boolean, fontScaleOf?: FontScaleOf, symbolFontOf?: SymbolFontOf): GlyphFragment[];
@@ -1,14 +1,14 @@
1
- import { type FontScaleOf, type GlyphFragment, type HidePolicy, type NamedOp, type SymbolFontOf } from "./glyph-positions.js";
1
+ import { type FontScaleOf, type GlyphFragment, type HidePolicy, type NamedOperator, type SymbolFontOf } from "./glyph-positions.js";
2
2
  import type { PdfTextRun } from "./pdf-source.js";
3
3
  export interface GlyphRunOptions {
4
- pageObjId?: string | undefined;
4
+ pageObjectId?: string | undefined;
5
5
  view?: readonly [number, number, number, number] | undefined;
6
6
  normalize?: ((text: string) => string) | undefined;
7
7
  sameFont?: ((a: string | undefined, b: string | undefined) => boolean) | undefined;
8
8
  }
9
- export declare function runsOfGlyphs(glyphs: readonly GlyphFragment[], options?: GlyphRunOptions): PdfTextRun[];
9
+ export declare function groupGlyphsIntoRuns(glyphs: readonly GlyphFragment[], options?: GlyphRunOptions): PdfTextRun[];
10
10
  export declare const MIN_ITALIC_SHEAR = 0.05;
11
- export declare function glyphRuns(ops: readonly NamedOp[], options?: GlyphRunOptions & {
11
+ export declare function readRunsFromOperators(ops: readonly NamedOperator[], options?: GlyphRunOptions & {
12
12
  hide?: HidePolicy;
13
13
  fontScaleOf?: FontScaleOf;
14
14
  symbolFontOf?: SymbolFontOf;
@@ -6,8 +6,8 @@ export interface GlyphWindowOptions {
6
6
  }
7
7
  export declare const CENTRE_WINDOW: GlyphWindowOptions;
8
8
  export declare const START_WINDOW: GlyphWindowOptions;
9
- export declare const sortedByBaseline: (glyphs: readonly GlyphFragment[]) => GlyphFragment[];
10
- export declare const glyphsOfRun: (run: {
9
+ export declare const sortByBaseline: (glyphs: readonly GlyphFragment[]) => GlyphFragment[];
10
+ export declare const findRunGlyphs: (run: {
11
11
  readonly x: number;
12
12
  readonly y: number;
13
13
  readonly width: number;
@@ -6,7 +6,7 @@ export interface AsideFigure {
6
6
  readonly lines: readonly PdfTextRun[][];
7
7
  readonly region: PageRegion;
8
8
  }
9
- export declare const asideFigures: (items: readonly PdfTextRun[], anchors: readonly ImageAnchor[], toBlocks: (segment: PdfTextRun[][]) => IRBlock[]) => {
9
+ export declare const findAsideFigures: (items: readonly PdfTextRun[], anchors: readonly ImageAnchor[], toBlocks: (segment: PdfTextRun[][]) => IRBlock[]) => {
10
10
  figures: AsideFigure[];
11
11
  taken: Set<PdfTextRun>;
12
12
  };
@@ -8,11 +8,12 @@ export interface BandedSplit<T> {
8
8
  export declare const MIN_SUBZONE_LINES = 4;
9
9
  export declare const MAX_BAND_ZONES_PER_PAGE = 64;
10
10
  export declare const MIN_WORDS_PER_ZONE_FRAGMENT = 1.5;
11
+ export declare const mostFrequentStart: (starts: readonly number[]) => number | undefined;
11
12
  export declare const bandedSplit: <T extends PositionedItem>(pageItems: readonly T[], cut: number | undefined, bound?: number, { standsAlone, innerCuts, }?: {
12
13
  standsAlone?: boolean;
13
14
  innerCuts?: readonly number[];
14
15
  }) => BandedSplit<T> | undefined;
15
- export declare const bandedSplitN: <T extends PositionedItem>(pageItems: readonly T[], cuts: readonly number[], bound?: number, standsAlone?: boolean) => {
16
+ export declare const splitIntoBands: <T extends PositionedItem>(pageItems: readonly T[], cuts: readonly number[], bound?: number, standsAlone?: boolean) => {
16
17
  above: T[][];
17
18
  bands: T[][][];
18
19
  below: T[][];
@@ -20,6 +21,6 @@ export declare const bandedSplitN: <T extends PositionedItem>(pageItems: readonl
20
21
  export declare const readingSegments: <T extends PositionedItem>(pageItems: readonly T[], cuts: readonly number[], bound?: number) => T[][][];
21
22
  export interface ReadSegment<T> {
22
23
  lines: T[][];
23
- column: boolean;
24
+ isColumn: boolean;
24
25
  }
25
26
  export declare const readingBands: <T extends PositionedItem>(pageItems: readonly T[], cuts: readonly number[], bound?: number, inBand?: boolean) => ReadSegment<T>[];
@@ -8,4 +8,4 @@ export interface DecodedImageObject {
8
8
  readonly data: Uint8Array;
9
9
  readonly heldBytes?: number;
10
10
  }
11
- export declare function ccittImageObjectOf(doc: PdfObjectsDocument, scope: PictureScope, name: string, grey1Kind: number): DecodedImageObject | undefined;
11
+ export declare function decodeCcittImageObject(doc: PdfObjectsDocument, scope: PictureScope, name: string, greyOneBitKind: number): DecodedImageObject | undefined;
@@ -1,4 +1,4 @@
1
- export declare function greyHex(grey: number): string;
2
- export declare function rgbHex(red: number, green: number, blue: number): string;
3
- export declare function cmykHex(cyan: number, magenta: number, yellow: number, black: number): string;
4
- export declare function cmykBytes(cyan: number, magenta: number, yellow: number, black: number): [number, number, number];
1
+ export declare function formatGreyHex(grey: number): string;
2
+ export declare function formatRgbHex(red: number, green: number, blue: number): string;
3
+ export declare function formatCmykHex(cyan: number, magenta: number, yellow: number, black: number): string;
4
+ export declare function convertCmykToRgb(cyan: number, magenta: number, yellow: number, black: number): [number, number, number];
@@ -21,5 +21,5 @@ export interface StandardSecurity {
21
21
  encryptMetadata: boolean;
22
22
  u: Uint8Array;
23
23
  }
24
- export declare function standardOutcome(security: StandardSecurity): DecryptOutcome;
24
+ export declare function evaluateStandardSecurity(security: StandardSecurity): DecryptOutcome;
25
25
  export {};