pdf-skryba 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/LICENSE +21 -661
  3. package/README.md +189 -115
  4. package/THIRD-PARTY.md +441 -134
  5. package/dist/first-party/reader.js +14915 -0
  6. package/dist/first-party/reader.js.map +7 -0
  7. package/dist/first-party.js +148 -0
  8. package/dist/first-party.js.map +7 -0
  9. package/dist/index.js +297 -2261
  10. package/dist/index.js.map +4 -4
  11. package/dist/index.min.js +4 -5
  12. package/dist/light.js +23 -305
  13. package/dist/light.js.map +4 -4
  14. package/dist/light.min.js +1 -1
  15. package/dist/types/{packages/doc-read/src/extractor → extractor}/glyph-accents.d.ts +1 -1
  16. package/dist/types/{packages/doc-read/src/extractor → extractor}/glyph-double-draw.d.ts +1 -1
  17. package/dist/types/{packages/doc-read/src/extractor → extractor}/glyph-positions.d.ts +3 -3
  18. package/dist/types/{packages/doc-read/src/extractor → extractor}/glyph-runs.d.ts +2 -2
  19. package/dist/types/{packages/doc-read/src/extractor → extractor}/glyph-window.d.ts +1 -1
  20. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-aside-figures.d.ts +3 -3
  21. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-bands.d.ts +1 -1
  22. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-ccitt-images.d.ts +2 -2
  23. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-cell-paragraphs.d.ts +2 -2
  24. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-column-cut.d.ts +1 -1
  25. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-document-info.d.ts +1 -1
  26. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-document-scale.d.ts +4 -4
  27. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-embedded-images.d.ts +3 -3
  28. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-facts.d.ts +2 -2
  29. package/dist/types/extractor/pdf-flate-images.d.ts +7 -0
  30. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-font-bridge.d.ts +1 -1
  31. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-font-objects.d.ts +2 -2
  32. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/font-text.d.ts +4 -4
  33. package/dist/types/extractor/pdf-fonts/widths.d.ts +4 -0
  34. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-framed-blocks.d.ts +2 -2
  35. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-glyph-source.d.ts +4 -4
  36. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-hidden-text.d.ts +1 -1
  37. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-image-anchors.d.ts +6 -6
  38. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-image-pixels.d.ts +2 -2
  39. package/dist/types/extractor/pdf-image-refusal.d.ts +4 -0
  40. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-image-store.d.ts +2 -2
  41. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-images.d.ts +1 -1
  42. package/dist/types/extractor/pdf-jpeg-images.d.ts +7 -0
  43. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-layers.d.ts +1 -1
  44. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-letter-spacing.d.ts +2 -2
  45. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-line-breaks.d.ts +2 -2
  46. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-lines.d.ts +3 -3
  47. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-links-ours.d.ts +2 -2
  48. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-links.d.ts +3 -3
  49. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-model.d.ts +9 -8
  50. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/content.d.ts +1 -1
  51. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/document.d.ts +1 -1
  52. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/parse.d.ts +1 -1
  53. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/refusal.d.ts +1 -1
  54. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/streams.d.ts +1 -1
  55. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/xref.d.ts +1 -1
  56. package/dist/types/extractor/pdf-objstm-source.d.ts +3 -0
  57. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-open.d.ts +4 -4
  58. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-ops-ours.d.ts +3 -3
  59. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-ops.d.ts +1 -1
  60. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-outline.d.ts +1 -1
  61. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-page-content.d.ts +3 -3
  62. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-page-figures.d.ts +7 -7
  63. package/dist/types/extractor/pdf-page-markers.d.ts +12 -0
  64. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-page-plan.d.ts +4 -4
  65. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-page-stages.d.ts +14 -13
  66. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-page-tables.d.ts +8 -8
  67. package/dist/types/extractor/pdf-page-tabs.d.ts +4 -0
  68. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-paragraphs.d.ts +3 -3
  69. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-paths-ours.d.ts +2 -2
  70. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-reading-order.d.ts +2 -2
  71. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-reference-ours.d.ts +2 -2
  72. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-region-order.d.ts +3 -3
  73. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-rotated-lines.d.ts +1 -1
  74. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-rotated-words.d.ts +1 -1
  75. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-row-url-join.d.ts +1 -1
  76. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-scanned.d.ts +8 -8
  77. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-smask.d.ts +2 -2
  78. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-source.d.ts +13 -13
  79. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-stencil-images.d.ts +3 -3
  80. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-structure.d.ts +1 -1
  81. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-symbol-page.d.ts +2 -2
  82. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-symbol-verdict.d.ts +1 -1
  83. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-table-detector.d.ts +7 -7
  84. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-table-render.d.ts +7 -4
  85. package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf.d.ts +14 -14
  86. package/dist/types/{packages/doc-ir/src/layout → layout}/aligned-grid.d.ts +1 -1
  87. package/dist/types/{packages/doc-ir/src/layout → layout}/baseline-lines.d.ts +1 -1
  88. package/dist/types/{packages/doc-ir/src/layout → layout}/cell-text.d.ts +1 -1
  89. package/dist/types/{packages/doc-ir/src/layout → layout}/column-discriminant.d.ts +1 -1
  90. package/dist/types/{packages/doc-ir/src/layout → layout}/column-grid.d.ts +1 -1
  91. package/dist/types/{packages/doc-ir/src/layout → layout}/cut-word.d.ts +2 -2
  92. package/dist/types/{packages/doc-ir/src/layout → layout}/fragment-cells.d.ts +1 -1
  93. package/dist/types/{packages/doc-ir/src/layout → layout}/geometry.d.ts +10 -9
  94. package/dist/types/{packages/doc-ir/src/layout → layout}/gutter.d.ts +1 -1
  95. package/dist/types/{packages/doc-ir/src/layout → layout}/hyphenation.d.ts +1 -1
  96. package/dist/types/{packages/doc-ir/src/layout → layout}/intersection-cells.d.ts +1 -1
  97. package/dist/types/{packages/doc-ir/src/layout → layout}/merged-cells.d.ts +1 -2
  98. package/dist/types/{packages/doc-ir/src/layout → layout}/page-furniture.d.ts +1 -1
  99. package/dist/types/{packages/doc-ir/src/layout → layout}/text-size.d.ts +1 -1
  100. package/dist/types/{packages/doc-ir/src/layout → layout}/vector-grid.d.ts +1 -1
  101. package/dist/types/lib/link-schemes.d.ts +1 -0
  102. package/dist/types/lib/pdf-first-party-reader.d.ts +11 -0
  103. package/dist/types/lib/pdf-first-party.d.ts +7 -0
  104. package/dist/types/lib/pdf-light.d.ts +15 -0
  105. package/dist/types/lib/pdf.d.ts +5 -0
  106. package/dist/types/lib/reader-options.d.ts +12 -0
  107. package/dist/types/lib/table-leading-bands.d.ts +7 -0
  108. package/dist/types/{packages/doc-read/src/pipeline → pipeline}/cut-paragraph-repair.d.ts +1 -1
  109. package/dist/types/{packages/doc-read/src/pipeline → pipeline}/glued-word-repair.d.ts +1 -1
  110. package/dist/types/{packages/doc-read/src/pipeline → pipeline}/lost-text-repair.d.ts +1 -1
  111. package/dist/types/{packages/doc-read/src/pipeline → pipeline}/pdf-conservation-source.d.ts +1 -1
  112. package/package.json +50 -15
  113. package/dist/types/packages/doc-ir/src/extractor/bytes.d.ts +0 -4
  114. package/dist/types/packages/doc-ir/src/extractor/image-format.d.ts +0 -15
  115. package/dist/types/packages/doc-ir/src/extractor/image-pixel-width.d.ts +0 -3
  116. package/dist/types/packages/doc-ir/src/extractor/png-color.d.ts +0 -4
  117. package/dist/types/packages/doc-ir/src/extractor/png-decode.d.ts +0 -8
  118. package/dist/types/packages/doc-ir/src/extractor/png.d.ts +0 -3
  119. package/dist/types/packages/doc-ir/src/extractor/raw-image.d.ts +0 -6
  120. package/dist/types/packages/doc-ir/src/layout/geometry-types.d.ts +0 -65
  121. package/dist/types/packages/doc-ir/src/layout/painted-paths.d.ts +0 -22
  122. package/dist/types/packages/doc-ir/src/layout/rect-rules.d.ts +0 -77
  123. package/dist/types/packages/doc-ir/src/layout/rect.d.ts +0 -14
  124. package/dist/types/packages/doc-ir/src/lib/blanks.d.ts +0 -1
  125. package/dist/types/packages/doc-ir/src/lib/digest.d.ts +0 -1
  126. package/dist/types/packages/doc-ir/src/lib/ir-walk.d.ts +0 -6
  127. package/dist/types/packages/doc-ir/src/lib/ir.d.ts +0 -133
  128. package/dist/types/packages/doc-ir/src/lib/link-schemes.d.ts +0 -5
  129. package/dist/types/packages/doc-ir/src/lib/page-labels.d.ts +0 -10
  130. package/dist/types/packages/doc-ir/src/lib/reader-error.d.ts +0 -14
  131. package/dist/types/packages/doc-ir/src/lib/reader-limits.d.ts +0 -47
  132. package/dist/types/packages/doc-ir/src/lib/reader-types.d.ts +0 -111
  133. package/dist/types/packages/doc-ir/src/lib/symbol-font.d.ts +0 -3
  134. package/dist/types/packages/doc-ir/src/lib/table-empty-parts.d.ts +0 -16
  135. package/dist/types/packages/doc-ir/src/lib/table-width-cap.d.ts +0 -7
  136. package/dist/types/packages/doc-ir/src/lib/vision-port.d.ts +0 -16
  137. package/dist/types/packages/doc-ir/src/pipeline/detect-language.d.ts +0 -13
  138. package/dist/types/packages/doc-ir/src/pipeline/language-profiles.d.ts +0 -8
  139. package/dist/types/packages/doc-ir/src/pipeline/text-conservation.d.ts +0 -89
  140. package/dist/types/packages/doc-read/src/extractor/pdf-flate-images.d.ts +0 -7
  141. package/dist/types/packages/doc-read/src/extractor/pdf-fonts/widths.d.ts +0 -4
  142. package/dist/types/packages/doc-read/src/extractor/pdf-image-refusal.d.ts +0 -4
  143. package/dist/types/packages/doc-read/src/extractor/pdf-jpeg-images.d.ts +0 -7
  144. package/dist/types/packages/doc-read/src/extractor/pdf-objstm-source.d.ts +0 -3
  145. package/dist/types/packages/doc-read/src/extractor/pdf-page-markers.d.ts +0 -12
  146. package/dist/types/packages/doc-read/src/extractor/pdf-page-tabs.d.ts +0 -4
  147. package/dist/types/packages/doc-read/src/lib/pdf-light.d.ts +0 -15
  148. package/dist/types/packages/doc-read/src/lib/pdf.d.ts +0 -5
  149. package/dist/types/packages/doc-read/src/lib/reader-options.d.ts +0 -12
  150. /package/dist/types/{packages/doc-read/src/extractor → extractor}/codecs/ccitt-fax.d.ts +0 -0
  151. /package/dist/types/{packages/doc-read/src/extractor → extractor}/codecs/ccitt-run-tables.d.ts +0 -0
  152. /package/dist/types/{packages/doc-read/src/extractor → extractor}/document-cache.d.ts +0 -0
  153. /package/dist/types/{packages/doc-read/src/extractor → extractor}/extraction-cost.d.ts +0 -0
  154. /package/dist/types/{packages/doc-read/src/extractor → extractor}/font-weight.d.ts +0 -0
  155. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-colour-ours.d.ts +0 -0
  156. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-decrypt.d.ts +0 -0
  157. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/bounds.d.ts +0 -0
  158. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/cns-cmap-data.d.ts +0 -0
  159. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/glyph-data.d.ts +0 -0
  160. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/jis-cmap-data.d.ts +0 -0
  161. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/names.d.ts +0 -0
  162. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/predefined-cmaps.d.ts +0 -0
  163. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/table-budget.d.ts +0 -0
  164. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/to-unicode.d.ts +0 -0
  165. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-fonts/type1-encoding.d.ts +0 -0
  166. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/bounds.d.ts +0 -0
  167. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-objects/objects.d.ts +0 -0
  168. /package/dist/types/{packages/doc-gate/src/extractor → extractor}/pdf-objstm-guard.d.ts +0 -0
  169. /package/dist/types/{packages/doc-read/src/extractor → extractor}/pdf-text-string.d.ts +0 -0
  170. /package/dist/types/{packages/doc-read/src/extractor → extractor}/text-writing-direction.d.ts +0 -0
  171. /package/dist/types/{packages/doc-ir/src/layout → layout}/grid-band.d.ts +0 -0
  172. /package/dist/types/{packages/doc-ir/src/layout → layout}/heading-sizes.d.ts +0 -0
  173. /package/dist/types/{packages/doc-ir/src/layout → layout}/hidden-repaints.d.ts +0 -0
  174. /package/dist/types/{packages/doc-ir/src/layout → layout}/hyphenation-en.d.ts +0 -0
  175. /package/dist/types/{packages/doc-ir/src/layout → layout}/hyphenation-fr.d.ts +0 -0
  176. /package/dist/types/{packages/doc-ir/src/layout → layout}/image-frontier.d.ts +0 -0
  177. /package/dist/types/{packages/doc-ir/src/layout → layout}/induced-markers.d.ts +0 -0
  178. /package/dist/types/{packages/doc-ir/src/layout → layout}/intervals.d.ts +0 -0
  179. /package/dist/types/{packages/doc-ir/src/layout → layout}/list.d.ts +0 -0
  180. /package/dist/types/{packages/doc-ir/src/layout → layout}/mode.d.ts +0 -0
  181. /package/dist/types/{packages/doc-ir/src/layout → layout}/position-clusters.d.ts +0 -0
  182. /package/dist/types/{packages/doc-ir/src/layout → layout}/straddled-boundaries.d.ts +0 -0
  183. /package/dist/types/{packages/doc-ir/src/layout → layout}/superscript.d.ts +0 -0
  184. /package/dist/types/{packages/doc-ir/src/layout → layout}/tolerances.d.ts +0 -0
  185. /package/dist/types/{packages/doc-ir/src/layout → layout}/word-gap.d.ts +0 -0
  186. /package/dist/types/{packages/doc-read/src/lib → lib}/chunk.d.ts +0 -0
  187. /package/dist/types/{packages/doc-ir/src/lib → lib}/extent.d.ts +0 -0
package/dist/light.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../doc-ir/src/pipeline/text-conservation.ts", "../../doc-read/src/pipeline/glued-word-repair.ts", "../../doc-ir/src/lib/blanks.ts", "../../doc-ir/src/layout/list.ts", "../../doc-read/src/pipeline/cut-paragraph-repair.ts", "../../doc-read/src/pipeline/lost-text-repair.ts", "../../doc-ir/src/lib/reader-error.ts", "../../doc-ir/src/lib/reader-limits.ts"],
4
- "sourcesContent": ["/** Whether the storage XHTML about to be published still carries every letter of the PDF's own text: a typed verdict \u2014 ok, lost, glued or abstain \u2014 with its rule, its margin and the pages concerned, from two readings that must agree.\r\n * NOT here: what the publish path keeps of a verdict (`pipeline/publish-conservation.ts`), the repairs of glued words, lost passages and cut paragraphs (`pipeline/glued-word-repair.ts`, `pipeline/lost-text-repair.ts`, `pipeline/cut-paragraph-repair.ts`), the furniture decision (`extractor/pdf-document-scale.ts`), nor the comparison for a format that declares its text (`pipeline/declared-format-conservation.ts`) \u2014 only a PDF has no declared text to trust, so only its verdict is computed here.\r\n * Also hosts the page reading shared with the declared formats (`TAG`, `INLINE_TAGS`, `dropScaffolding`, `readPage`, `decodePageEntities`).\r\n * Called by: `pipeline/publish-conservation.ts`, `pipeline/glued-word-repair.ts`, `pipeline/lost-text-repair.ts` and `pipeline/cut-paragraph-repair.ts` for where a page word sits in the XHTML, `pipeline/adf-conservation.ts` for the page letters, and `pipeline/declared-format-conservation.ts` for the shared page reading. */\r\n\r\n/**\r\n * WHY TWO READINGS (design validated by 21/09/2026).\r\n *\r\n * The WORD reading tiles the source words against the page words, order\r\n * ignored, then explains what is left by re-spacing: a page token that is\r\n * exactly 2+ consecutive source words (glued), a source word that is exactly\r\n * 2+ consecutive page words (split). The LETTER reading does not look at word\r\n * boundaries at all: a leftover source word is covered when the page's\r\n * leftover letters, document-wide, still hold all of its letters. A word is\r\n * LOST only when neither reading finds it. A word the word reading explains\r\n * but the letters can no longer cover \u2014 an earlier leftover already took them\r\n * \u2014 means the two readings tell different stories: we abstain.\r\n *\r\n * NO THRESHOLD: a real render loses exactly 0 letters (fixture 24 in\r\n * `text-conservation.fixtures.test.ts`), so the margin is simply the number of\r\n * letters beyond 0.\r\n *\r\n * \u26A0\uFE0F CLIENT TEXT. `respacings` and `lostPassages` carry the document's own\r\n * words, because a repair needs them. They live in memory only: never stored\r\n * in an entity. What may travel into a RECORD is the counts and the page\r\n * numbers. The ONE exception (lot C addendum, 29/09/2026): `lostWords`\r\n * below, which `pipeline/publish-conservation.ts` hands on to the\r\n * DEVELOPMENT-only log line of `adapters/conservation-log.ts` \u2014 never\r\n * production, never a page, never an entity.\r\n */\r\n\r\n/** What this check needs from a text run \u2014 a subset of `PdfTextRun`. */\r\n\r\nexport interface ConservationRun {\r\n text: string;\r\n x: number;\r\n y: number;\r\n width: number;\r\n fontSize: number;\r\n hasEOL: boolean;\r\n}\r\n\r\ntype ConservationDecision = \"ok\" | \"lost\" | \"glued\" | \"abstain\";\r\n\r\n/** Every rule a verdict can name \u2014 a closed list, so the output vocabulary stays enumerable. */\r\nexport type ConservationRule =\r\n \"all-words-found\" | \"respaced-words\" | \"letters-cover-unmatched-words\" | \"letters-missing\" | \"readings-disagree\";\r\n\r\n/** Where a page word sits: the index of its text block in the page (macros\r\n * not counted), and its index among that block's words. */\r\nexport interface PageWordAt {\r\n block: number;\r\n word: number;\r\n}\r\n\r\n/**\r\n * One re-spacing the word reading proved: in memory only (see the module\r\n * note). `glued`: one page word (`pageWords` has one entry) spells the\r\n * `sourceWords` run. `split`: the `pageWords` run spells one source word.\r\n */\r\nexport interface Respacing {\r\n kind: \"glued\" | \"split\";\r\n /** 1-based PDF page of the first source word. */\r\n page: number;\r\n pageWords: PageWordAt[];\r\n /** The source words as read, boundaries included \u2014 what a repair re-inserts. */\r\n sourceWords: string[];\r\n}\r\n\r\n/**\r\n * The source word right beside a lost passage, as a repair needs it: where\r\n * its matched page word sits, the edge of the document when there is no\r\n * source word on that side, or `unanchored` when that word was found some\r\n * other way (an image's alt text, a list number, a deliberate removal, a\r\n * re-spacing, the letter reading) \u2014 it has no single place in the page.\r\n */\r\ntype LostPassageAnchor = PageWordAt | \"document-edge\" | \"unanchored\";\r\n\r\n/** A run of consecutive lost source words, in memory only (see the module note). */\r\nexport interface LostPassage {\r\n /** 1-based PDF page of the first word. */\r\n page: number;\r\n /** The tokens as read \u2014 what a repair re-inserts: the lost words and the\r\n * letterless tokens between them. Those around the passage belong to no\r\n * one for sure and are left out. */\r\n sourceWords: string[];\r\n before: LostPassageAnchor;\r\n after: LostPassageAnchor;\r\n}\r\n\r\n/** The source word a page word was tiled to, one to one: its index in the\r\n * PDF's reading order (every checked page, furniture left out), and the font\r\n * size its first and last characters were set in. No text: it travels\r\n * nowhere, but it names no word either. */\r\nexport interface SourceWordLink {\r\n index: number;\r\n firstSize: number;\r\n lastSize: number;\r\n}\r\n\r\nexport interface ConservationVerdict {\r\n decision: ConservationDecision;\r\n rule: ConservationRule;\r\n /** Letters beyond zero: `lostLetters` for a loss, 0 otherwise. */\r\n margin: number;\r\n /** Letters and digits of the source words neither reading found. */\r\n lostLetters: number;\r\n /** Re-spacings proved by the word reading, plus leftover words the letters\r\n * covered. Line-end hyphenation, letter-spaced titles and ideographic text\r\n * rejoined are correct joins and are not counted. */\r\n gluedWords: number;\r\n /** 1-based pages of the words the decision is about, ascending. */\r\n pages: number[];\r\n /** Page words no source word matched and no re-spacing explains \u2014 words\r\n * the page has and the PDF never had. A repair may not add any. */\r\n unmatchedPageWords: number;\r\n respacings: Respacing[];\r\n /** Letters and digits of every checked source word: a repaired page may not carry more. */\r\n sourceLetters: number;\r\n lostPassages: LostPassage[];\r\n /** Per page block, per word (the indices of `PageWordAt`): the source word\r\n * the word reading tiled it to, or `null` \u2014 an extra, a re-spacing, a word\r\n * the PDF lacks. Two page words whose links follow each other are two\r\n * words the PDF reads in a row. */\r\n sourceOfPageWords: (SourceWordLink | null)[][];\r\n}\r\n\r\n/** The lost source words themselves, normalised like every other word this\r\n * check compares (`conservationKey`) \u2014 for the dashboard's cause groups and\r\n * the DEVELOPMENT-only log line only (lot C addendum,\r\n * `pipeline/publish-conservation.ts`, `adapters/conservation-log.ts`): in\r\n * memory, built from `lostPassages`, never stored in an entity and never on\r\n * a page (module note above still holds \u2014 this reads the SAME in-memory\r\n * verdict a repair already reads). */\r\nexport const lostWords = (verdict: Pick<ConservationVerdict, \"lostPassages\">): string[] =>\r\n verdict.lostPassages\r\n .flatMap((p) => p.sourceWords)\r\n .map(conservationKey)\r\n .filter((w) => w.length > 0);\r\n\r\nexport interface ConservationOptions {\r\n /** 0-based pages whose runs are not document text we can check: scanned\r\n * pages and pages under an invisible OCR layer. */\r\n excludedPages?: ReadonlySet<number>;\r\n /** Texts the render drops ON PURPOSE (a merged header painted several\r\n * times, the repeated header row of a continued table). Their words absorb\r\n * leftover source words, after body text and extras, each at most as many\r\n * times as it is listed: `extractPdf` hands them on as\r\n * `textSource.deliberateRemovals`. */\r\n deliberateRemovals?: readonly string[];\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 normalisation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/** Letters and digits only, NFKC (ligatures), lower case. Dropping every other\r\n * character is what gives apostrophes a single form: none. */\r\nexport const conservationKey = (token: string): string =>\r\n token\r\n .normalize(\"NFKC\")\r\n .toLowerCase()\r\n .replace(/[^\\p{L}\\p{N}]/gu, \"\");\r\n\r\n/** The keys of the words of `text`, as every check here splits them: on white\r\n * space, a word with no letter or digit dropped. */\r\nexport const wordKeysOf = (text: string): string[] =>\r\n text\r\n .split(/\\s+/)\r\n .map(conservationKey)\r\n .filter((k) => k.length > 0);\r\n\r\nconst HYPHEN_END = /[-\u2010\u00AD]$/u;\r\nconst IDEOGRAPHIC = /[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}]/u;\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 source side \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\ninterface SourceWord {\r\n raw: string;\r\n key: string;\r\n /** 1-based. */\r\n page: number;\r\n /** The letterless tokens read between the previous word and this one\r\n * (\u00AB : \u00BB, \u00AB \u00AB \u00BB), which a lost passage carries back between its words. */\r\n gap: string[];\r\n /** The font size of the run the word's first character came from, and its last. */\r\n firstSize: number;\r\n lastSize: number;\r\n}\r\n\r\n/**\r\n * Runs in content-stream order \u2192 text, by geometry alone and independently of\r\n * the render: two runs are glued only when they share a baseline and the gap\r\n * between them is under 0.15 em. Same reading as `tools/render-lint.ts`,\r\n * rewritten here because `src/` never imports `tools/`. `owner[k]` is the run\r\n * character `k` of the text came from, -1 for a space this reading added.\r\n */\r\nconst joinRuns = (runs: readonly ConservationRun[]): { text: string; owner: number[] } => {\r\n let text = \"\";\r\n const owner: number[] = [];\r\n const separate = (): void => {\r\n text += \" \";\r\n owner.push(-1);\r\n };\r\n runs.forEach((run, i) => {\r\n text += run.text;\r\n for (let k = 0; k < run.text.length; k++) owner.push(i);\r\n const next = runs[i + 1];\r\n if (next === undefined) return;\r\n if (run.hasEOL) {\r\n separate();\r\n return;\r\n }\r\n const em = Math.max(run.fontSize, 1);\r\n const sameLine = Math.abs(next.y - run.y) < 0.5 * em;\r\n const gap = next.x - (run.x + run.width);\r\n if (!(sameLine && gap < 0.15 * em && gap > -0.5 * em)) separate();\r\n });\r\n return { text, owner };\r\n};\r\n\r\nconst sourceWords = <R extends ConservationRun>(\r\n pages: readonly (readonly R[])[],\r\n excluded: ReadonlySet<number>,\r\n): SourceWord[] =>\r\n pages.flatMap((pageRuns, index) => {\r\n if (excluded.has(index)) return [];\r\n const runs = pageRuns;\r\n const { text, owner } = joinRuns(runs);\r\n const sizeAt = (k: number): number => runs[owner[k]!]?.fontSize ?? 0;\r\n const words: SourceWord[] = [];\r\n let gap: string[] = [];\r\n for (const m of text.matchAll(/\\S+/g)) {\r\n const raw = m[0];\r\n const key = conservationKey(raw);\r\n if (key.length > 0) {\r\n words.push({\r\n raw,\r\n key,\r\n page: index + 1,\r\n gap,\r\n firstSize: sizeAt(m.index),\r\n lastSize: sizeAt(m.index + raw.length - 1),\r\n });\r\n gap = [];\r\n } else gap.push(raw);\r\n }\r\n return words;\r\n });\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 page side \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\ninterface PageWord {\r\n key: string;\r\n at: PageWordAt;\r\n}\r\n\r\nexport interface PublishedPage {\r\n readonly blocks: readonly string[];\r\n readonly extras?: readonly string[];\r\n /** What the caller can say about each published block WITHOUT the library knowing its markup, and which two of the\r\n * three repairs need (09/11/2026). Index by index with `blocks`; absent means \u00AB I cannot say \u00BB, and a repair that\r\n * needs a fact it does not have abstains rather than guesses.\r\n * `paragraph`: the block is a plain paragraph of prose \u2014 not a cell, not a list item, not a heading. Joining two\r\n * blocks is only ever proposed for two of those.\r\n * `joinableWithNext`: nothing of the page sits between this block and the next one, so joining them would move no\r\n * other content. In Confluence's storage format that means two `<p>` elements side by side with only blank text\r\n * between them; in another destination it means whatever that destination's \u00AB side by side \u00BB is. */\r\n readonly blockFacts?: readonly { readonly paragraph: boolean; readonly joinableWithNext: boolean }[];\r\n /**\r\n * THE PAGE'S UNITS, as the caller cuts them: what its destination treats as one block-level element \u2014 a paragraph, a\r\n * heading, a table. Two of the three repairs reason on units, not on blocks, because a unit may hold several blocks\r\n * (a line break inside a paragraph ends a block, not the paragraph).\r\n *\r\n * Three facts per unit, each one the caller's to state and none of them naming a format:\r\n * `blocks` \u2014 the `blocks` indices it holds, in order. Only blocks that carry a word, numbered as this check numbers\r\n * them, so an empty cell shifts nothing.\r\n * `paragraphOrHeading` \u2014 the destination treats it as prose or a title. A lost passage may only be anchored at the\r\n * edge of such a unit: put back inside a table or a list it would land in a cell nobody asked for.\r\n * `joinable` \u2014 it can be merged with the next unit WITHOUT LOSING ANYTHING IT CARRIES. A paragraph with its own\r\n * styling is not joinable, because merging it would drop that styling silently.\r\n * `adjacentToNext` \u2014 nothing of the page sits between this unit and the next, so merging them, or putting a passage\r\n * between them, moves no other content.\r\n *\r\n * Absent means \u00AB I cannot say \u00BB: a repair that needs a unit fact it does not have abstains rather than guesses.\r\n */\r\n readonly units?: readonly {\r\n readonly blocks: readonly number[];\r\n readonly paragraphOrHeading: boolean;\r\n readonly joinable: boolean;\r\n readonly adjacentToNext: boolean;\r\n }[];\r\n}\r\n\r\n/**\r\n * ONE REPAIR THE LIBRARY DECIDED, FOR THE CALLER TO APPLY TO ITS OWN PAGE (09/11/2026: \u00AB on le fait auj' \u00BB).\r\n *\r\n * The check proves what is wrong and WHERE, in the coordinates of the page it was given \u2014 a block index, and a\r\n * character index inside that block's text. It never writes the page: composing markup is the caller's job, because\r\n * only the caller knows its markup. So a repair comes back as a list of these, and the caller applies them (for\r\n * Confluence, `pipeline/confluence-page-edits.ts#applyPageEdits`), re-checks, and keeps or undoes the lot.\r\n *\r\n * `insert-space`: put one space inside block `block`, before the character at `atChar` \u2014 the re-split of a glued word.\r\n * `insert-block-after`: publish `text` as a NEW block of its own, right after block `block` (`-1` means before the\r\n * first block) \u2014 a lost passage put back where the source says it belongs. The caller writes it in its own markup,\r\n * escaping as its format requires.\r\n * `join-with-next`: make block `block` and the next one ONE block, separated by `separator` \u2014 two paragraphs the\r\n * source proves were cut in mid-sentence.\r\n *\r\n * Every index is one in the `PublishedPage` as given: a caller that applies several edits applies them so that they do\r\n * not shift one another (back to front, as the Confluence applier does).\r\n */\r\nexport type PageEdit =\r\n | { readonly kind: \"insert-space\"; readonly block: number; readonly atChar: number }\r\n /** Publish `text` as a new UNIT of its own, right after unit `unit`; `-1` means before the first unit. */\r\n | { readonly kind: \"insert-unit-after\"; readonly unit: number; readonly text: string }\r\n /** Make unit `unit` and the next one ONE unit, their texts separated by one space. */\r\n | { readonly kind: \"join-units\"; readonly unit: number };\r\n\r\n/** A published page's located words: the TEXT of each block, numbered exactly as `readPage` numbers the storage XHTML's\r\n * (`PageWordAt` = block, then word inside it), so the two paths give the same verdict on the same content. */\r\nexport const pageWordsOfPublished = (page: PublishedPage): { body: PageWord[]; extras: string[] } => {\r\n const body: PageWord[] = [];\r\n let block = 0;\r\n for (const text of page.blocks) {\r\n const keys = wordKeysOf(text);\r\n if (keys.length === 0) continue;\r\n keys.forEach((key, word) => body.push({ key, at: { block, word } }));\r\n block += 1;\r\n }\r\n return { body, extras: [...(page.extras ?? [])] };\r\n};\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 word reading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Greedy string tiling, order ignored: the longest shared run of words first,\r\n * then the next longest among what remains, down to one word. Every tile is\r\n * kept \u2014 order is not this check's question. Returns, per source word, the\r\n * page word it was matched to, or -1.\r\n */\r\nconst tile = (src: readonly string[], ren: readonly string[]): { srcTo: Int32Array; renUsed: Uint8Array } => {\r\n const where = new Map<string, number[]>();\r\n src.forEach((k, i) => {\r\n const list = where.get(k);\r\n if (list === undefined) where.set(k, [i]);\r\n else list.push(i);\r\n });\r\n const buckets: [number, number][][] = [];\r\n let top = 0;\r\n ren.forEach((k, j) => {\r\n for (const i of where.get(k) ?? []) {\r\n if (i > 0 && j > 0 && src[i - 1] === ren[j - 1]) continue; // not a maximal start\r\n let len = 1;\r\n while (i + len < src.length && j + len < ren.length && src[i + len] === ren[j + len]) len++;\r\n (buckets[len] ??= []).push([i, j]);\r\n top = Math.max(top, len);\r\n }\r\n });\r\n const srcTo = new Int32Array(src.length).fill(-1);\r\n const renUsed = new Uint8Array(ren.length);\r\n for (let len = top; len >= 1; len--) {\r\n const bucket = buckets[len];\r\n // Pieces re-queued while this bucket is read go to strictly shorter buckets.\r\n for (let q = 0; bucket !== undefined && q < bucket.length; q++) {\r\n const [i, j] = bucket[q]!;\r\n let free = true;\r\n for (let k = 0; k < len && free; k++) free = srcTo[i + k] === -1 && renUsed[j + k] === 0;\r\n if (free) {\r\n for (let k = 0; k < len; k++) {\r\n srcTo[i + k] = j + k;\r\n renUsed[j + k] = 1;\r\n }\r\n continue;\r\n }\r\n let start = -1;\r\n for (let k = 0; k <= len; k++) {\r\n const ok = k < len && srcTo[i + k] === -1 && renUsed[j + k] === 0;\r\n if (ok && start < 0) start = k;\r\n if (!ok && start >= 0) {\r\n (buckets[k - start] ??= []).push([i + start, j + start]);\r\n start = -1;\r\n }\r\n }\r\n }\r\n }\r\n return { srcTo, renUsed };\r\n};\r\n\r\n/** A multiset of keys that absorbs leftover source words, in source order.\r\n * Known limit: it is unpositioned, so a dropped standalone number equal to a number the page draws for an ordered list is not seen by this guard. */\r\nconst absorb = (leftover: number[], words: readonly SourceWord[], texts: readonly string[]): number[] => {\r\n const bag = new Map<string, number>();\r\n for (const t of texts) for (const key of wordKeysOf(t)) bag.set(key, (bag.get(key) ?? 0) + 1);\r\n return leftover.filter((i) => {\r\n const n = bag.get(words[i]!.key) ?? 0;\r\n if (n === 0) return true;\r\n bag.set(words[i]!.key, n - 1);\r\n return false;\r\n });\r\n};\r\n\r\n/**\r\n * Runs of 2+ CONSECUTIVE leftover words of the `many` side that spell one\r\n * leftover word of the `one` side. Consecutive means adjacent in that side's\r\n * own sequence, both words leftover. Returns [manyRun, oneIndex] pairs.\r\n */\r\nconst spelledRuns = (\r\n manyLeft: readonly number[],\r\n manyKey: (i: number) => string,\r\n manyAdjacent: (a: number, b: number) => boolean,\r\n oneLeft: readonly number[],\r\n oneKey: (i: number) => string,\r\n taken: { many: Set<number>; one: Set<number> },\r\n): [number[], number][] => {\r\n const byKey = new Map<string, number[]>();\r\n const prefixes = new Set<string>();\r\n for (const o of oneLeft) {\r\n if (taken.one.has(o)) continue;\r\n const k = oneKey(o);\r\n (byKey.get(k) ?? byKey.set(k, []).get(k)!).push(o);\r\n for (let n = 1; n <= k.length; n++) prefixes.add(k.slice(0, n));\r\n }\r\n const found: [number[], number][] = [];\r\n for (let a = 0; a < manyLeft.length; a++) {\r\n if (taken.many.has(manyLeft[a]!)) continue;\r\n let acc = \"\";\r\n for (let b = a; b < manyLeft.length; b++) {\r\n const idx = manyLeft[b]!;\r\n if (taken.many.has(idx) || (b > a && !manyAdjacent(manyLeft[b - 1]!, idx))) break;\r\n acc += manyKey(idx);\r\n if (!prefixes.has(acc)) break;\r\n const candidates = b > a ? byKey.get(acc)?.filter((o) => !taken.one.has(o)) : undefined;\r\n if (candidates === undefined || candidates.length === 0) continue;\r\n const run = manyLeft.slice(a, b + 1);\r\n run.forEach((i) => taken.many.add(i));\r\n taken.one.add(candidates[0]!);\r\n found.push([run, candidates[0]!]);\r\n // eslint-disable-next-line sonarjs/updated-loop-counter -- the outer scan resumes after the run just claimed (a = b)\r\n a = b;\r\n break;\r\n }\r\n }\r\n return found;\r\n};\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 the verdict \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/** How many times each character of `key` occurs. */\r\nexport const letterCounts = (key: string): Map<string, number> => {\r\n const counts = new Map<string, number>();\r\n for (const c of key) counts.set(c, (counts.get(c) ?? 0) + 1);\r\n return counts;\r\n};\r\n\r\n/** Takes `key`'s letters from `pool` if all of them are there; leaves the pool untouched otherwise. */\r\nconst takeLetters = (key: string, pool: Map<string, number>): boolean => {\r\n const need = letterCounts(key);\r\n for (const [c, n] of need) if ((pool.get(c) ?? 0) < n) return false;\r\n for (const [c, n] of need) pool.set(c, pool.get(c)! - n);\r\n return true;\r\n};\r\n\r\nconst pagesOf = (indices: Iterable<number>, words: readonly SourceWord[]): number[] =>\r\n [...new Set([...indices].map((i) => words[i]!.page))].sort((a, b) => a - b);\r\n\r\nexport function textConservation<R extends ConservationRun>(\r\n sourceRuns: readonly (readonly R[])[],\r\n /** The page: its TEXT block by block. No markup ever reaches this check (09/11/2026) \u2014 the caller converts its own\r\n * render (`pipeline/confluence-page-reading.ts#confluencePageOf` for Confluence). */\r\n published: PublishedPage,\r\n options: ConservationOptions = {},\r\n): ConservationVerdict {\r\n const src = sourceWords(sourceRuns, options.excludedPages ?? new Set());\r\n const { body, extras } = pageWordsOfPublished(published);\r\n\r\n // WORD READING \u2014 body text first, then extras, then deliberate removals.\r\n const { srcTo, renUsed } = tile(\r\n src.map((w) => w.key),\r\n body.map((w) => w.key),\r\n );\r\n let srcLeft: number[] = [];\r\n srcTo.forEach((j, i) => {\r\n if (j === -1) srcLeft.push(i);\r\n });\r\n srcLeft = absorb(srcLeft, src, extras);\r\n srcLeft = absorb(srcLeft, src, options.deliberateRemovals ?? []);\r\n const pageLeft: number[] = [];\r\n renUsed.forEach((used, j) => {\r\n if (used === 0) pageLeft.push(j);\r\n });\r\n\r\n const taken = { many: new Set<number>(), one: new Set<number>() };\r\n const glued = spelledRuns(\r\n srcLeft,\r\n (i) => src[i]!.key,\r\n (a, b) => b === a + 1,\r\n pageLeft,\r\n (j) => body[j]!.key,\r\n taken,\r\n );\r\n const takenSplit = { many: new Set<number>(), one: new Set<number>(taken.many) };\r\n const split = spelledRuns(\r\n pageLeft.filter((j) => !taken.one.has(j)),\r\n (j) => body[j]!.key,\r\n (a, b) => b === a + 1 && body[a]!.at.block === body[b]!.at.block,\r\n srcLeft,\r\n (i) => src[i]!.key,\r\n takenSplit,\r\n );\r\n\r\n const respacings: Respacing[] = [];\r\n const explained = new Set<number>();\r\n let gluedWords = 0;\r\n for (const [run, j] of glued) {\r\n run.forEach((i) => explained.add(i));\r\n const raws = run.map((i) => src[i]!.raw);\r\n const correctJoin =\r\n raws.slice(0, -1).every((r) => HYPHEN_END.test(r)) ||\r\n run.every((i) => src[i]!.key.length <= 1) ||\r\n IDEOGRAPHIC.test(raws.join(\"\"));\r\n if (correctJoin) continue;\r\n gluedWords += 1;\r\n respacings.push({ kind: \"glued\", page: src[run[0]!]!.page, pageWords: [body[j]!.at], sourceWords: raws });\r\n }\r\n for (const [run, i] of split) {\r\n explained.add(i);\r\n gluedWords += 1;\r\n respacings.push({\r\n kind: \"split\",\r\n page: src[i]!.page,\r\n pageWords: run.map((j) => body[j]!.at),\r\n sourceWords: [src[i]!.raw],\r\n });\r\n }\r\n\r\n // LETTER READING \u2014 every leftover source word, in source order, against the\r\n // page's leftover letters, document-wide.\r\n const pool = letterCounts(pageLeft.map((j) => body[j]!.key).join(\"\"));\r\n const lost: number[] = [];\r\n const disagree: number[] = [];\r\n const covered: number[] = [];\r\n for (const i of srcLeft) {\r\n const inLetters = takeLetters(src[i]!.key, pool);\r\n if (explained.has(i)) {\r\n if (!inLetters) disagree.push(i);\r\n } else if (inLetters) covered.push(i);\r\n else lost.push(i);\r\n }\r\n gluedWords += covered.length;\r\n const lostLetters = lost.reduce((n, i) => n + src[i]!.key.length, 0);\r\n\r\n // Lost words come in source order: each run of consecutive ones is a passage.\r\n const anchor = (i: number): LostPassageAnchor => {\r\n if (i < 0 || i >= src.length) return \"document-edge\";\r\n const j = srcTo[i]!;\r\n return j === -1 ? \"unanchored\" : body[j]!.at;\r\n };\r\n const lostPassages: LostPassage[] = [];\r\n for (let k = 0; k < lost.length;) {\r\n let end = k;\r\n while (end + 1 < lost.length && lost[end + 1] === lost[end]! + 1) end++;\r\n const run = lost.slice(k, end + 1);\r\n lostPassages.push({\r\n page: src[run[0]!]!.page,\r\n sourceWords: run.flatMap((i, k) => (k === 0 ? [src[i]!.raw] : [...src[i]!.gap, src[i]!.raw])),\r\n before: anchor(run[0]! - 1),\r\n after: anchor(run[run.length - 1]! + 1),\r\n });\r\n k = end + 1;\r\n }\r\n\r\n const unmatchedPageWords = pageLeft.filter((j) => !taken.one.has(j) && !takenSplit.many.has(j)).length;\r\n\r\n const sourceOfPageWords: (SourceWordLink | null)[][] = [];\r\n for (const { at } of body) (sourceOfPageWords[at.block] ??= []).push(null);\r\n srcTo.forEach((j, i) => {\r\n if (j === -1) return;\r\n const { at } = body[j]!;\r\n sourceOfPageWords[at.block]![at.word] = { index: i, firstSize: src[i]!.firstSize, lastSize: src[i]!.lastSize };\r\n });\r\n\r\n const verdict = (decision: ConservationDecision, rule: ConservationRule, pages: number[]): ConservationVerdict => ({\r\n decision,\r\n rule,\r\n margin: decision === \"lost\" ? lostLetters : 0,\r\n lostLetters,\r\n gluedWords,\r\n pages,\r\n unmatchedPageWords,\r\n respacings,\r\n sourceLetters: src.reduce((n, w) => n + w.key.length, 0),\r\n lostPassages,\r\n sourceOfPageWords,\r\n });\r\n if (disagree.length > 0) return verdict(\"abstain\", \"readings-disagree\", pagesOf(disagree, src));\r\n if (lost.length > 0) return verdict(\"lost\", \"letters-missing\", pagesOf(lost, src));\r\n const gluedPages = [...new Set([...pagesOf(covered, src), ...respacings.map((r) => r.page)])].sort((a, b) => a - b);\r\n if (covered.length > 0) return verdict(\"glued\", \"letters-cover-unmatched-words\", gluedPages);\r\n if (gluedWords > 0) return verdict(\"glued\", \"respaced-words\", gluedPages);\r\n return verdict(\"ok\", \"all-words-found\", []);\r\n}\r\n", "/** Re-splits a glued page word where the PDF's own reading proves the boundaries, by adding spaces to the storage XHTML's text nodes \u2014 and undoes the whole repair if the re-check comes out worse in any way.\r\n * NOT here: finding the glued words (`pipeline/text-conservation.ts`), what the document record keeps (`pipeline/publish-conservation.ts`), nor joining a word published split \u2014 this lot repairs glued words only.\r\n * Called by: `pipeline/publish-conservation.ts`, once per checked PDF render. */\r\n\r\n/**\r\n * THE RULE (21/09/2026, lot 4). A page token is re-split ONLY when\r\n * its letters, as the check normalises them, are EXACTLY the concatenation of\r\n * the 2+ consecutive source words the word reading proved; a space goes at\r\n * each boundary the source gives, and nothing else changes. Anything less\r\n * certain is left alone and stays counted as glued, visible on the dashboard.\r\n *\r\n * WHY THE XHTML AND NOT THE DOCUMENT MODEL. The finding locates a word by\r\n * block and word index in the storage XHTML the check read; the same reader\r\n * hands back the text nodes those indices came from, so the edit lands on the\r\n * exact characters, with no second mapping to get wrong. A space added inside\r\n * a text node leaves every tag where it was: bold runs, links and images keep\r\n * their markup, and an image is never inside a word (it ends the\r\n * block for the reader). A boundary at a formatting edge gets its space at\r\n * the end of the first word's text node, inside that run.\r\n *\r\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the\r\n * first of the next, the page may carry non-letters (\u00AB IV.1.1)Vrsta \u00BB). They\r\n * are split as the source words carry them \u2014 the first word's trailing\r\n * characters, then the next word's leading ones; if the page's characters\r\n * there are not exactly those, the token is left alone rather than guessed.\r\n *\r\n * THE UNDO. The repaired page is checked again. It must lose no letter, keep\r\n * every page letter in the same order, create no word the PDF lacks, and\r\n * leave at most the glued words it did not repair; otherwise the original\r\n * page and its verdict are kept, whole \u2014 never a partial repair.\r\n *\r\n * \u26A0\uFE0F CLIENT TEXT, in memory only, like the verdict it reads.\r\n */\r\n\r\nimport {\r\n conservationKey,\r\n type ConservationVerdict,\r\n type PageEdit,\r\n type PublishedPage,\r\n type Respacing,\r\n} from \"doc-ir/pipeline/text-conservation\";\r\n\r\n/** One character of a published block: its text, its letters, and where it ends IN THAT BLOCK'S TEXT.\r\n * Until 09/11/2026 `end` was an offset in the storage XHTML and a unit could be an entity (`&amp;`): the decision\r\n * then only worked on one markup. It is now an index in the text the caller published, which every destination has. */\r\ninterface Unit {\r\n text: string;\r\n key: string;\r\n end: number;\r\n}\r\n\r\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole one), so `end` is a UTF-16 index usable for `slice`. */\r\nconst UNIT = /[\\s\\S]/gu;\r\n\r\n/** The units of one published block. */\r\nconst unitsOf = (text: string): Unit[] =>\r\n [...text.matchAll(UNIT)].map((m) => ({ text: m[0], key: conservationKey(m[0]), end: m.index + m[0].length }));\r\n\r\n/** The block's words, as the check splits them: runs of non-space units with at least one letter.\r\n * Same split as `text-conservation.ts#wordKeysOf`, kept by unit to locate offsets. */\r\nconst wordsOf = (units: readonly Unit[]): Unit[][] => {\r\n const words: Unit[][] = [];\r\n let current: Unit[] = [];\r\n const close = (): void => {\r\n if (conservationKey(current.map((u) => u.text).join(\"\")).length > 0) words.push(current);\r\n current = [];\r\n };\r\n for (const u of units) {\r\n if (/^\\s+$/u.test(u.text)) close();\r\n else current.push(u);\r\n }\r\n close();\r\n return words;\r\n};\r\n\r\n/** Leading or trailing characters of a source word that carry no letter. */\r\nconst edge = (raw: string, side: \"lead\" | \"trail\"): string => {\r\n const chars = [...raw];\r\n const order = side === \"lead\" ? chars : [...chars].reverse();\r\n const out: string[] = [];\r\n for (const c of order) {\r\n if (conservationKey(c).length > 0) break;\r\n out.push(c);\r\n }\r\n return (side === \"lead\" ? out : [...out].reverse()).join(\"\");\r\n};\r\n\r\n/** The renderer's zero-width space before a superscript glued to a word (`renderer/storage.ts#renderInlines`, PLATFORM-STATUS \u00A781)\r\n * carries nothing the source says: it is passed over between the words, and the space goes before it. */\r\nconst visible = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\r\n\r\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\r\nconst insertionsFor = (blocks: readonly string[], r: Respacing): number[] | undefined => {\r\n const at = r.pageWords[0];\r\n if (r.kind !== \"glued\" || r.pageWords.length !== 1 || at === undefined || r.sourceWords.length < 2) return undefined;\r\n const text = blocks[at.block];\r\n const units = text === undefined ? undefined : unitsOf(text);\r\n const word = units === undefined ? undefined : wordsOf(units)[at.word];\r\n if (word === undefined) return undefined;\r\n const keys = r.sourceWords.map(conservationKey);\r\n const tokenKey = conservationKey(word.map((u) => u.text).join(\"\"));\r\n // Unit by unit, the letters must add up to the token's own (NFKC can join\r\n // across characters), and the token must be exactly the source words.\r\n if (word.map((u) => u.key).join(\"\") !== tokenKey || keys.join(\"\") !== tokenKey) return undefined;\r\n\r\n const offsets: number[] = [];\r\n let u = 0;\r\n let letters = 0;\r\n for (let i = 0; i < keys.length - 1; i++) {\r\n const boundary = letters + keys[i]!.length;\r\n // The unit carrying the first word's last letter must end exactly there.\r\n while (u < word.length && letters + word[u]!.key.length <= boundary && letters < boundary)\r\n letters += word[u++]!.key.length;\r\n if (letters !== boundary) return undefined;\r\n // Non-letters up to the next word's first letter, split as the source says.\r\n let next = u;\r\n while (next < word.length && word[next]!.key.length === 0) next++;\r\n const between = word.slice(u, next);\r\n const trail = edge(r.sourceWords[i]!, \"trail\");\r\n if (visible(between.map((x) => x.text).join(\"\")) !== trail + edge(r.sourceWords[i + 1]!, \"lead\")) return undefined;\r\n let taken = \"\";\r\n let k = 0;\r\n while (taken.length < trail.length && k < between.length) taken += visible(between[k++]!.text);\r\n if (taken !== trail) return undefined;\r\n offsets.push(word[u + k - 1]!.end);\r\n u += k;\r\n }\r\n return offsets;\r\n};\r\n\r\n/** The spaces this check PROVES, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\r\n * that got all of theirs. Writes nothing: composing a page is the caller's job (`PageEdit`). */\r\nexport function gluedWordEdits(\r\n page: PublishedPage,\r\n respacings: readonly Respacing[],\r\n): { edits: PageEdit[]; repaired: number } {\r\n const glued = respacings.filter((r) => r.kind === \"glued\");\r\n if (glued.length === 0) return { edits: [], repaired: 0 };\r\n const taken = new Set<string>();\r\n const edits: PageEdit[] = [];\r\n let repaired = 0;\r\n for (const r of glued) {\r\n const block = r.pageWords[0]?.block;\r\n const at = insertionsFor(page.blocks, r);\r\n if (at === undefined || block === undefined || at.some((o) => taken.has(`${block}:${o}`))) continue;\r\n for (const atChar of at) {\r\n taken.add(`${block}:${atChar}`);\r\n edits.push({ kind: \"insert-space\", block, atChar });\r\n }\r\n repaired += 1;\r\n }\r\n return { edits, repaired };\r\n}\r\n\r\n/** Whether the re-checked page is no worse than the original in any way. Exported since 09/11/2026: the loop that\r\n * applies the edits and re-checks belongs to the caller (it writes the page), but the RULE for keeping or undoing a\r\n * repair is this check's and stays here \u2014 a caller that invented its own could keep a page that lost a letter. */\r\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict, repaired: number): boolean =>\r\n after.lostLetters <= before.lostLetters &&\r\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\r\n after.decision !== \"abstain\" &&\r\n after.gluedWords <= before.gluedWords - repaired &&\r\n after.unmatchedPageWords <= before.unmatchedPageWords &&\r\n after.respacings.filter((r) => r.kind === \"split\").length <=\r\n before.respacings.filter((r) => r.kind === \"split\").length;\r\n", "/** The one \u00AB fold the blanks and trim \u00BB of the app: every run of whitespace (a non-breaking space included) becomes one\r\n * space, then the ends are trimmed.\r\n * NOT here: a fold that keeps line breaks apart (`extractor/pdf-scanned.ts`) nor the page-furniture key (`layout/page-furniture.ts`).\r\n * Called by: the docx, pptx and SmartArt readers, `pipeline/cut-paragraph-repair.ts`, `extractor/pdf-letter-spacing.ts`, `extractor/pdf-facts.ts`. */\r\nexport const collapseBlanks = (text: string): string => text.replace(/\\s+/g, \" \").trim();\r\n", "/** The lists a PDF never declares, found in the markers and the hanging indent\n * of its lines.\n * NOT here: how a list becomes IR blocks, nor paragraph grouping \u2014 both in\n * `extractor/pdf-paragraphs.ts`.\n * Called by: `extractor/pdf-paragraphs.ts`, `extractor/pdf-line-breaks.ts`. */\nimport { maxOf } from \"../lib/extent\";\nimport { SAME_LINE_PT } from \"./tolerances\";\n\n/**\n * list \u2014 LES LISTES D'UN PDF, sans mod\u00E8le.\n *\n * POURQUOI CE MODULE EXISTE. Aucune r\u00E8gle ne cherchait de liste dans ce d\u00E9p\u00F4t :\n * z\u00E9ro liste sur trente-cinq documents, pas \u00AB aucune trouv\u00E9e \u00BB mais rien pour en\n * chercher. C'est l'une des quatre pertes silencieuses relev\u00E9es en lisant\n * Matterhorn (`docs/MATTERHORN-CIBLES.md` [purged 27/09/2026, git history]).\n *\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * LA R\u00C8GLE, ET LES DEUX CONDITIONS QUI LA FONDENT\n *\n * **Un item est une ligne RETIR\u00C9E par rapport au corps. Une liste est une suite\n * d'au moins deux items, dont la MOITI\u00C9 au moins porte un marqueur lisible.**\n *\n * Les deux conditions viennent du mainteneur (16/09/2026) et chacune a \u00E9t\u00E9 mesur\u00E9e\n * avant d'\u00EAtre \u00E9crite (`tools/list-map.ts`, `docs/ETUDE-BIBLIOTHEQUES-PDF.md` [purged 27/09/2026, git history]\n * le\u00E7on 19) :\n *\n * \u00AB sans retrait, ce n'est pas une puce \u00BB \u2014 un marqueur SEUL ne suffit pas :\n * un tiret en t\u00EAte de phrase, un num\u00E9ro de r\u00E9f\u00E9rence, une date \u00AB 12. \u00BB en\n * portent un sans \u00EAtre des listes. Le retrait, lui, est ce que le document a\n * VOULU.\n *\n * \u00AB vaut mieux \u00EAtre assez bon que se tromper \u00BB \u2014 d'o\u00F9 le marqueur EN PLUS du\n * retrait. Sur 26 documents r\u00E9els :\n *\n * retrait seul 85 suites, 2 177 lignes \u2014 84 par document, absurde\n * retrait ET marqueur 8 suites, 119 lignes \u2014 pr\u00E9cis\n *\n * **LE BIAIS EST CHOISI, et c'est celui du d\u00E9p\u00F4t : cette r\u00E8gle SOUS-D\u00C9TECTE.**\n * Une liste manqu\u00E9e ne perd aucun texte \u2014 il reste publi\u00E9 et cherchable. Une\n * liste invent\u00E9e, elle, ment sur la structure.\n *\n * \u26A0\uFE0F **CE MODULE EST JUSTE ; LE C\u00C2BLAGE A DEMAND\u00C9 QUATRE CORRECTIFS AILLEURS.**\n * Branch\u00E9 tel quel, il a rendu Z\u00C9RO liste \u2014 et pas une seule fois \u00E0 cause de la\n * r\u00E8gle. Les items n'arrivaient jamais sous la forme attendue : une goutti\u00E8re\n * sans colonne coupait les pages \u00E0 puces en deux, la taille d'une ligne se\n * lisait sur la puce, `isCentredPair` prenait le retrait pendant pour du\n * centrage, et rien ne s\u00E9parait deux items cons\u00E9cutifs (`startsNewItem`). Tout\n * est dans `extractor/pdf-paragraphs.ts` et la le\u00E7on 20 de `docs/ETUDE-BIBLIOTHEQUES-PDF.md` [purged 27/09/2026, git history].\n *\n * CE QUE LA LITT\u00C9RATURE AJOUTE, et qu'on n'a pas retenu : le niveau\n * d'imbrication, tir\u00E9 des retraits quantifi\u00E9s successifs. Notre IR le porterait\n * (`items: IRBlock[][]`), mais aucun document mesur\u00E9 n'en a montr\u00E9 le besoin, et\n * inventer une hi\u00E9rarchie que le document ne demande pas est exactement ce qu'on\n * refuse partout ailleurs.\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * \uD83D\uDD34 **BULLETS: A LIST ONLY IN THE SIMPLE CASE (14/10/2026).**\n *\n * History. On 23/09/2026 no bulleted list was published at all: a run of bullets\n * or dashes stayed paragraphs, **the marker kept in the text** (nothing removed,\n * nothing lost). Why: a bullet is what our documents read worst (a symbol-font\n * letter, a dash glued to its word, a vector disc, a wrapped line taken for an\n * item), and the list tag is what let us REMOVE the marker, so a misread marker\n * made a false list. That rule still holds for `listRuns` (indented runs of\n * dashes, mixed runs, anything outside the simple case).\n *\n * Revision. A run is published as a bulleted list again, but only through\n * `bulletRuns` (see there for the conditions). Measured on 51 French and English\n * PDFs: 84 lists, 318 items, 0 invented list. Numbered and lettered lists are\n * unchanged.\n */\n\n/**\n * LES MARQUEURS, et la raison de chaque famille.\n *\n * \u26A0\uFE0F Le caract\u00E8re de puce est ABSENT de la couche texte dans cinq documents\n * r\u00E9els sur six \u2014 Word, InDesign et Canva le DESSINENT \u00E0 c\u00F4t\u00E9. Ce motif ne suffit\n * donc jamais \u00E0 lui seul ; c'est le retrait qui porte le signal, et lui qui\n * confirme.\n *\n * \u26A0\uFE0F And when the character IS there, it can be a LIE \u2014 see the written limits\n * below: a symbol font writes its bullet as \u00AB x \u00BB or as a private codepoint,\n * and only the font would tell. We do not read the font.\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 * `layout/list.markers.test.ts` \u2014 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 (\n * 22/09/2026). Word 2007 glues its dash to its word \u2014 \u00AB -Ensures Safety of the\n * patient \u00BB \u2014 so fixture 28 page 2 publishes 7 items as 7 paragraphs.\n *\n * Accepting a glued dash was built and measured, then dropped. The two\n * populations, over the 39 French and English PDFs \u2014 22 lines open on a dash\n * with NO blank after it, in 3 documents:\n * \u00B7 7 REAL items, fixture 28 p2, where the dash IS the bullet (read on the\n * page image);\n * \u00B7 15 that are not, and the two conditions already hold every one of them\n * out of any list on their own: 0000312 p1 \u00AB \u2013positive advanced\n * nonsquamous\u2026 \u00BB (two wrapped lines continuing \u00AB ALK\u2013positive \u00BB, not\n * indented, 45.4 pt is the body's own margin), 27 p2 \u00AB -30- \u00BB (the end mark\n * of a press release, not indented), and the timeline of 28 p3-p4\n * (\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 \u2014 and it was still dropped. On\n * 28 p2 the text ALREADY comes out one item per line: the `<ul>` was a comfort,\n * 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. Reopen it the\n * day a document really loses something 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/** Le retrait est quantifi\u00E9 : deux lignes \u00E0 53,8 et 54,1 sont au m\u00EAme niveau. */\nconst INDENT_QUANTUM_PT = 3;\n/** Un item isol\u00E9 n'est pas une liste \u2014 c'est un paragraphe indent\u00E9. */\nconst MIN_ITEMS = 2;\n\n/*\n * WRITTEN LIMIT, NOT A DEFECT TO FIX (22/09/2026). The Jev re-read\n * (`docs/ESSAI-JEV-ETIQUETAGE.md` [purged 27/09/2026, git history], French and English documents) found 35\n * items published as plain paragraphs, in 8 documents, in three shapes: marked\n * items that are NOT indented (20), several items fused into one block (8), and\n * 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\n * the indent. Measured over 34 French/English PDFs: 7 runs, 17 items, no false\n * list \u2014 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. Reopen\n * only if a real document loses something because of a missed list.\n *\n * THREE MORE FAMILIES OF BULLET, MEASURED ON 22/09/2026 AND LEFT ALONE\n * (same day: \u00AB les puces, pas de prise de t\u00EAte \u00BB \u2014 the text already\n * comes out line by line in all three, so the drawn bullet is a comfort, and a\n * marker we do not read is a marker we cannot remove 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\n * different ways, because a symbol font's glyphs have no character\n * identity and what pdf.js wrote for them (measured before its removal) was an accident of the font's\n * cmap (a symbolic TrueType (3,0) cmap maps to 0xF000+code):\n * SymbolMT 0xB7 \u2192 \u00AB \u2022 \u00BB U+2022, 68 runs, 6 documents \u2014 read today\n * Wingdings 0xFC \u2192 U+F0FC, 17 runs, safedocs 0000609 \u2014 a private\n * codepoint, published as a tofu box\n * SymbolMT 0x78 \u2192 \u00AB x \u00BB U+0078, 24 runs, fixture 25 \u2014 a LETTER\n * The character cannot be the test, so the FONT would have to be: measured\n * over the 39 French and English PDFs, every run painted in a font named\n * for a symbol family is 116 runs, 9 fonts, 8 documents, ALL of ONE\n * character and ALL bullets \u2014 0 run of prose, 0 run longer than one\n * character. The discriminant is clean; its price is not. It needs the\n * boundary to resolve the font name (`pdf-source.ts`), a new field on every\n * text run, and a new field on every line. Built and measured that way, it\n * gave ONE list \u2014 safedocs 0000609 p5, 6 items \u2014 whose 6 lines already come\n * out one per line today. Reopen it only if a document loses text for it.\n * Also tried: the private-use range U+E000\u2013U+F8FF as the test, which\n * PyMuPDF4LLM does with U+F0B7 and U+F0A7 hard-coded. No new reading, 17\n * lines on the corpus, all bullets, 0 false \u2014 but it catches only the\n * Wingdings shape, not the \u00AB x \u00BB, and it publishes a `<ul>` in place of\n * lines that are already right.\n *\n * 2. **A DISC DRAWN IN VECTOR, not written.** Fixture 26 (Canva) marks 37 lines\n * with a filled circle of 3.7 to 3.8 pt; all 37 sit 8.2 to 8.4 pt to the\n * left of their line, on its baseline band (dy 2.1 to 2.6 pt) \u2014 geometry\n * clean enough to attach. What stops it is elsewhere and it is bigger: every\n * page of that document publishes as ONE TABLE, and a table cell's blocks\n * are built without `paragraphsFromLines` (`pdf-table-render.ts`), so no\n * list is ever looked for inside a cell. The marker would change nothing.\n * And the size is no discriminant on its own: fixture 25 draws a watch with\n * 484 small paths of 26 different sizes, 1.2 to 6.3 pt, 15 of which sit just\n * left of a line.\n * 3. **A WRAPPED LINE TAKEN FOR AN ITEM.** Safedocs 0000602 p2 publishes\n * \u00AB April 6, 2020 \u00BB 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\n * of them marked \u00BB rule lets in. Counted over every item the 39 French and\n * English PDFs publish \u2014 78 of them \u2014 it is the ONLY one. One case is not a\n * family, and no 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\n * marker for the list rule, but it never leaves the text (22/09/2026).\n * The IR list has no marker type, so the only ordered rendering is `<ol>`\n * counting 1, 2, 3: stripping \u00AB a. \u00BB replaced every letter with a number, and\n * the letters were lost \u2014 16 on safedocs 0000609 p7. A run of letters is\n * therefore a BULLET list whose items keep \u00AB a. \u00BB in their text: the simplest\n * form that loses nothing and still says \"these are items\". Set aside: no list\n * at all (the items would then read as loose paragraphs), and a marker type in\n * the IR (a 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 \u2014 removed from the\n * rendering only when the list's own marker replaces it (see\n * `pdf-paragraphs.ts#groupLists`). */\n length: number;\n /** Le num\u00E9ro lu, pour un marqueur ordonn\u00E9 qui en porte un. */\n value?: number;\n}\n\n/**\n * Le marqueur en t\u00EAte d'une ligne, s'il y en a un.\n *\n * \u26A0\uFE0F **UN MARQUEUR SE LIT, IL NE S'INTERPR\u00C8TE PAS.** \u00AB ordonn\u00E9e \u00BB n'est pas une\n * inf\u00E9rence sur l'intention : c'est ce que dit un num\u00E9ro. GROBID, lui, ne\n * distingue m\u00EAme pas les deux \u2014 notre IR le demande, donc on lit le marqueur\n * plut\u00F4t que de deviner.\n *\n * \u26A0\uFE0F IT READS THE TEXT AND NOTHING ELSE. A marker the text cannot name is a\n * written limit here, not a parameter \u2014 see below.\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 m = pattern.exec(text);\n if (m !== null) return { kind, length: m[0].length };\n }\n return undefined;\n}\n\n/** Ce qu'une ligne candidate apporte \u00E0 la d\u00E9cision. */\nexport interface ListCandidate {\n /** Retir\u00E9e par rapport au corps du document \u2014 la condition N\u00C9CESSAIRE. */\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 /** Premier index de la suite, inclus. */\n start: number;\n /** Dernier index, inclus. */\n end: number;\n ordered: boolean;\n}\n\n/**\n * Les suites d'items dans une s\u00E9quence de blocs cons\u00E9cutifs.\n *\n * Un bloc entre dans la suite en cours s'il est RETIR\u00C9 ; la suite se ferme d\u00E8s\n * qu'un bloc ne l'est pas. Elle n'est retenue que si elle compte au moins\n * `MIN_ITEMS` blocs et que la moiti\u00E9 au moins portent un marqueur.\n *\n * `ordered` suit la MAJORIT\u00C9 des marqueurs lus, jamais une pr\u00E9f\u00E9rence : une\n * suite de \u00AB 1. 2. 3. \u00BB est ordonn\u00E9e parce que le document la num\u00E9rote.\n *\n * Tried and set aside (22/09/2026): requiring the run's MARKED blocks to share\n * one quantised indent \u2014 signal 3 of the literature is \u00AB bullet partner\n * detection AT THE SAME LEVEL \u00BB and we only kept the partner. Written while the\n * symbol-font marker above was being measured, to hold back the one false list\n * it produced on fixture 25 (eight booklet pages imposed on one sheet, columns\n * not cut, markers then at 138, 144, 312 and 318 pt). With the markers we\n * actually read, the level changes NOTHING over the 39 French and English PDFs.\n * A guard that guards nothing is mechanism, so it is not here \u2014 reopen it with\n * 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 close = (end: number): void => {\n if (start === undefined) return;\n const slice = candidates.slice(start, end + 1);\n const marked = slice.filter((c) => c.marker !== undefined);\n const ofKind = (kind: MarkerKind): number => marked.filter((c) => c.marker?.kind === kind).length;\n // A run of bullets or dashes is no list here (23/09/2026, see the header; the\n // simple bulleted case goes through `bulletRuns`). The majority decides, as for\n // `ordered`, and a tie falls on the side of ABSTENTION.\n const bulleted = ofKind(\"bullet\") * 2 >= marked.length;\n if (slice.length >= MIN_ITEMS && marked.length * 2 >= slice.length && !bulleted) {\n const ordered = ofKind(\"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 close(index - 1);\n }\n close(candidates.length - 1);\n return runs;\n}\n\n/**\n * THE SIMPLE BULLETED RUN (14/10/2026). A run of consecutive paragraph\n * 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, fixture 33 p5: \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\n * the last item, no further below than the list's own line spacing, is that\n * item's continuation (docx-reel/10 p38: the last item is cut in two blocks) and\n * is returned as `tail`. The list's line spacing is the largest line pitch inside\n * its own wrapped items; with none to measure it from, the whole list is REJECTED\n * (bias: abstain). Beyond that spacing the block is a paragraph of its own and the\n * list stays.\n *\n * BULLET_RUN_MAX_DRIFT_PT = 1 pt, starting value to calibrate (the coordinate\n * noise of `SAME_LINE_PT`). Measured over 51 French and English PDFs: 84 runs\n * (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\n * at 86.2 against 89.5 pt (1) and on a bullet glued to its text (1); two of them\n * 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 first = lines[0];\n if (first === undefined) return {};\n const last = lines[lines.length - 1]!;\n const pitches = lines.slice(1).map((line, k) => lines[k]!.y - line.y);\n const geometry: BlockGeometry = {\n firstLeft: first.left,\n firstY: first.y,\n lastY: last.y,\n ...(pitches.length > 0 ? { pitch: maxOf(pitches, (p) => p) } : {}),\n };\n const opener = first.lead?.text.trim();\n if (\n first.lead === undefined ||\n opener === undefined ||\n !BULLET_LEAD_CHARS.has(opener) ||\n !first.text.trimStart().startsWith(opener)\n )\n return { geometry };\n const afterOpener = lines\n .map((line) => line.text)\n .join(\" \")\n .trimStart()\n .slice(opener.length);\n return {\n geometry,\n bullet: {\n markerLeft: first.left,\n textLeft: first.lead.nextLeft,\n continuationLefts: lines.slice(1).map((line) => line.left),\n secondBullet: ANY_BULLET_LEAD.test(afterOpener),\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 near = (a: number, b: number): boolean => Math.abs(a - b) <= BULLET_RUN_MAX_DRIFT_PT;\n\n/** The simple bulleted runs among consecutive blocks \u2014 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\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((c) => c.bullet!);\n const { markerLeft, textLeft } = items[0]!;\n const simple =\n textLeft - markerLeft > BULLET_RUN_MAX_DRIFT_PT &&\n items.every(\n (item) =>\n near(item.markerLeft, markerLeft) &&\n near(item.textLeft, textLeft) &&\n !item.secondBullet &&\n item.continuationLefts.every((left) => near(left, textLeft)),\n );\n if (!simple) return undefined;\n\n const next = candidates[end + 1];\n if (\n next?.geometry === undefined ||\n next.marker !== undefined ||\n next.bullet !== undefined ||\n !near(next.geometry.firstLeft, textLeft)\n )\n return { start, end };\n const pitches = candidates.slice(start, end + 1).flatMap((c) => c.geometry?.pitch ?? []);\n // ITEMS WITHOUT A WRAPPED LINE STILL HAVE A LINE SPACING: the pitch between two consecutive one-line items\n // (05/11/2026, fixture 29 : cinq questions d'une ligne suivies d'un bloc au x du texte \u2014 l'ancien rejet en bloc\n // faisait retomber TOUTE la liste en paragraphes d\u00E8s que le chemin des titres ne consommait plus ce bloc).\n const itemPitches = candidates.slice(start, end).flatMap((c, k) => {\n const below = candidates[start + k + 1]!.geometry;\n const own = c.geometry;\n return own === undefined || below === undefined ? [] : [own.lastY - below.firstY].filter((d) => d > 0);\n });\n const spacing =\n pitches.length > 0 ? maxOf(pitches, (p) => p) : itemPitches.length > 0 ? maxOf(itemPitches, (p) => p) : undefined;\n if (spacing === undefined) return undefined;\n const gap = candidates[end]!.geometry!.lastY - next.geometry.firstY;\n // The tail lies BELOW the last item: a block read after a jump up the page (another column) is never one (review of 14/10/2026).\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.\n * Starting value to calibrate: 1 pt, the coordinate-noise tolerance of\n * `hangsFromMarker`. Measured on the French and English PDFs (22/09/2026):\n * - aligned: an item's text start read twice (after its marker, on its second\n * line) agrees to 0.05 pt on 53 of 64 items; the one unnumbered block that\n * belongs to an item (0000609 p1, \u00AB and crew across borders \u00BB, the last line\n * of item 1 split off) is 0.0 pt from its item's text;\n * - not aligned: the nearest disagreement is 1.3 pt, on a form (0000523), and\n * the nearest block after an item that does not 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\n * resumes after the marker on the first line, and the left of the second line\n * (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 (22/09/2026).\n *\n * `<ol>` counts its `<li>`, so an unnumbered block let in as an item shifts every\n * number after it: safedocs 0000713 p8 published \u00AB 1. \u00BB to \u00AB 5. \u00BB as 3 to 7. The\n * left edge of a block includes its marker, and an unnumbered block (a letter or\n * a 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\n * 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,\n * no gap, no duplicate) over at least `MIN_ITEMS` items. Otherwise every block\n * stays a paragraph, its written number in its text. Every tool read on\n * 22/09/2026 keeps the written number; none checks the sequence\n * (`docs/ETUDE-BIBLIOTHEQUES-PDF.md` [purged 27/09/2026, git history], lesson 21).\n *\n * Set aside (22/09/2026): letting in a NON-indented block aligned on the item's\n * text. It would put the \u00AB b) \u00BB and \u00AB c) \u00BB of 0000713 p8 back into item 5, but\n * the same geometry is a body paragraph after a list whose markers hang in the\n * margin (fixture 29: three body paragraphs 0.0 pt from the text of the bullet\n * before them). Nothing tells the two apart, so only blocks already in the run\n * 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 opener: ListCandidate | undefined;\n\n const close = (): void => {\n const exact = numbers.every((n, k) => n === numbers[0]! + k);\n if (items.length >= MIN_ITEMS && exact) 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 opener = 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 opener = candidate;\n } else if (opener !== undefined && continuesItem(opener, candidate)) {\n items[items.length - 1]!.push(index);\n } else {\n close();\n pieces.push({ kind: \"paragraph\", index });\n }\n }\n close();\n return pieces;\n}\n\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", "/** Joins two adjacent top-level paragraphs of the storage XHTML into one when the render cut a sentence between them \u2014 the shape says so and the PDF reads their edge words in a row, at one size \u2014 and undoes the whole join if the re-check comes out worse in any way.\r\n * NOT here: where a line break is decided (`extractor/pdf-line-breaks.ts`), the word reading that links page words to source words (`pipeline/text-conservation.ts`), the other repairs (`pipeline/lost-text-repair.ts`, `pipeline/glued-word-repair.ts`), headings cut in two, nor the paragraphs of a table cell or of a list item (measured, then refused \u2014 see the module note).\r\n * Called by: `pipeline/publish-conservation.ts`, once per checked PDF render, after the other two repairs. */\r\n\r\n/**\r\n * THE RULE (22/09/2026, lot 35 \u2014 remedy B of the mid-sentence cuts\r\n * diagnosis). Two `<p>` children of the SAME element, with nothing between\r\n * them, become one ONLY when two independent readings agree:\r\n * - THE SHAPE, in our render: the first does not end with `. : ; ! ? \u00BB \" \u2026 )`\r\n * and the second starts with a word all in lower case (signature S2 of\r\n * `tools/render-lint.ts`, rewritten here because `src/` never imports\r\n * `tools/`). A second paragraph that opens on a list marker (\u00AB a. \u00BB,\r\n * \u00AB iv) \u00BB, \u00AB \u2013 \u00BB, `layout/list.ts#markerOf`) or on a token of ONE letter is\r\n * never a continuation.\r\n * - THE SOURCE: the last three words of the first and the first three of\r\n * the second are six source words in a row in the PDF's reading, furniture\r\n * left out, and the two edge words are set at the same size. The link from\r\n * page word to source word is the check's own tiling, so nothing is read\r\n * twice.\r\n * Anything else stays as it is. A paragraph cut in two is still all there\r\n * and searchable; two paragraphs joined by mistake are a sentence that never\r\n * existed.\r\n *\r\n * WHERE IT WORKS: the page's own `<p>` only.\r\n *\r\n * \u26A0\uFE0F MEASURED IN A CELL, THEN REFUSED (condition, 22/09/2026: not\r\n * one wrong join in a cell). Joining the `<p>` of ONE cell \u2014 a cell's lines\r\n * are each a paragraph (`extractor/pdf-table-render.ts`) \u2014 gives 65 joins on\r\n * the 39 French and English PDFs, 64 of them right, including the two cuts\r\n * of safedocs 0000754 p2 (defect E) and 49 lines of fixture 26 rejoined.\r\n * THE ONE WRONG, fixture 26 p13, cell of \u00AB Moyens de Communication Interne \u00BB:\r\n * \u00AB Le chat via Google drive \u00BB \u2016 \u00AB ordinateur portable pour chaque\r\n * collaborateur. \u00BB are TWO bullets of a list (checked against the page\r\n * image); the bullet character is DRAWN, absent from the text layer, so the\r\n * second item opens on a lowercase word the PDF reads right after the first.\r\n * A cell packs items without markers far more often than prose does \u2014 that\r\n * is what the measurement shows, and why the same rule is not safe there.\r\n * The two `<p>` of one list item, and two cells side by side, are refused for\r\n * the same reason (0000713 p5: two items of one cell must stay two).\r\n *\r\n * MEASURED on the 39 French and English PDFs, publish path, 22/09/2026: 18\r\n * joins in 7 documents (16 groups, two of them three paragraphs), 61 \u2192 43\r\n * pairs of the S2 shape at the top level, every verdict unchanged, no letter\r\n * lost and none added. Each join was read: 17 right, 1 wrong (below).\r\n *\r\n * \u26A0\uFE0F WHY A TOKEN OF ONE LETTER STOPS THE JOIN. Two joins of a first\r\n * measurement were wrong, both on fixture 25: the bullet of a three-line spec\r\n * list is drawn \u00AB x \u00BB in the text layer, so it reads as a lowercase word, and\r\n * the PDF does read it right after the line before. `markerOf` does not catch\r\n * it \u2014 nothing in the extraction reads a symbol font's glyph as a bullet.\r\n * DECIDED (22/09/2026): a paragraph opening on a token of ONE\r\n * letter is never a continuation. It costs none of the 17 right joins.\r\n * - THE LIMIT IT BRINGS, written and accepted: a real continuation opening\r\n * on \u00AB il \u00BB, \u00AB y \u00BB, \u00AB \u00E0 \u00BB, \u00AB a \u00BB is refused too \u2014 \u00AB \u2026tout ce qu'il \u2016 y a\r\n * de plus simple \u00BB. No such case in the 39 French and English PDFs.\r\n * - TRIED AND SET ASIDE: reading the glyph's FONT to know a drawn bullet.\r\n * It is the honest reading, and it needs a new datum \u2014 the font of each\r\n * run \u2014 carried from `extractor/pdf-source.ts` through `ConservationRun`\r\n * to here, for two joins on one document. One line of shape beats it.\r\n *\r\n * THE ONE WRONG JOIN LEFT, safedocs 0000393: a page of search results, where a result's\r\n * snippet is joined to the next result's title (\u00AB \u2026920cc. 1982 and 1983 \u00BB \u2016\r\n * \u00AB virago xv535 1100 1981 1994 service manual \u2026 - Yamaha club \u00BB). Both\r\n * readings say \u00AB continuation \u00BB: the title is lower case and the PDF does\r\n * read it right after. Nothing separates it without reading the meaning.\r\n *\r\n * NOT IN THIS LOT. Two consecutive headings (S1): measured, it joins \u00AB \u2026GVS\r\n * 2015 \u00BB with \u00AB Executive Summary \u00BB (fixture 28).\r\n *\r\n * THE JOIN. `<p>A</p><p>B</p>` becomes `<p>A B</p>`: each part's inner XHTML\r\n * as it was, marks included, and one space. No word is added or removed.\r\n *\r\n * THE UNDO. The joined page is checked again. Its letters must be exactly the\r\n * same, in the same order, and it may lose no letter, glue no word, carry no\r\n * new word the PDF lacks, nor turn the verdict into an abstention; otherwise\r\n * the original page and its verdict are kept, whole.\r\n *\r\n * \u26A0\uFE0F CLIENT TEXT, in memory only, like the verdict it reads.\r\n */\r\n\r\nimport { collapseBlanks } from \"doc-ir/lib/blanks\";\r\nimport { markerOf } from \"doc-ir/layout/list\";\r\nimport {\r\n conservationKey,\r\n type ConservationVerdict,\r\n type PageEdit,\r\n type PublishedPage,\r\n type SourceWordLink,\r\n} from \"doc-ir/pipeline/text-conservation\";\r\n\r\n/** How many words each side of the cut must bring, read in a row by the PDF\r\n * (fewer when the paragraph has fewer). Simulated on 39 French and English\r\n * PDFs before this lot (diagnosis of 22/09/2026): 41 joins with 3, 48 with\r\n * 1. The stricter window is kept. */\r\nconst WINDOW = 3;\r\n\r\n/** A sentence closes on these (`tools/render-lint.ts`, S2). */\r\nconst TERMINAL = /[.:;!?\u00BB\"\u2026)]$/u;\r\n/** \u00AB suite de la phrase \u00BB yes, \u00AB iPhone \u00BB no. */\r\nconst startsLowercaseWord = (text: string): boolean => /^\\p{Ll}+(?![\\p{L}\\p{N}])/u.test(text);\r\n\r\n/** A paragraph opening on a token of ONE letter: a marker drawn with a symbol\r\n * font, not a word carried over (22/09/2026 \u2014 see the module note). */\r\nconst startsOnALoneLetter = (text: string): boolean => conservationKey(text.split(/\\s+/)[0] ?? \"\").length <= 1;\r\n\r\n/** The text of one UNIT, as this rule reads it: the texts of the blocks it holds, joined by a space \u2014 a line break\r\n * inside a paragraph ends a block, and the old rule turned that `<br>` into a space before collapsing blanks. */\r\nconst textOfUnit = (page: PublishedPage, blocks: readonly number[]): string =>\r\n collapseBlanks(blocks.map((b) => page.blocks[b] ?? \"\").join(\" \"));\r\n\r\n/** Whether the PDF reads `tail` then `head` as source words in a row, the two edge words at one size. */\r\nconst readInARow = (tail: readonly (SourceWordLink | null)[], head: readonly (SourceWordLink | null)[]): boolean => {\r\n const words = [...tail, ...head];\r\n if (tail.length === 0 || head.length === 0 || words.some((w) => w === null)) return false;\r\n const links = words as SourceWordLink[];\r\n for (let k = 1; k < links.length; k++) if (links[k]!.index !== links[k - 1]!.index + 1) return false;\r\n const last = links[tail.length - 1]!;\r\n const first = links[tail.length]!;\r\n return Math.abs(last.lastSize - first.firstSize) < 0.01;\r\n};\r\n\r\n/** Whether the re-checked page is no worse than the original in any way. Exported since 09/11/2026: the loop that\r\n * applies the joins and re-checks is the caller's \u2014 it writes the page \u2014 but the rule for keeping or undoing them is\r\n * this check's, and a caller that invented its own could keep a page that lost a letter. */\r\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict): boolean =>\r\n after.decision !== \"abstain\" &&\r\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\r\n after.lostLetters <= before.lostLetters &&\r\n after.gluedWords <= before.gluedWords &&\r\n after.unmatchedPageWords <= before.unmatchedPageWords;\r\n\r\n/**\r\n * THE JOINS THIS RULE PROVES, as edits for the caller to apply to its own page (09/11/2026). It writes nothing:\r\n * removing `</p><p>` from a storage XHTML is knowledge of ONE destination, and this check has none.\r\n *\r\n * Reasons it abstains, unchanged: no `units` from the caller (it cannot know what a unit is on its own), a verdict\r\n * that abstains (the tiling linking the words is not trusted), a unit the caller did not call `joinable`, or anything\r\n * of the page sitting between the two.\r\n */\r\nexport function cutParagraphEdits(\r\n page: PublishedPage,\r\n verdict: ConservationVerdict,\r\n): { edits: PageEdit[]; joined: number } {\r\n const units = page.units;\r\n if (units === undefined || verdict.decision === \"abstain\") return { edits: [], joined: 0 };\r\n\r\n // Each unit's page words, as links to the source: the words of every block the unit holds, in order.\r\n const links: (SourceWordLink | null)[][] = units.map((unit) =>\r\n unit.blocks.flatMap((b) => verdict.sourceOfPageWords[b] ?? []),\r\n );\r\n\r\n const cutAfter = (u: number): boolean => {\r\n const first = units[u]!;\r\n const second = units[u + 1]!;\r\n if (!first.joinable || !second.joinable || !first.adjacentToNext) return false;\r\n const ta = textOfUnit(page, first.blocks);\r\n const tb = textOfUnit(page, second.blocks);\r\n if (ta.length === 0 || TERMINAL.test(ta)) return false;\r\n if (!startsLowercaseWord(tb) || markerOf(tb) !== undefined || startsOnALoneLetter(tb)) return false;\r\n return readInARow(links[u]!.slice(-WINDOW), links[u + 1]!.slice(0, WINDOW));\r\n };\r\n\r\n // Right to left, so a join never shifts the unit still to look at.\r\n const edits: PageEdit[] = [];\r\n for (let u = units.length - 2; u >= 0; u--) if (cutAfter(u)) edits.push({ kind: \"join-units\", unit: u });\r\n return { edits, joined: edits.length };\r\n}\r\n", "/** Puts a passage the render lost back into the storage XHTML, as its own paragraph between the two adjacent top-level paragraphs that hold its source neighbours \u2014 and undoes the whole repair unless the re-check gains exactly the inserted letters.\r\n * NOT here: finding the lost words and their neighbours (`pipeline/text-conservation.ts`), glued words (`pipeline/glued-word-repair.ts`), nor what the document record keeps (`pipeline/publish-conservation.ts`).\r\n * Called by: `pipeline/publish-conservation.ts`, once per checked PDF render. */\r\n\r\n/**\r\n * THE RULE (21/09/2026, lot 5). A lost passage is a run of\r\n * consecutive source words neither reading found. Its neighbours are the\r\n * source words right before and right after it. It goes back ONLY when:\r\n * - each neighbour is a word the page matched (not an alt text, a list\r\n * number, a re-spacing: those have no single place in the page);\r\n * - the neighbour before is the LAST word of a top-level paragraph or\r\n * heading, the one after the FIRST word of the next top-level element,\r\n * with nothing between the two elements;\r\n * - at the start or the end of the document, the one neighbour opens the\r\n * page's first text block, or closes its last one.\r\n * Anything else abstains by name and the page stays \u00AB lost \u00BB, visible on the\r\n * dashboard: a loss inside a paragraph, a table cell, a list, an image\r\n * between the two paragraphs. A paragraph cut in the wrong place reads as if\r\n * nothing were wrong; a \u00AB N characters are not published \u00BB line does not.\r\n *\r\n * WHY THE XHTML AND NOT THE DOCUMENT MODEL (as lot 4). The check locates each\r\n * neighbour by block and word in the XHTML it read; the insertion goes at an\r\n * element boundary of that same XHTML, so no second mapping can disagree. The\r\n * inserted paragraph is the words as the PDF reads them, joined by single\r\n * spaces, escaped by the serializer's own `escapeText`.\r\n *\r\n * THE UNDO. The repaired page is checked again. Lost letters must drop by\r\n * EXACTLY the inserted letters, the page may carry no new word the PDF lacks\r\n * nor a new glued word, its letters must grow by exactly the inserted ones,\r\n * and it may never carry more letters than the PDF (the over-insertion the\r\n * design measurement saw once). Otherwise the original page and its verdict\r\n * are kept, whole. A consequence, chosen: a document whose page already\r\n * carries more letters than its checked source (OCR text of a scanned page\r\n * next to digital ones) is never repaired.\r\n *\r\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are\r\n * read in content-stream order. Measured on 871 paragraphs cut from the 45\r\n * fixture renders (21/09/2026): 426 put back with the page's letters exactly\r\n * as before, 22 put back elsewhere \u2014 where the stream reads them. Some of\r\n * those read better than the render did (a form label, 0000523), some worse\r\n * (a second column read line by line, fixture 11). Tried and NOT kept: also\r\n * requiring the blocks on each side to follow the source's order \u2014 it\r\n * caught 8 of the 22 and cost 17 exact repairs. Text back in the page is what\r\n * search needs; a paragraph slightly out of place is the lesser defect.\r\n *\r\n * \u26A0\uFE0F CLIENT TEXT, in memory only, like the verdict it reads.\r\n */\r\n\r\nimport {\r\n conservationKey,\r\n wordKeysOf,\r\n type LostPassage,\r\n type PageEdit,\r\n type PageWordAt,\r\n type PublishedPage,\r\n} from \"doc-ir/pipeline/text-conservation\";\r\n\r\n/** Why a lost passage was not put back \u2014 a closed list. */\r\nexport type LostTextAbstention =\r\n | \"no-anchor\"\r\n | \"anchor-unmatched\"\r\n | \"anchors-out-of-order\"\r\n | \"anchor-in-container\"\r\n | \"loss-inside-block\"\r\n | \"blocks-not-adjacent\";\r\n\r\n/** One passage placed: the edit the caller applies, and the letters it puts back (for the caller's accounting). */\r\nexport interface LostTextInsertion {\r\n edit: PageEdit;\r\n letters: number;\r\n}\r\n\r\n/** Where each lost passage goes, as an edit for the caller to apply \u2014 or why it does not go anywhere.\r\n *\r\n * It reasons on the page's UNITS (`PublishedPage.units`), never on markup (09/11/2026): a passage is put back between\r\n * two units only when the source word before it is the LAST word of its unit, the one after it the FIRST of the next,\r\n * both units are prose or a title, and nothing of the page sits between them. Anything less certain abstains by name,\r\n * and the name travels to the caller so a reader of the dashboard knows why nothing was repaired.\r\n *\r\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container` \u2014 the same\r\n * answer as a page whose anchors sit somewhere a paragraph may not go.\r\n */\r\nexport function placeLostPassages(\r\n page: PublishedPage,\r\n passages: readonly LostPassage[],\r\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\r\n const insertions: LostTextInsertion[] = [];\r\n const abstentions: LostTextAbstention[] = [];\r\n if (passages.length === 0) return { insertions, abstentions };\r\n const units = page.units;\r\n const words = page.blocks.map((text) => wordKeysOf(text).length);\r\n const lastBlock = words.length - 1;\r\n const unitOf = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\r\n\r\n /** The anchor's unit, or why it cannot anchor. */\r\n const edgeOf = (at: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\r\n const u = unitOf(at.block);\r\n if (u < 0 || units?.[u]?.paragraphOrHeading !== true) return \"anchor-in-container\";\r\n // The last word of the unit (before) or its first (after): the loss must sit at the unit's edge, not inside it.\r\n const neighbourBlock = side === \"before\" ? at.block + 1 : at.block - 1;\r\n const atEdge = side === \"before\" ? at.word === (words[at.block] ?? 0) - 1 : at.word === 0;\r\n if (!atEdge || unitOf(neighbourBlock) === u) return \"loss-inside-block\";\r\n return u;\r\n };\r\n\r\n /** The unit the passage goes AFTER (`-1`: before the first unit), or why it does not. */\r\n const place = (passage: LostPassage): number | LostTextAbstention => {\r\n const { before, after } = passage;\r\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\r\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\r\n if (before !== \"document-edge\" && after !== \"document-edge\") {\r\n if (after.block < before.block || (after.block === before.block && after.word <= before.word))\r\n return \"anchors-out-of-order\";\r\n }\r\n const u1 = before === \"document-edge\" ? undefined : edgeOf(before, \"before\");\r\n if (typeof u1 === \"string\") return u1;\r\n const u2 = after === \"document-edge\" ? undefined : edgeOf(after, \"after\");\r\n if (typeof u2 === \"string\") return u2;\r\n if (u1 === undefined) return after !== \"document-edge\" && after.block === 0 ? u2! - 1 : \"no-anchor\";\r\n if (u2 === undefined) return before !== \"document-edge\" && before.block === lastBlock ? u1 : \"no-anchor\";\r\n return u2 === u1 + 1 && units?.[u1]?.adjacentToNext === true ? u1 : \"blocks-not-adjacent\";\r\n };\r\n\r\n for (const passage of passages) {\r\n const at = place(passage);\r\n if (typeof at === \"string\") abstentions.push(at);\r\n else {\r\n insertions.push({\r\n edit: { kind: \"insert-unit-after\", unit: at, text: passage.sourceWords.join(\" \") },\r\n letters: passage.sourceWords.reduce((n, w) => n + conservationKey(w).length, 0),\r\n });\r\n }\r\n }\r\n return { insertions, abstentions };\r\n}\r\n", "/** The ONE failure the reading library throws: a code from a closed list, a message composed by us, and \u2014 for a PDF refusal \u2014 the\r\n * two page counts as structured fields, so no caller ever parses the message. A LEAF module: it imports nothing.\r\n * Decides: which codes a reading may end with (the nine below, nothing else), and that a failure of a FOREIGN service the reading\r\n * calls (the optional OCR) travels as `cause`, unread: the library does not interpret it, whoever called the reading may.\r\n * NOT here: what a code means to the product (retry, dead letter, wording: `core/errors.ts`), nor the conversion to the app's\r\n * `AppError` (`core/reader-bridge.ts`, which fails to compile if a code here is not an `ErrorCode` there).\r\n * Called by: every reader that refuses a file (`extractor/`, `pipeline/source-reading-package.ts`), and `core/reader-bridge.ts`. */\r\n\r\n/** The closed list, in one array so a test reads the same words the type is made of. */\r\nexport const READER_ERROR_CODES = [\r\n \"EXTRACT_FAILED\",\r\n \"FILE_UNSAFE\",\r\n \"UNSUPPORTED_TYPE\",\r\n \"DOCUMENT_PASSWORD_PROTECTED\",\r\n \"DOCUMENT_TOO_MANY_PAGES\",\r\n \"SCANNED_PDF_NEEDS_AI_OCR\",\r\n \"OCR_LOW_CONFIDENCE\",\r\n \"NO_PUBLISHABLE_SHEET\",\r\n \"UNKNOWN\",\r\n] as const;\r\n\r\nexport type ReaderErrorCode = (typeof READER_ERROR_CODES)[number];\r\n\r\n/** The numbers a PDF refusal carries: `scannedPageCount` is the pages to read (all of them for a scan); absent when the refusal came\r\n * before anything was read (the page-count cap). */\r\nexport interface ReaderCountDetail {\r\n pageCount?: number;\r\n scannedPageCount?: number;\r\n}\r\n\r\nexport class ReaderError extends Error {\r\n readonly pageCount?: number;\r\n readonly scannedPageCount?: number;\r\n\r\n /** `options.cause`: what a foreign service threw (the library's `UNKNOWN` \u00AB the AI reading failed \u00BB). Never part of the message. */\r\n constructor(\r\n public readonly code: ReaderErrorCode,\r\n message: string,\r\n detail?: ReaderCountDetail,\r\n options?: { cause?: unknown },\r\n ) {\r\n super(message, options);\r\n this.name = \"ReaderError\";\r\n if (detail?.pageCount !== undefined) this.pageCount = detail.pageCount;\r\n if (detail?.scannedPageCount !== undefined) this.scannedPageCount = detail.scannedPageCount;\r\n }\r\n}\r\n", "/** The size limits a reading enforces on ONE document, and the notice builders for the parts a cap leaves out\r\n * (`unpublishedPartNotices`, `workbookCapNotice`, `sheetUnreadableNotice`, `cutNoticeName`).\r\n *\r\n * \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\r\n * TWO FAMILIES, AND ONLY ONE OF THEM HAS A VALUE HERE (09/11/2026)\r\n * \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\r\n * A ceiling shaped by the DESTINATION \u2014 the pages of a PDF, the slide tabs and the elements of a slide, the sheet\r\n * tabs, the rows and columns of a sheet and of a table \u2014 is not the library's business: it is the size of one\r\n * Confluence page, a product decision of Miksumia Publisher. Those seven live in the APP\r\n * (`core/document-caps.ts#PRODUCT_READER_LIMITS`), which passes them as `limits` at the two call sites that read a\r\n * document. Here they default to `NO_CAP`: **a reading given no `limits` withholds nothing**, and a consumer of the\r\n * published library (`pdf-skryba`) sets its own, or none.\r\n * A bound that protects the READER keeps its value here, and is only lowerable: the byte ceiling of a payload, the\r\n * chart bounds, and \u2014 in their own files \u2014 the zip, XML and PDF decoding budgets. A reader that reads without bounds\r\n * is a bomb whatever its caller asked for, so those are never `NO_CAP`.\r\n *\r\n * Decides: `NO_CAP` and the reader's own bounds below, how a notice names what a cap kept out, and `ReaderLimits`,\r\n * the object a reading takes to set any cap (a field left out is `NO_CAP` for the seven, the bound below for the rest).\r\n * NOT here: the seven product ceilings and `exceedsDocumentPageCap` (`core/document-caps.ts`), the limit of documents\r\n * of a CONNECTION (`core/document-caps.ts#PAGE_COUNT_HARD_LIMIT`), the monthly scan quota (`core/ai-budget.ts`), the\r\n * comb threshold of a PDF strip of boxes (`extractor/pdf-table-render.ts#COMB_MIN_COLUMNS`, a geometry heuristic that\r\n * withholds nothing), nor what a refusal becomes (`orchestrator/doc-queue.ts`, `orchestrator/sync-plan.ts`).\r\n * Called by: `extractor/` (PDF, docx, pptx, xlsx and sheet readers), `pipeline/source-reading-{xlsx,pptx,gsheet,chart}.ts`,\r\n * `pipeline/structure-conservation.ts`, `lib/table-width-cap.ts`, `adapters/conservation-log.ts`,\r\n * `orchestrator/page-cap.ts` through its re-export, and `tools/bench/`. */\r\n\r\nimport type { DocumentNotice } from \"./reader-types\";\r\n\r\n/**\r\n * NO_CAP \u2014 what a reading uses when its caller set no ceiling for one of the seven DESTINATION caps (the pages of a\r\n * PDF, the slide tabs, the elements of a slide, the sheet tabs, the rows and columns of a sheet and of a table).\r\n * **Nothing is withheld.** The library reads what the file holds; deciding that a document is too big for the page it\r\n * is going to is the caller's decision, and `core/document-caps.ts#PRODUCT_READER_LIMITS` is Miksumia Publisher's.\r\n *\r\n * `Number.MAX_SAFE_INTEGER`, not `Infinity`, for the readers that consume these fields: every one only COMPARES\r\n * (`>`, `>=`), SLICES (`slice(0, n)`) or SUBTRACTS from a budget (`budget.left -= count`), none allocates in\r\n * proportion to a cap, and an integer stays an integer where a notice or a message would otherwise print\r\n * \u00AB Infinity \u00BB or carry `cap + 1` (reached only past the cap, so never). The same reasoning the app wrote for its own\r\n * lifted upload limits on 07/11/2026, now the library's default \u2014 which is why that object could be deleted.\r\n */\r\nexport const NO_CAP = Number.MAX_SAFE_INTEGER;\r\n\r\n/** The ONE byte ceiling of a payload read or inflated for a document (08/10/2026): a direct download\r\n * (`adapters/forge-drive.ts#BINARY_MAX_BYTES`), an export link (`EXPORT_LINK_MAX_BYTES`) and the images a docx, pptx or xlsx\r\n * inflates (`extractor/ooxml/package.ts#IMAGE_MAX_TOTAL_BYTES`) derive from it. NOT derived: Google's own 10 MB\r\n * HTML export limit and `SHEETS_META_MAX_BYTES`. */\r\nexport const MAX_PAYLOAD_BYTES = 50_000_000;\r\n\r\n/** How many sheet names a `workbook-cap` notice carries (`lib/reader-types.ts#DocumentNotice`):\r\n * the record stays small however many sheets a workbook has \u2014 the rest is\r\n * only counted (`more`). Starting value to calibrate (owner design, 30/09/2026). */\r\nexport const MAX_NOTICE_SHEET_NAMES = 5;\r\n\r\n/** How many LOST PICTURE PLACES a `pdf-image-unread` notice names (`lib/reader-types.ts#DocumentNotice`): the same\r\n * display bound as the sheet names, and for the same reason \u2014 a dialog line, not a log; the rest is only counted\r\n * (`more`). 03/11/2026: a count with nowhere to look is not a report. */\r\nexport const MAX_NOTICE_IMAGE_PLACES = MAX_NOTICE_SHEET_NAMES;\r\n\r\n/** How many PAGE RANGES a `pdf-text-unread` notice names (`lib/reader-types.ts#DocumentNotice`): the same display bound as\r\n * the lost picture places, and for the same reason; the pages left out are only counted (`more`). Starting value to\r\n * calibrate (16/11/2026). A PDF of 2 000 pages that all fail holds in one range. */\r\nexport const MAX_NOTICE_PAGE_RANGES = MAX_NOTICE_IMAGE_PLACES;\r\n\r\n/** A sheet name is client text: a notice keeps at most this many characters\r\n * of it (then \u00AB \u2026 \u00BB). The dev log's missing words are cut by the same `cutNoticeName`, at the same value as\r\n * `pipeline/declared-format-conservation.ts#MISSING_WORD_SHOWN_MAX_CHARS` (held equal by `core/reader-limits.test.ts`;\r\n * this file imports no other reader file). */\r\nexport const MAX_NOTICE_SHEET_NAME_CHARS = 64;\r\n\r\n/** Client text as a notice or the dev log carries it: bounded, never the whole string. */\r\nexport const cutNoticeName = (name: string): string =>\r\n name.length > MAX_NOTICE_SHEET_NAME_CHARS ? `${name.slice(0, MAX_NOTICE_SHEET_NAME_CHARS)}\u2026` : name;\r\n\r\n/** The folded notices of parts a reader kept out, one line per kind and only when counted: charts withheld whole (a bound,\r\n * a damaged part: `chart-withheld`), pictures whose part is damaged (`image-missing`), and hidden content dropped\r\n * (`hidden-dropped`, one per `what`; 08/10/2026). The same lines for every format (07/10/2026). */\r\nexport const unpublishedPartNotices = (counts: {\r\n chartsWithheld: number;\r\n imagesMissing: number;\r\n hiddenShapes?: number;\r\n filteredRows?: number;\r\n trackedDeletions?: number;\r\n tablesWithheld?: number;\r\n}): Extract<DocumentNotice, { kind: \"chart-withheld\" | \"image-missing\" | \"hidden-dropped\" | \"table-withheld\" }>[] => [\r\n ...(counts.chartsWithheld > 0 ? [{ kind: \"chart-withheld\" as const, count: counts.chartsWithheld }] : []),\r\n ...(counts.imagesMissing > 0 ? [{ kind: \"image-missing\" as const, count: counts.imagesMissing }] : []),\r\n ...(counts.tablesWithheld !== undefined && counts.tablesWithheld > 0\r\n ? [{ kind: \"table-withheld\" as const, count: counts.tablesWithheld }]\r\n : []),\r\n ...(\r\n [\r\n [\"shape\", counts.hiddenShapes],\r\n [\"filtered-rows\", counts.filteredRows],\r\n [\"tracked-deletion\", counts.trackedDeletions],\r\n ] as const\r\n ).flatMap(([what, count]) =>\r\n count !== undefined && count > 0 ? [{ kind: \"hidden-dropped\" as const, what, count }] : [],\r\n ),\r\n];\r\n\r\nconst boundedSheetNames = (names: readonly string[]): { sheets: string[]; more: number } => ({\r\n sheets: names.slice(0, MAX_NOTICE_SHEET_NAMES).map(cutNoticeName),\r\n more: Math.max(0, names.length - MAX_NOTICE_SHEET_NAMES),\r\n});\r\n\r\n/** The `workbook-cap` notice of the sheets left beyond the cap: at most\r\n * `MAX_NOTICE_SHEET_NAMES` cut names, the others counted in `more`. */\r\nexport const workbookCapNotice = (\r\n beyondCap: readonly string[],\r\n): { kind: \"workbook-cap\"; sheets: string[]; more: number } => ({\r\n kind: \"workbook-cap\",\r\n ...boundedSheetNames(beyondCap),\r\n});\r\n\r\n/** The `sheet-unreadable` notice of visible sheets whose part is absent: the same bounds as `workbook-cap`. */\r\nexport const sheetUnreadableNotice = (\r\n names: readonly string[],\r\n): { kind: \"sheet-unreadable\"; sheets: string[]; more: number } => ({\r\n kind: \"sheet-unreadable\",\r\n ...boundedSheetNames(names),\r\n});\r\n\r\n/** Starting value to calibrate: the most cells (rows \u00D7 columns) one chart\r\n * table may hold. A legitimate chart is hundreds of cells (10 000 rows of\r\n * 3 columns is 30 000); the product of the point and series bounds alone\r\n * allows hundreds of millions. Past it the chart is withheld whole. */\r\nexport const MAX_CHART_CELLS = 200_000;\r\n\r\n/** Starting value to calibrate: the most series (`c:ser`) one chart may\r\n * hold. Excel's own limit is 255 series per chart; the repo's fixtures hold\r\n * a handful. Checked BEFORE any series' array is built: 5 000 series of one\r\n * point each (620 KB of XML) used to cost 13 s and 435 MB. Past it the whole\r\n * chart is withheld (d\u00E9cision B). */\r\nexport const MAX_CHART_SERIES = 255;\r\n\r\n/** Starting value to calibrate: the largest chart-cache `idx` kept. The chart caches of the repo's fixtures count their points in the\r\n * hundreds; the bound guards against a declared `c:ptCount` of 2 000 000 000. A point at or past it withholds the chart whole. */\r\nexport const MAX_CHART_POINTS = 10_000;\r\n\r\n/** Starting value to calibrate: the most category levels (`c:multiLvlStrCache`) of one chart. Word-made charts group categories two or three\r\n * deep; a cache of 2 000 levels built 4 002 000 cells. A ninth level withholds the chart whole. */\r\nexport const MAX_CHART_LEVELS = 8;\r\n\r\n/** The limits a reading takes as a PARAMETER (docs/PLAN-BIBLIOTHEQUE.md \u00A75, step 5): one optional object handed to a reader.\r\n * **The seven destination caps are `NO_CAP` when left out** \u2014 a reading given no limits withholds nothing, and the caller\r\n * that wants the size of a Confluence page asks for it (`core/document-caps.ts#PRODUCT_READER_LIMITS`). The other fields\r\n * default to the reader's own bound, the constant above that each one mirrors, and can only be lowered usefully.\r\n * Read where the cap bites, always as `limits?.field ?? NO_CAP` or `?? BOUND`: never copied into a default object.\r\n * Two readings of one document (the extraction and its independent conservation source) must be given the SAME limits, or they\r\n * withhold different tables, sheets and slides and the check reports a loss that is only a difference of cap.\r\n * Not a field: the notice names (`MAX_NOTICE_SHEET_NAME*`, how a notice is written, not what a reading withholds) and the\r\n * layout threshold past which a PDF strip of boxes is a comb written as spaced letters\r\n * (`extractor/pdf-table-render.ts#COMB_MIN_COLUMNS`: not a cap, no content is withheld by it). */\r\nexport interface ReaderLimits {\r\n /** PDF only: more pages than this and the document is refused. `NO_CAP` by default. */\r\n readonly pageLimit?: number;\r\n /** The byte ceiling of the pictures a document inflates (`MAX_PAYLOAD_BYTES`, a reader bound). */\r\n readonly payloadBytes?: number;\r\n /** Elements one slide, drawing or SmartArt may hold. `NO_CAP` by default. */\r\n readonly slideElements?: number;\r\n /** Slide tabs a presentation page shows. `NO_CAP` by default. */\r\n readonly presentationTabs?: number;\r\n /** Sheet tabs a workbook page shows. `NO_CAP` by default. */\r\n readonly workbookTabs?: number;\r\n /** Rows of a worksheet tab. `NO_CAP` by default. */\r\n readonly sheetRows?: number;\r\n /** Columns of a worksheet tab. `NO_CAP` by default. */\r\n readonly sheetCols?: number;\r\n /** Rows of a table of any format. `NO_CAP` by default. */\r\n readonly tableRows?: number;\r\n /** Columns of a table of any format. `NO_CAP` by default. */\r\n readonly tableCols?: number;\r\n /** Cells of one chart table (`MAX_CHART_CELLS`). */\r\n readonly chartCells?: number;\r\n /** Series of one chart (`MAX_CHART_SERIES`). */\r\n readonly chartSeries?: number;\r\n /** The largest chart-cache index kept (`MAX_CHART_POINTS`). */\r\n readonly chartPoints?: number;\r\n /** Category levels of one chart (`MAX_CHART_LEVELS`). */\r\n readonly chartLevels?: number;\r\n}\r\n"],
5
- "mappings": ";AAsIO,IAAM,YAAY,CAAC,YACxB,QAAQ,aACL,QAAQ,CAAC,MAAM,EAAE,WAAW,EAC5B,IAAI,eAAe,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAkBxB,IAAM,kBAAkB,CAAC,UAC9B,MACG,UAAU,MAAM,EAChB,YAAY,EACZ,QAAQ,mBAAmB,EAAE;AAI3B,IAAM,aAAa,CAAC,SACzB,KACG,MAAM,KAAK,EACX,IAAI,eAAe,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAE/B,IAAM,aAAa;AACnB,IAAM,cAAc;AAwBpB,IAAM,WAAW,CAAC,SAAwE;AACxF,MAAI,OAAO;AACX,QAAM,QAAkB,CAAC;AACzB,QAAM,WAAW,MAAY;AAC3B,YAAQ;AACR,UAAM,KAAK,EAAE;AAAA,EACf;AACA,OAAK,QAAQ,CAAC,KAAK,MAAM;AACvB,YAAQ,IAAI;AACZ,aAAS,IAAI,GAAG,IAAI,IAAI,KAAK,QAAQ,IAAK,OAAM,K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AAI,QAAQ,cAAc,OAAW,MAAK,YAAY,OAAO;AAC7D,QAAI,QAAQ,qBAAqB,OAAW,MAAK,mBAAmB,OAAO;AAAA,EAC7E;AAAA,EATkB;AAAA,EALT;AAAA,EACA;AAcX;;;ACNO,IAAM,SAAS,OAAO;AAMtB,IAAM,oBAAoB;",
6
- "names": ["k", "u", "noWorse"]
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 PDF PACKAGE (`pdf-skryba/light`): the conservation check of a PDF and the shapes it speaks\n * in, with no reader behind them \u2014 importing this loads no PDF, no zip, no XML.\n *\n * WHY IT IS NOT THE APP'S LIGHT DOOR (`src/readers/light.ts`). The app publishes every format: its door carries the\n * DECLARED-format comparison (`missingWordGroups`, `DeclaredFormatConservationSource`), the Office MIME constants and\n * the diagram helpers. A PDF package has no use for any of it, and measured on 09/11/2026 it cost the package eight\n * type declarations of the docx/xlsx/zip families and three Office MIME strings \u2014 carried for nothing.\n *\n * WHAT A PDF CONSUMER CHECKS WITH. It hands the text it published, block by block (`PublishedPage`), and gets back\n * what was lost, invented, glued or split \u2014 in the coordinates of its own blocks, never its markup. The three repairs\n * come back as `PageEdit`s it applies itself: the library proves WHAT and WHERE, writing the page is the caller's.\n * NOT here: the readers (`lib/pdf.ts`, published as the package's main entry), the declared formats' own check, nor\n * anything that reads a rendered page \u2014 that knowledge belongs to whoever owns the markup.\n * Called by: nobody in this repository \u2014 it is a PUBLISHED door, so its callers are third parties that install\n * the package, and `tools/build-library.ts`, which builds it and holds what it may reach.\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", "/** Re-splits a glued page word where the PDF's own reading proves the boundaries, by adding spaces to the storage XHTML's text nodes \u2014 and undoes the whole repair if the re-check comes out worse in any way.\n * NOT here: finding the glued words (`pipeline/text-conservation.ts`), what the document record keeps (`pipeline/publish-conservation.ts`), nor joining a word published split \u2014 this lot repairs glued words only.\n * Called by: `pipeline/publish-conservation.ts`, once per checked PDF render. */\n\n/**\n * THE RULE (21/09/2026, lot 4). A page token is re-split ONLY when\n * its letters, as the check normalises them, are EXACTLY the concatenation of\n * the 2+ consecutive source words the word reading proved; a space goes at\n * each boundary the source gives, and nothing else changes. Anything less\n * certain is left alone and stays counted as glued, visible on the dashboard.\n *\n * WHY THE XHTML AND NOT THE DOCUMENT MODEL. The finding locates a word by\n * block and word index in the storage XHTML the check read; the same reader\n * hands back the text nodes those indices came from, so the edit lands on the\n * exact characters, with no second mapping to get wrong. A space added inside\n * a text node leaves every tag where it was: bold runs, links and images keep\n * their markup, and an image is never inside a word (it ends the\n * block for the reader). A boundary at a formatting edge gets its space at\n * the end of the first word's text node, inside that run.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the\n * first of the next, the page may carry non-letters (\u00AB IV.1.1)Vrsta \u00BB). They\n * are split as the source words carry them \u2014 the first word's trailing\n * characters, then the next word's leading ones; if the page's characters\n * there are not exactly those, the token is left alone rather than guessed.\n *\n * THE UNDO. The repaired page is checked again. It must lose no letter, keep\n * every page letter in the same order, create no word the PDF lacks, and\n * leave at most the glued words it did not repair; otherwise the original\n * page and its verdict are kept, whole \u2014 never a partial repair.\n *\n * \u26A0\uFE0F CLIENT TEXT, 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 character of a published block: its text, its letters, and where it ends IN THAT BLOCK'S TEXT.\n * Until 09/11/2026 `end` was an offset in the storage XHTML and a unit could be an entity (`&amp;`): the decision\n * then only worked on one markup. It is now an index in the text the caller published, which every destination has. */\ninterface Unit {\n text: string;\n key: string;\n end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole one), so `end` is a UTF-16 index usable for `slice`. */\nconst UNIT = /[\\s\\S]/gu;\n\n/** The units of one published block. */\nconst unitsOf = (text: string): Unit[] =>\n [...text.matchAll(UNIT)].map((m) => ({ text: m[0], key: conservationKey(m[0]), end: m.index + m[0].length }));\n\n/** The block's words, as the check splits them: runs of non-space units with at least one letter.\n * Same split as `text-conservation.ts#wordKeysOf`, kept by unit to locate offsets. */\nconst wordsOf = (units: readonly Unit[]): Unit[][] => {\n const words: Unit[][] = [];\n let current: Unit[] = [];\n const close = (): void => {\n if (conservationKey(current.map((u) => u.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const u of units) {\n if (/^\\s+$/u.test(u.text)) close();\n else current.push(u);\n }\n close();\n return words;\n};\n\n/** Leading or trailing characters of a source word that carry no letter. */\nconst edge = (raw: string, side: \"lead\" | \"trail\"): string => {\n const chars = [...raw];\n const order = side === \"lead\" ? chars : [...chars].reverse();\n const out: string[] = [];\n for (const c of order) {\n if (conservationKey(c).length > 0) break;\n out.push(c);\n }\n return (side === \"lead\" ? out : [...out].reverse()).join(\"\");\n};\n\n/** The renderer's zero-width space before a superscript glued to a word (`renderer/storage.ts#renderInlines`, PLATFORM-STATUS \u00A781)\n * carries nothing the source says: it is passed over between the words, and the space goes before it. */\nconst visible = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst insertionsFor = (blocks: readonly string[], r: Respacing): number[] | undefined => {\n const at = r.pageWords[0];\n if (r.kind !== \"glued\" || r.pageWords.length !== 1 || at === undefined || r.sourceWords.length < 2) return undefined;\n const text = blocks[at.block];\n const units = text === undefined ? undefined : unitsOf(text);\n const word = units === undefined ? undefined : wordsOf(units)[at.word];\n if (word === undefined) return undefined;\n const keys = r.sourceWords.map(conservationKey);\n const tokenKey = conservationKey(word.map((u) => u.text).join(\"\"));\n // Unit by unit, the letters must add up to the token's own (NFKC can join\n // across characters), and the token must be exactly the source words.\n if (word.map((u) => u.key).join(\"\") !== tokenKey || keys.join(\"\") !== tokenKey) return undefined;\n\n const offsets: number[] = [];\n let u = 0;\n let letters = 0;\n for (let i = 0; i < keys.length - 1; i++) {\n const boundary = letters + keys[i]!.length;\n // The unit carrying the first word's last letter must end exactly there.\n while (u < word.length && letters + word[u]!.key.length <= boundary && letters < boundary)\n letters += word[u++]!.key.length;\n if (letters !== boundary) return undefined;\n // Non-letters up to the next word's first letter, split as the source says.\n let next = u;\n while (next < word.length && word[next]!.key.length === 0) next++;\n const between = word.slice(u, next);\n const trail = edge(r.sourceWords[i]!, \"trail\");\n if (visible(between.map((x) => x.text).join(\"\")) !== trail + edge(r.sourceWords[i + 1]!, \"lead\")) return undefined;\n let taken = \"\";\n let k = 0;\n while (taken.length < trail.length && k < between.length) taken += visible(between[k++]!.text);\n if (taken !== trail) return undefined;\n offsets.push(word[u + k - 1]!.end);\n u += k;\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. Writes nothing: composing a page is the caller's job (`PageEdit`). */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((r) => r.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const taken = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const r of glued) {\n const block = r.pageWords[0]?.block;\n const at = insertionsFor(page.blocks, r);\n if (at === undefined || block === undefined || at.some((o) => taken.has(`${block}:${o}`))) continue;\n for (const atChar of at) {\n taken.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** Whether the re-checked page is no worse than the original in any way. Exported since 09/11/2026: the loop that\n * applies the edits and re-checks belongs to the caller (it writes the page), but the RULE for keeping or undoing a\n * repair is this check's and stays here \u2014 a caller that invented its own could keep a page that lost a letter. */\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 after.respacings.filter((r) => r.kind === \"split\").length <=\n before.respacings.filter((r) => r.kind === \"split\").length;\n", "/** Joins two adjacent top-level paragraphs of the storage XHTML into one when the render cut a sentence between them \u2014 the shape says so and the PDF reads their edge words in a row, at one size \u2014 and undoes the whole join if the re-check comes out worse in any way.\n * NOT here: where a line break is decided (`extractor/pdf-line-breaks.ts`), the word reading that links page words to source words (`pipeline/text-conservation.ts`), the other repairs (`pipeline/lost-text-repair.ts`, `pipeline/glued-word-repair.ts`), headings cut in two, nor the paragraphs of a table cell or of a list item (measured, then refused \u2014 see the module note).\n * Called by: `pipeline/publish-conservation.ts`, once per checked PDF render, after the other two repairs. */\n\n/**\n * THE RULE (22/09/2026, lot 35 \u2014 remedy B of the mid-sentence cuts\n * diagnosis). Two `<p>` children of the SAME element, with nothing between\n * them, become one ONLY when two independent readings agree:\n * - THE SHAPE, in our render: the first does not end with `. : ; ! ? \u00BB \" \u2026 )`\n * and the second starts with a word all in lower case (signature S2 of\n * `tools/render-lint.ts`, rewritten here because `src/` never imports\n * `tools/`). A second paragraph that opens on a list marker (\u00AB a. \u00BB,\n * \u00AB iv) \u00BB, \u00AB \u2013 \u00BB, `layout/list.ts#markerOf`) or on a token of ONE letter is\n * never a continuation.\n * - THE SOURCE: the last three words of the first and the first three of\n * the second are six source words in a row in the PDF's reading, furniture\n * left out, and the two edge words are set at the same size. The link from\n * page word to source word is the check's own tiling, so nothing is read\n * twice.\n * Anything else stays as it is. A paragraph cut in two is still all there\n * and searchable; two paragraphs joined by mistake are a sentence that never\n * existed.\n *\n * WHERE IT WORKS: the page's own `<p>` only.\n *\n * \u26A0\uFE0F MEASURED IN A CELL, THEN REFUSED (condition, 22/09/2026: not\n * one wrong join in a cell). Joining the `<p>` of ONE cell \u2014 a cell's lines\n * are each a paragraph (`extractor/pdf-table-render.ts`) \u2014 gives 65 joins on\n * the 39 French and English PDFs, 64 of them right, including the two cuts\n * of safedocs 0000754 p2 (defect E) and 49 lines of fixture 26 rejoined.\n * THE ONE WRONG, fixture 26 p13, cell of \u00AB Moyens de Communication Interne \u00BB:\n * \u00AB Le chat via Google drive \u00BB \u2016 \u00AB ordinateur portable pour chaque\n * collaborateur. \u00BB are TWO bullets of a list (checked against the page\n * image); the bullet character is DRAWN, absent from the text layer, so the\n * second item opens on a lowercase word the PDF reads right after the first.\n * A cell packs items without markers far more often than prose does \u2014 that\n * is what the measurement shows, and why the same rule is not safe there.\n * The two `<p>` of one list item, and two cells side by side, are refused for\n * the same reason (0000713 p5: two items of one cell must stay two).\n *\n * MEASURED on the 39 French and English PDFs, publish path, 22/09/2026: 18\n * joins in 7 documents (16 groups, two of them three paragraphs), 61 \u2192 43\n * pairs of the S2 shape at the top level, every verdict unchanged, no letter\n * lost and none added. Each join was read: 17 right, 1 wrong (below).\n *\n * \u26A0\uFE0F WHY A TOKEN OF ONE LETTER STOPS THE JOIN. Two joins of a first\n * measurement were wrong, both on fixture 25: the bullet of a three-line spec\n * list is drawn \u00AB x \u00BB in the text layer, so it reads as a lowercase word, and\n * the PDF does read it right after the line before. `markerOf` does not catch\n * it \u2014 nothing in the extraction reads a symbol font's glyph as a bullet.\n * DECIDED (22/09/2026): a paragraph opening on a token of ONE\n * letter is never a continuation. It costs none of the 17 right joins.\n * - THE LIMIT IT BRINGS, written and accepted: a real continuation opening\n * on \u00AB il \u00BB, \u00AB y \u00BB, \u00AB \u00E0 \u00BB, \u00AB a \u00BB is refused too \u2014 \u00AB \u2026tout ce qu'il \u2016 y a\n * de plus simple \u00BB. No such case in the 39 French and English PDFs.\n * - TRIED AND SET ASIDE: reading the glyph's FONT to know a drawn bullet.\n * It is the honest reading, and it needs a new datum \u2014 the font of each\n * run \u2014 carried from `extractor/pdf-source.ts` through `ConservationRun`\n * to here, for two joins on one document. One line of shape beats it.\n *\n * THE ONE WRONG JOIN LEFT, safedocs 0000393: a page of search results, where a result's\n * snippet is joined to the next result's title (\u00AB \u2026920cc. 1982 and 1983 \u00BB \u2016\n * \u00AB virago xv535 1100 1981 1994 service manual \u2026 - Yamaha club \u00BB). Both\n * readings say \u00AB continuation \u00BB: the title is lower case and the PDF does\n * read it right after. Nothing separates it without reading the meaning.\n *\n * NOT IN THIS LOT. Two consecutive headings (S1): measured, it joins \u00AB \u2026GVS\n * 2015 \u00BB with \u00AB Executive Summary \u00BB (fixture 28).\n *\n * THE JOIN. `<p>A</p><p>B</p>` becomes `<p>A B</p>`: each part's inner XHTML\n * as it was, marks included, and one space. No word is added or removed.\n *\n * THE UNDO. The joined page is checked again. Its letters must be exactly the\n * same, in the same order, and it may lose no letter, glue no word, carry no\n * new word the PDF lacks, nor turn the verdict into an abstention; otherwise\n * the original page and its verdict are kept, whole.\n *\n * \u26A0\uFE0F CLIENT TEXT, 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\n * (fewer when the paragraph has fewer). Simulated on 39 French and English\n * PDFs before this lot (diagnosis of 22/09/2026): 41 joins with 3, 48 with\n * 1. The stricter window is kept. */\nconst WINDOW = 3;\n\n/** A sentence closes on these (`tools/render-lint.ts`, S2). */\nconst TERMINAL = /[.:;!?\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 paragraph opening on a token of ONE letter: a marker drawn with a symbol\n * font, not a word carried over (22/09/2026 \u2014 see the module note). */\nconst startsOnALoneLetter = (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 the blocks it holds, joined by a space \u2014 a line break\n * inside a paragraph ends a block, and the old rule turned that `<br>` into a space before collapsing blanks. */\nconst textOfUnit = (page: PublishedPage, blocks: readonly number[]): string =>\n collapseBlanks(blocks.map((b) => page.blocks[b] ?? \"\").join(\" \"));\n\n/** Whether the PDF reads `tail` then `head` as source words in a row, the two edge words at one size. */\nconst readInARow = (tail: readonly (SourceWordLink | null)[], head: readonly (SourceWordLink | null)[]): boolean => {\n const words = [...tail, ...head];\n if (tail.length === 0 || head.length === 0 || words.some((w) => w === null)) return false;\n const links = words as SourceWordLink[];\n for (let k = 1; k < links.length; k++) if (links[k]!.index !== links[k - 1]!.index + 1) return false;\n const last = links[tail.length - 1]!;\n const first = links[tail.length]!;\n return Math.abs(last.lastSize - first.firstSize) < 0.01;\n};\n\n/** Whether the re-checked page is no worse than the original in any way. Exported since 09/11/2026: the loop that\n * applies the joins and re-checks is the caller's \u2014 it writes the page \u2014 but the rule for keeping or undoing them is\n * this check's, and a caller that invented its own could keep a page that 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 (09/11/2026). It writes nothing:\n * removing `</p><p>` from a storage XHTML is knowledge of ONE destination, and this check has none.\n *\n * Reasons it abstains, unchanged: no `units` from the caller (it cannot know what a unit is on its own), a verdict\n * that abstains (the tiling linking the words is not trusted), a unit the caller did not call `joinable`, or anything\n * of the page sitting between the two.\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 // Each unit's page words, as links to the source: the words of every block the unit holds, in order.\n const links: (SourceWordLink | null)[][] = units.map((unit) =>\n unit.blocks.flatMap((b) => verdict.sourceOfPageWords[b] ?? []),\n );\n\n const cutAfter = (u: number): boolean => {\n const first = units[u]!;\n const second = units[u + 1]!;\n if (!first.joinable || !second.joinable || !first.adjacentToNext) return false;\n const ta = textOfUnit(page, first.blocks);\n const tb = textOfUnit(page, second.blocks);\n if (ta.length === 0 || TERMINAL.test(ta)) return false;\n if (!startsLowercaseWord(tb) || markerOf(tb) !== undefined || startsOnALoneLetter(tb)) return false;\n return readInARow(links[u]!.slice(-WINDOW), links[u + 1]!.slice(0, WINDOW));\n };\n\n // Right to left, so a join never shifts the unit still to look at.\n const edits: PageEdit[] = [];\n for (let u = units.length - 2; u >= 0; u--) if (cutAfter(u)) edits.push({ kind: \"join-units\", unit: u });\n return { edits, joined: edits.length };\n}\n", "/** The lists a PDF never declares, found in the markers and the hanging indent\n * of its lines.\n * NOT here: how a list becomes IR blocks, nor paragraph grouping \u2014 both in\n * `extractor/pdf-paragraphs.ts`.\n * Called by: `extractor/pdf-paragraphs.ts`, `extractor/pdf-line-breaks.ts`. */\nimport { maxOf } from \"../lib/extent\";\nimport { SAME_LINE_PT } from \"./tolerances\";\n\n/**\n * list \u2014 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 * \uD83D\uDD34 **BULLETS: A LIST ONLY IN THE SIMPLE CASE (14/10/2026).**\n *\n * History. On 23/09/2026 no bulleted list was published at all: a run of bullets\n * or dashes stayed paragraphs, **the marker kept in the text** (nothing removed,\n * nothing lost). Why: a bullet is what our documents read worst (a symbol-font\n * letter, a dash glued to its word, a vector disc, a wrapped line taken for an\n * item), and the list tag is what let us REMOVE the marker, so a misread marker\n * made a false list. That rule still holds for `listRuns` (indented runs of\n * dashes, mixed runs, anything outside the simple case).\n *\n * Revision. A run is published as a bulleted list again, but only through\n * `bulletRuns` (see there for the conditions). Measured on 51 French and English\n * PDFs: 84 lists, 318 items, 0 invented list. Numbered and lettered lists are\n * unchanged.\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 * \u26A0\uFE0F And when the character IS there, it can be a LIE \u2014 see the written limits\n * below: a symbol font writes its bullet as \u00AB x \u00BB or as a private codepoint,\n * and only the font would tell. We do not read the font.\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 * `layout/list.markers.test.ts` \u2014 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 (\n * 22/09/2026). Word 2007 glues its dash to its word \u2014 \u00AB -Ensures Safety of the\n * patient \u00BB \u2014 so fixture 28 page 2 publishes 7 items as 7 paragraphs.\n *\n * Accepting a glued dash was built and measured, then dropped. The two\n * populations, over the 39 French and English PDFs \u2014 22 lines open on a dash\n * with NO blank after it, in 3 documents:\n * \u00B7 7 REAL items, fixture 28 p2, where the dash IS the bullet (read on the\n * page image);\n * \u00B7 15 that are not, and the two conditions already hold every one of them\n * out of any list on their own: 0000312 p1 \u00AB \u2013positive advanced\n * nonsquamous\u2026 \u00BB (two wrapped lines continuing \u00AB ALK\u2013positive \u00BB, not\n * indented, 45.4 pt is the body's own margin), 27 p2 \u00AB -30- \u00BB (the end mark\n * of a press release, not indented), and the timeline of 28 p3-p4\n * (\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 \u2014 and it was still dropped. On\n * 28 p2 the text ALREADY comes out one item per line: the `<ul>` was a comfort,\n * 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. Reopen it the\n * day a document really loses something 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 (22/09/2026). The Jev re-read\n * (`docs/ESSAI-JEV-ETIQUETAGE.md` [purged 27/09/2026, git history], French and English documents) found 35\n * items published as plain paragraphs, in 8 documents, in three shapes: marked\n * items that are NOT indented (20), several items fused into one block (8), and\n * 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\n * the indent. Measured over 34 French/English PDFs: 7 runs, 17 items, no false\n * list \u2014 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. Reopen\n * only if a real document loses something because of a missed list.\n *\n * THREE MORE FAMILIES OF BULLET, MEASURED ON 22/09/2026 AND LEFT ALONE\n * (the text already\n * comes out line by line in all three, so the drawn bullet is a comfort, and a\n * marker we do not read is a marker we cannot remove 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\n * different ways, because a symbol font's glyphs have no character\n * identity and what pdf.js wrote for them (measured before its removal) was an accident of the font's\n * cmap (a symbolic TrueType (3,0) cmap maps to 0xF000+code):\n * SymbolMT 0xB7 \u2192 \u00AB \u2022 \u00BB U+2022, 68 runs, 6 documents \u2014 read today\n * Wingdings 0xFC \u2192 U+F0FC, 17 runs, safedocs 0000609 \u2014 a private\n * codepoint, published as a tofu box\n * SymbolMT 0x78 \u2192 \u00AB x \u00BB U+0078, 24 runs, fixture 25 \u2014 a LETTER\n * The character cannot be the test, so the FONT would have to be: measured\n * over the 39 French and English PDFs, every run painted in a font named\n * for a symbol family is 116 runs, 9 fonts, 8 documents, ALL of ONE\n * character and ALL bullets \u2014 0 run of prose, 0 run longer than one\n * character. The discriminant is clean; its price is not. It needs the\n * boundary to resolve the font name (`pdf-source.ts`), a new field on every\n * text run, and a new field on every line. Built and measured that way, it\n * gave ONE list \u2014 safedocs 0000609 p5, 6 items \u2014 whose 6 lines already come\n * out one per line today. Reopen it only if a document loses text for it.\n * Also tried: the private-use range U+E000\u2013U+F8FF as the test, which\n * PyMuPDF4LLM does with U+F0B7 and U+F0A7 hard-coded. No new reading, 17\n * lines on the corpus, all bullets, 0 false \u2014 but it catches only the\n * Wingdings shape, not the \u00AB x \u00BB, and it publishes a `<ul>` in place of\n * lines that are already right.\n *\n * 2. **A DISC DRAWN IN VECTOR, not written.** Fixture 26 (Canva) marks 37 lines\n * with a filled circle of 3.7 to 3.8 pt; all 37 sit 8.2 to 8.4 pt to the\n * left of their line, on its baseline band (dy 2.1 to 2.6 pt) \u2014 geometry\n * clean enough to attach. What stops it is elsewhere and it is bigger: every\n * page of that document publishes as ONE TABLE, and a table cell's blocks\n * are built without `paragraphsFromLines` (`pdf-table-render.ts`), so no\n * list is ever looked for inside a cell. The marker would change nothing.\n * And the size is no discriminant on its own: fixture 25 draws a watch with\n * 484 small paths of 26 different sizes, 1.2 to 6.3 pt, 15 of which sit just\n * left of a line.\n * 3. **A WRAPPED LINE TAKEN FOR AN ITEM.** Safedocs 0000602 p2 publishes\n * \u00AB April 6, 2020 \u00BB 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\n * of them marked \u00BB rule lets in. Counted over every item the 39 French and\n * English PDFs publish \u2014 78 of them \u2014 it is the ONLY one. One case is not a\n * family, and no 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\n * marker for the list rule, but it never leaves the text (22/09/2026).\n * The IR list has no marker type, so the only ordered rendering is `<ol>`\n * counting 1, 2, 3: stripping \u00AB a. \u00BB replaced every letter with a number, and\n * the letters were lost \u2014 16 on safedocs 0000609 p7. A run of letters is\n * therefore a BULLET list whose items keep \u00AB a. \u00BB in their text: the simplest\n * form that loses nothing and still says \"these are items\". Set aside: no list\n * at all (the items would then read as loose paragraphs), and a marker type in\n * the IR (a 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 \u2014 removed from the\n * rendering only when the list's own marker replaces it (see\n * `pdf-paragraphs.ts#groupLists`). */\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 * \u26A0\uFE0F IT READS THE TEXT AND NOTHING ELSE. A marker the text cannot name is a\n * written limit here, not a parameter \u2014 see below.\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 m = pattern.exec(text);\n if (m !== null) return { kind, length: m[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 (22/09/2026): requiring the run's MARKED blocks to share\n * one quantised indent \u2014 signal 3 of the literature is \u00AB bullet partner\n * detection AT THE SAME LEVEL \u00BB and we only kept the partner. Written while the\n * symbol-font marker above was being measured, to hold back the one false list\n * it produced on fixture 25 (eight booklet pages imposed on one sheet, columns\n * not cut, markers then at 138, 144, 312 and 318 pt). With the markers we\n * actually read, the level changes NOTHING over the 39 French and English PDFs.\n * A guard that guards nothing is mechanism, so it is not here \u2014 reopen it with\n * 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 close = (end: number): void => {\n if (start === undefined) return;\n const slice = candidates.slice(start, end + 1);\n const marked = slice.filter((c) => c.marker !== undefined);\n const ofKind = (kind: MarkerKind): number => marked.filter((c) => c.marker?.kind === kind).length;\n // A run of bullets or dashes is no list here (23/09/2026, see the header; the\n // simple bulleted case goes through `bulletRuns`). The majority decides, as for\n // `ordered`, and a tie falls on the side of ABSTENTION.\n const bulleted = ofKind(\"bullet\") * 2 >= marked.length;\n if (slice.length >= MIN_ITEMS && marked.length * 2 >= slice.length && !bulleted) {\n const ordered = ofKind(\"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 close(index - 1);\n }\n close(candidates.length - 1);\n return runs;\n}\n\n/**\n * THE SIMPLE BULLETED RUN (14/10/2026). A run of consecutive paragraph\n * 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, fixture 33 p5: \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\n * the last item, no further below than the list's own line spacing, is that\n * item's continuation (docx-reel/10 p38: the last item is cut in two blocks) and\n * is returned as `tail`. The list's line spacing is the largest line pitch inside\n * its own wrapped items; with none to measure it from, the whole list is REJECTED\n * (bias: abstain). Beyond that spacing the block is a paragraph of its own and the\n * list stays.\n *\n * BULLET_RUN_MAX_DRIFT_PT = 1 pt, starting value to calibrate (the coordinate\n * noise of `SAME_LINE_PT`). Measured over 51 French and English PDFs: 84 runs\n * (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\n * at 86.2 against 89.5 pt (1) and on a bullet glued to its text (1); two of them\n * 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 first = lines[0];\n if (first === undefined) return {};\n const last = lines[lines.length - 1]!;\n const pitches = lines.slice(1).map((line, k) => lines[k]!.y - line.y);\n const geometry: BlockGeometry = {\n firstLeft: first.left,\n firstY: first.y,\n lastY: last.y,\n ...(pitches.length > 0 ? { pitch: maxOf(pitches, (p) => p) } : {}),\n };\n const opener = first.lead?.text.trim();\n if (\n first.lead === undefined ||\n opener === undefined ||\n !BULLET_LEAD_CHARS.has(opener) ||\n !first.text.trimStart().startsWith(opener)\n )\n return { geometry };\n const afterOpener = lines\n .map((line) => line.text)\n .join(\" \")\n .trimStart()\n .slice(opener.length);\n return {\n geometry,\n bullet: {\n markerLeft: first.left,\n textLeft: first.lead.nextLeft,\n continuationLefts: lines.slice(1).map((line) => line.left),\n secondBullet: ANY_BULLET_LEAD.test(afterOpener),\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 near = (a: number, b: number): boolean => Math.abs(a - b) <= BULLET_RUN_MAX_DRIFT_PT;\n\n/** The simple bulleted runs among consecutive blocks \u2014 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\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((c) => c.bullet!);\n const { markerLeft, textLeft } = items[0]!;\n const simple =\n textLeft - markerLeft > BULLET_RUN_MAX_DRIFT_PT &&\n items.every(\n (item) =>\n near(item.markerLeft, markerLeft) &&\n near(item.textLeft, textLeft) &&\n !item.secondBullet &&\n item.continuationLefts.every((left) => near(left, textLeft)),\n );\n if (!simple) return undefined;\n\n const next = candidates[end + 1];\n if (\n next?.geometry === undefined ||\n next.marker !== undefined ||\n next.bullet !== undefined ||\n !near(next.geometry.firstLeft, textLeft)\n )\n return { start, end };\n const pitches = candidates.slice(start, end + 1).flatMap((c) => c.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((c, k) => {\n const below = candidates[start + k + 1]!.geometry;\n const own = c.geometry;\n return own === undefined || below === undefined ? [] : [own.lastY - below.firstY].filter((d) => d > 0);\n });\n const spacing =\n pitches.length > 0 ? maxOf(pitches, (p) => p) : itemPitches.length > 0 ? maxOf(itemPitches, (p) => p) : undefined;\n if (spacing === undefined) return undefined;\n const gap = candidates[end]!.geometry!.lastY - next.geometry.firstY;\n // The tail lies BELOW the last item: a block read after a jump up the page (another column) is never one (review of 14/10/2026).\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.\n * Starting value to calibrate: 1 pt, the coordinate-noise tolerance of\n * `hangsFromMarker`. Measured on the French and English PDFs (22/09/2026):\n * - aligned: an item's text start read twice (after its marker, on its second\n * line) agrees to 0.05 pt on 53 of 64 items; the one unnumbered block that\n * belongs to an item (0000609 p1, \u00AB and crew across borders \u00BB, the last line\n * of item 1 split off) is 0.0 pt from its item's text;\n * - not aligned: the nearest disagreement is 1.3 pt, on a form (0000523), and\n * the nearest block after an item that does not 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\n * resumes after the marker on the first line, and the left of the second line\n * (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 (22/09/2026).\n *\n * `<ol>` counts its `<li>`, so an unnumbered block let in as an item shifts every\n * number after it: safedocs 0000713 p8 published \u00AB 1. \u00BB to \u00AB 5. \u00BB as 3 to 7. The\n * left edge of a block includes its marker, and an unnumbered block (a letter or\n * a 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\n * 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,\n * no gap, no duplicate) over at least `MIN_ITEMS` items. Otherwise every block\n * stays a paragraph, its written number in its text. Every tool read on\n * 22/09/2026 keeps the written number; none checks the sequence\n * (`docs/ETUDE-BIBLIOTHEQUES-PDF.md` [purged 27/09/2026, git history], lesson 21).\n *\n * Set aside (22/09/2026): letting in a NON-indented block aligned on the item's\n * text. It would put the \u00AB b) \u00BB and \u00AB c) \u00BB of 0000713 p8 back into item 5, but\n * the same geometry is a body paragraph after a list whose markers hang in the\n * margin (fixture 29: three body paragraphs 0.0 pt from the text of the bullet\n * before them). Nothing tells the two apart, so only blocks already in the run\n * 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 opener: ListCandidate | undefined;\n\n const close = (): void => {\n const exact = numbers.every((n, k) => n === numbers[0]! + k);\n if (items.length >= MIN_ITEMS && exact) 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 opener = 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 opener = candidate;\n } else if (opener !== undefined && continuesItem(opener, candidate)) {\n items[items.length - 1]!.push(index);\n } else {\n close();\n pieces.push({ kind: \"paragraph\", index });\n }\n }\n close();\n return pieces;\n}\n\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", "/** Decides WHERE a passage the render lost goes back into the published page, as its own paragraph between the two adjacent top-level paragraphs that hold its source neighbours \u2014 and hands the caller the edit and the letters it puts back, or why it abstains.\n * NOT here: finding the lost words and their neighbours (`pipeline/text-conservation.ts`), glued words (`pipeline/glued-word-repair.ts`), nor applying an edit, checking the page again and keeping or undoing the repair: all three are the caller's.\n * Called by: a caller of the published light door (`lib/pdf-light.ts`), once per checked PDF render. */\n\n/**\n * THE RULE (21/09/2026, lot 5). A lost passage is a run of\n * consecutive source words neither reading found. Its neighbours are the\n * source words right before and right after it. It goes back ONLY when:\n * - each neighbour is a word the page matched (not an alt text, a list\n * number, a re-spacing: those have no single place in the page);\n * - the neighbour before is the LAST word of a top-level paragraph or\n * heading, the one after the FIRST word of the next top-level element,\n * with nothing between the two elements;\n * - at the start or the end of the document, the one neighbour opens the\n * page's first text block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB, visible on the\n * dashboard: a loss inside a paragraph, a table cell, a list, an image\n * between the two paragraphs. A paragraph cut in the wrong place reads as if\n * nothing were wrong; a \u00AB N characters are not published \u00BB line does not.\n *\n * WHY THE XHTML AND NOT THE DOCUMENT MODEL (as lot 4). The check locates each\n * neighbour by block and word in the XHTML it read; the insertion goes at an\n * element boundary of that same XHTML, so no second mapping can disagree. The\n * inserted paragraph is the words as the PDF reads them, joined by single\n * spaces, escaped by the serializer's own `escapeText`.\n *\n * THE UNDO IS THE CALLER'S, NOT THIS MODULE'S. A caller applies the edits,\n * checks the repaired page again, and decides alone whether to keep it or to\n * restore the original page and its verdict. This module publishes only what\n * that re-check needs: for each passage placed, the edit and the number of\n * letters it puts back (`LostTextInsertion`); for each passage left where it\n * was, why (`LostTextAbstention`). A caller that wants an exact repair keeps\n * it only when the lost letters drop by EXACTLY the letters handed back here\n * and nothing else of the page moves: that rule is written where it is run.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are\n * read in content-stream order. Measured on 871 paragraphs cut from the 45\n * fixture renders (21/09/2026): 426 put back with the page's letters exactly\n * as before, 22 put back elsewhere \u2014 where the stream reads them. Some of\n * those read better than the render did (a form label, 0000523), some worse\n * (a second column read line by line, fixture 11). Tried and NOT kept: also\n * requiring the blocks on each side to follow the source's order \u2014 it\n * caught 8 of the 22 and cost 17 exact repairs. Text back in the page is what\n * search needs; a paragraph slightly out of place is the lesser defect.\n *\n * \u26A0\uFE0F CLIENT TEXT, 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 \u2014 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/** Where each lost passage goes, as an edit for the caller to apply \u2014 or why it does not go anywhere.\n *\n * It reasons on the page's UNITS (`PublishedPage.units`), never on markup (09/11/2026): a passage is put back between\n * two units only when the source word before it is the LAST word of its unit, the one after it the FIRST of the next,\n * both units are prose or a title, and nothing of the page sits between them. Anything less certain abstains by name,\n * and the name travels to the caller so a reader of the dashboard knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container` \u2014 the same\n * answer as a page whose anchors sit somewhere 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 words = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = words.length - 1;\n const unitOf = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const edgeOf = (at: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const u = unitOf(at.block);\n if (u < 0 || units?.[u]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The last word of the unit (before) or its first (after): the loss must sit at the unit's edge, not inside it.\n const neighbourBlock = side === \"before\" ? at.block + 1 : at.block - 1;\n const atEdge = side === \"before\" ? at.word === (words[at.block] ?? 0) - 1 : at.word === 0;\n if (!atEdge || unitOf(neighbourBlock) === u) return \"loss-inside-block\";\n return u;\n };\n\n /** The unit the passage goes AFTER (`-1`: before the first unit), or why it does not. */\n const place = (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\") {\n if (after.block < before.block || (after.block === before.block && after.word <= before.word))\n return \"anchors-out-of-order\";\n }\n const u1 = before === \"document-edge\" ? undefined : edgeOf(before, \"before\");\n if (typeof u1 === \"string\") return u1;\n const u2 = after === \"document-edge\" ? undefined : edgeOf(after, \"after\");\n if (typeof u2 === \"string\") return u2;\n if (u1 === undefined) return after !== \"document-edge\" && after.block === 0 ? u2! - 1 : \"no-anchor\";\n if (u2 === undefined) return before !== \"document-edge\" && before.block === lastBlock ? u1 : \"no-anchor\";\n return u2 === u1 + 1 && units?.[u1]?.adjacentToNext === true ? u1 : \"blocks-not-adjacent\";\n };\n\n for (const passage of passages) {\n const at = place(passage);\n if (typeof at === \"string\") abstentions.push(at);\n else {\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: at, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((n, w) => n + conservationKey(w).length, 0),\n });\n }\n }\n return { insertions, abstentions };\n}\n"],
5
+ "mappings": ";AAkBA,SAAS,mBAAAA,kBAAiB,WAAW,kBAAkB,cAAAC,mBAAkB;;;ACgBzE,SAAS,uBAAoG;AAY7G,IAAM,OAAO;AAGb,IAAM,UAAU,CAAC,SACf,CAAC,GAAG,KAAK,SAAS,IAAI,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC,GAAG,KAAK,gBAAgB,EAAE,CAAC,CAAC,GAAG,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE;AAI9G,IAAM,UAAU,CAAC,UAAqC;AACpD,QAAM,QAAkB,CAAC;AACzB,MAAI,UAAkB,CAAC;AACvB,QAAM,QAAQ,MAAY;AACxB,QAAI,gBAAgB,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAG,OAAM,KAAK,OAAO;AACvF,cAAU,CAAC;AAAA,EACb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qBAAqB,MAAM,IAAI,MAAM,QAAQ,YAAY,KAAK,GAAG,EAAE;AAAA,QACjF,SAAS,QAAQ,YAAY,OAAO,CAAC,GAAG,MAAM,IAAIA,iBAAgB,CAAC,EAAE,QAAQ,CAAC;AAAA,MAChF,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;;;AJ9FA,SAAS,mBAAmB;AAG5B,SAAS,yBAAyB;",
6
+ "names": ["conservationKey", "wordKeysOf", "u", "conservationKey", "noWorse", "conservationKey"]
7
7
  }
package/dist/light.min.js CHANGED
@@ -1 +1 @@
1
- var X=n=>n.lostPassages.flatMap(e=>e.sourceWords).map(x).filter(e=>e.length>0),x=n=>n.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]/gu,""),A=n=>n.split(/\s+/).map(x).filter(e=>e.length>0),G=/[-‐­]$/u,F=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,$=n=>{let e="",o=[],t=()=>{e+=" ",o.push(-1)};return n.forEach((r,l)=>{e+=r.text;for(let s=0;s<r.text.length;s++)o.push(l);let u=n[l+1];if(u===void 0)return;if(r.hasEOL){t();return}let f=Math.max(r.fontSize,1),c=Math.abs(u.y-r.y)<.5*f,a=u.x-(r.x+r.width);c&&a<.15*f&&a>-.5*f||t()}),{text:e,owner:o}},q=(n,e)=>n.flatMap((o,t)=>{if(e.has(t))return[];let r=o,{text:l,owner:u}=$(r),f=s=>r[u[s]]?.fontSize??0,c=[],a=[];for(let s of l.matchAll(/\S+/g)){let d=s[0],b=x(d);b.length>0?(c.push({raw:d,key:b,page:t+1,gap:a,firstSize:f(s.index),lastSize:f(s.index+d.length-1)}),a=[]):a.push(d)}return c}),J=n=>{let e=[],o=0;for(let t of n.blocks){let r=A(t);r.length!==0&&(r.forEach((l,u)=>e.push({key:l,at:{block:o,word:u}})),o+=1)}return{body:e,extras:[...n.extras??[]]}},Q=(n,e)=>{let o=new Map;n.forEach((f,c)=>{let a=o.get(f);a===void 0?o.set(f,[c]):a.push(c)});let t=[],r=0;e.forEach((f,c)=>{for(let a of o.get(f)??[]){if(a>0&&c>0&&n[a-1]===e[c-1])continue;let s=1;for(;a+s<n.length&&c+s<e.length&&n[a+s]===e[c+s];)s++;(t[s]??=[]).push([a,c]),r=Math.max(r,s)}});let l=new Int32Array(n.length).fill(-1),u=new Uint8Array(e.length);for(let f=r;f>=1;f--){let c=t[f];for(let a=0;c!==void 0&&a<c.length;a++){let[s,d]=c[a],b=!0;for(let g=0;g<f&&b;g++)b=l[s+g]===-1&&u[d+g]===0;if(b){for(let g=0;g<f;g++)l[s+g]=d+g,u[d+g]=1;continue}let m=-1;for(let g=0;g<=f;g++){let y=g<f&&l[s+g]===-1&&u[d+g]===0;y&&m<0&&(m=g),!y&&m>=0&&((t[g-m]??=[]).push([s+m,d+m]),m=-1)}}}return{srcTo:l,renUsed:u}},I=(n,e,o)=>{let t=new Map;for(let r of o)for(let l of A(r))t.set(l,(t.get(l)??0)+1);return n.filter(r=>{let l=t.get(e[r].key)??0;return l===0?!0:(t.set(e[r].key,l-1),!1)})},D=(n,e,o,t,r,l)=>{let u=new Map,f=new Set;for(let a of t){if(l.one.has(a))continue;let s=r(a);(u.get(s)??u.set(s,[]).get(s)).push(a);for(let d=1;d<=s.length;d++)f.add(s.slice(0,d))}let c=[];for(let a=0;a<n.length;a++){if(l.many.has(n[a]))continue;let s="";for(let d=a;d<n.length;d++){let b=n[d];if(l.many.has(b)||d>a&&!o(n[d-1],b)||(s+=e(b),!f.has(s)))break;let m=d>a?u.get(s)?.filter(y=>!l.one.has(y)):void 0;if(m===void 0||m.length===0)continue;let g=n.slice(a,d+1);g.forEach(y=>l.many.add(y)),l.one.add(m[0]),c.push([g,m[0]]),a=d;break}}return c},B=n=>{let e=new Map;for(let o of n)e.set(o,(e.get(o)??0)+1);return e},Z=(n,e)=>{let o=B(n);for(let[t,r]of o)if((e.get(t)??0)<r)return!1;for(let[t,r]of o)e.set(t,e.get(t)-r);return!0},T=(n,e)=>[...new Set([...n].map(o=>e[o].page))].sort((o,t)=>o-t);function ee(n,e,o={}){let t=q(n,o.excludedPages??new Set),{body:r,extras:l}=J(e),{srcTo:u,renUsed:f}=Q(t.map(i=>i.key),r.map(i=>i.key)),c=[];u.forEach((i,p)=>{i===-1&&c.push(p)}),c=I(c,t,l),c=I(c,t,o.deliberateRemovals??[]);let a=[];f.forEach((i,p)=>{i===0&&a.push(p)});let s={many:new Set,one:new Set},d=D(c,i=>t[i].key,(i,p)=>p===i+1,a,i=>r[i].key,s),b={many:new Set,one:new Set(s.many)},m=D(a.filter(i=>!s.one.has(i)),i=>r[i].key,(i,p)=>p===i+1&&r[i].at.block===r[p].at.block,c,i=>t[i].key,b),g=[],y=new Set,P=0;for(let[i,p]of d){i.forEach(L=>y.add(L));let h=i.map(L=>t[L].raw);h.slice(0,-1).every(L=>G.test(L))||i.every(L=>t[L].key.length<=1)||F.test(h.join(""))||(P+=1,g.push({kind:"glued",page:t[i[0]].page,pageWords:[r[p].at],sourceWords:h}))}for(let[i,p]of m)y.add(p),P+=1,g.push({kind:"split",page:t[p].page,pageWords:i.map(h=>r[h].at),sourceWords:[t[p].raw]});let E=B(a.map(i=>r[i].key).join("")),k=[],W=[],C=[];for(let i of c){let p=Z(t[i].key,E);y.has(i)?p||W.push(i):p?C.push(i):k.push(i)}P+=C.length;let N=k.reduce((i,p)=>i+t[p].key.length,0),M=i=>{if(i<0||i>=t.length)return"document-edge";let p=u[i];return p===-1?"unanchored":r[p].at},O=[];for(let i=0;i<k.length;){let p=i;for(;p+1<k.length&&k[p+1]===k[p]+1;)p++;let h=k.slice(i,p+1);O.push({page:t[h[0]].page,sourceWords:h.flatMap((R,L)=>L===0?[t[R].raw]:[...t[R].gap,t[R].raw]),before:M(h[0]-1),after:M(h[h.length-1]+1)}),i=p+1}let Y=a.filter(i=>!s.one.has(i)&&!b.many.has(i)).length,_=[];for(let{at:i}of r)(_[i.block]??=[]).push(null);u.forEach((i,p)=>{if(i===-1)return;let{at:h}=r[i];_[h.block][h.word]={index:p,firstSize:t[p].firstSize,lastSize:t[p].lastSize}});let S=(i,p,h)=>({decision:i,rule:p,margin:i==="lost"?N:0,lostLetters:N,gluedWords:P,pages:h,unmatchedPageWords:Y,respacings:g,sourceLetters:t.reduce((R,L)=>R+L.key.length,0),lostPassages:O,sourceOfPageWords:_});if(W.length>0)return S("abstain","readings-disagree",T(W,t));if(k.length>0)return S("lost","letters-missing",T(k,t));let v=[...new Set([...T(C,t),...g.map(i=>i.page)])].sort((i,p)=>i-p);return C.length>0?S("glued","letters-cover-unmatched-words",v):P>0?S("glued","respaced-words",v):S("ok","all-words-found",[])}var ne=/[\s\S]/gu,te=n=>[...n.matchAll(ne)].map(e=>({text:e[0],key:x(e[0]),end:e.index+e[0].length})),re=n=>{let e=[],o=[],t=()=>{x(o.map(r=>r.text).join("")).length>0&&e.push(o),o=[]};for(let r of n)/^\s+$/u.test(r.text)?t():o.push(r);return t(),e},U=(n,e)=>{let o=[...n],t=e==="lead"?o:[...o].reverse(),r=[];for(let l of t){if(x(l).length>0)break;r.push(l)}return(e==="lead"?r:[...r].reverse()).join("")},j=n=>n.replaceAll("\u200B",""),oe=(n,e)=>{let o=e.pageWords[0];if(e.kind!=="glued"||e.pageWords.length!==1||o===void 0||e.sourceWords.length<2)return;let t=n[o.block],r=t===void 0?void 0:te(t),l=r===void 0?void 0:re(r)[o.word];if(l===void 0)return;let u=e.sourceWords.map(x),f=x(l.map(d=>d.text).join(""));if(l.map(d=>d.key).join("")!==f||u.join("")!==f)return;let c=[],a=0,s=0;for(let d=0;d<u.length-1;d++){let b=s+u[d].length;for(;a<l.length&&s+l[a].key.length<=b&&s<b;)s+=l[a++].key.length;if(s!==b)return;let m=a;for(;m<l.length&&l[m].key.length===0;)m++;let g=l.slice(a,m),y=U(e.sourceWords[d],"trail");if(j(g.map(k=>k.text).join(""))!==y+U(e.sourceWords[d+1],"lead"))return;let P="",E=0;for(;P.length<y.length&&E<g.length;)P+=j(g[E++].text);if(P!==y)return;c.push(l[a+E-1].end),a+=E}return c};function se(n,e){let o=e.filter(u=>u.kind==="glued");if(o.length===0)return{edits:[],repaired:0};let t=new Set,r=[],l=0;for(let u of o){let f=u.pageWords[0]?.block,c=oe(n.blocks,u);if(!(c===void 0||f===void 0||c.some(a=>t.has(`${f}:${a}`)))){for(let a of c)t.add(`${f}:${a}`),r.push({kind:"insert-space",block:f,atChar:a});l+=1}}return{edits:r,repaired:l}}var ie=(n,e,o)=>e.lostLetters<=n.lostLetters&&(e.decision!=="lost"||n.decision==="lost")&&e.decision!=="abstain"&&e.gluedWords<=n.gluedWords-o&&e.unmatchedPageWords<=n.unmatchedPageWords&&e.respacings.filter(t=>t.kind==="split").length<=n.respacings.filter(t=>t.kind==="split").length;var H=n=>n.replace(/\s+/g," ").trim();var ae="\u2022\u25AA\u25E6\u2023\xB7\u25CF\u2043",de=new RegExp(`^\\s*[${ae}]\\s*`,"u"),le=/^\s*[-–—]\s+/u,ue=/^\s*(\d{1,2})[.)]\s+/u,ce=/^\s*[a-zA-Z][.)]\s+/u,fe=/^\s*[IVXivx]{1,4}[.)]\s+/u;function V(n){let e=ue.exec(n);if(e!==null)return{kind:"ordered",length:e[0].length,value:Number(e[1])};for(let[o,t]of[[de,"bullet"],[le,"bullet"],[fe,"letter"],[ce,"letter"]]){let r=o.exec(n);if(r!==null)return{kind:t,length:r[0].length}}}var z=3,ge=/[.:;!?»"…)]$/u,pe=n=>new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])","u").test(n),be=n=>x(n.split(/\s+/)[0]??"").length<=1,K=(n,e)=>H(e.map(o=>n.blocks[o]??"").join(" ")),me=(n,e)=>{let o=[...n,...e];if(n.length===0||e.length===0||o.some(u=>u===null))return!1;let t=o;for(let u=1;u<t.length;u++)if(t[u].index!==t[u-1].index+1)return!1;let r=t[n.length-1],l=t[n.length];return Math.abs(r.lastSize-l.firstSize)<.01},he=(n,e)=>e.decision!=="abstain"&&(e.decision!=="lost"||n.decision==="lost")&&e.lostLetters<=n.lostLetters&&e.gluedWords<=n.gluedWords&&e.unmatchedPageWords<=n.unmatchedPageWords;function ye(n,e){let o=n.units;if(o===void 0||e.decision==="abstain")return{edits:[],joined:0};let t=o.map(u=>u.blocks.flatMap(f=>e.sourceOfPageWords[f]??[])),r=u=>{let f=o[u],c=o[u+1];if(!f.joinable||!c.joinable||!f.adjacentToNext)return!1;let a=K(n,f.blocks),s=K(n,c.blocks);return a.length===0||ge.test(a)||!pe(s)||V(s)!==void 0||be(s)?!1:me(t[u].slice(-z),t[u+1].slice(0,z))},l=[];for(let u=o.length-2;u>=0;u--)r(u)&&l.push({kind:"join-units",unit:u});return{edits:l,joined:l.length}}function xe(n,e){let o=[],t=[];if(e.length===0)return{insertions:o,abstentions:t};let r=n.units,l=n.blocks.map(s=>A(s).length),u=l.length-1,f=s=>r?.findIndex(d=>d.blocks.includes(s))??-1,c=(s,d)=>{let b=f(s.block);if(b<0||r?.[b]?.paragraphOrHeading!==!0)return"anchor-in-container";let m=d==="before"?s.block+1:s.block-1;return!(d==="before"?s.word===(l[s.block]??0)-1:s.word===0)||f(m)===b?"loss-inside-block":b},a=s=>{let{before:d,after:b}=s;if(d==="unanchored"||b==="unanchored")return"anchor-unmatched";if(d==="document-edge"&&b==="document-edge")return"no-anchor";if(d!=="document-edge"&&b!=="document-edge"&&(b.block<d.block||b.block===d.block&&b.word<=d.word))return"anchors-out-of-order";let m=d==="document-edge"?void 0:c(d,"before");if(typeof m=="string")return m;let g=b==="document-edge"?void 0:c(b,"after");return typeof g=="string"?g:m===void 0?b!=="document-edge"&&b.block===0?g-1:"no-anchor":g===void 0?d!=="document-edge"&&d.block===u?m:"no-anchor":g===m+1&&r?.[m]?.adjacentToNext===!0?m:"blocks-not-adjacent"};for(let s of e){let d=a(s);typeof d=="string"?t.push(d):o.push({edit:{kind:"insert-unit-after",unit:d,text:s.sourceWords.join(" ")},letters:s.sourceWords.reduce((b,m)=>b+x(m).length,0)})}return{insertions:o,abstentions:t}}var w=class extends Error{constructor(o,t,r,l){super(t,l);this.code=o;this.name="ReaderError",r?.pageCount!==void 0&&(this.pageCount=r.pageCount),r?.scannedPageCount!==void 0&&(this.scannedPageCount=r.scannedPageCount)}code;pageCount;scannedPageCount};var Ue=Number.MAX_SAFE_INTEGER,ke=5e7;export{ke as MAX_PAYLOAD_BYTES,w as ReaderError,x as conservationKey,ye as cutParagraphEdits,se as gluedWordEdits,he as joinNoWorse,X as lostWords,ie as noWorse,xe as placeLostPassages,ee as textConservation,A as wordKeysOf};
1
+ import{conservationKey as ae,lostWords as fe,textConservation as pe,wordKeysOf as me}from"doc-ir";import{conservationKey as g}from"doc-ir";var A=/[\s\S]/gu,I=t=>[...t.matchAll(A)].map(e=>({text:e[0],key:g(e[0]),end:e.index+e[0].length})),R=t=>{let e=[],n=[],r=()=>{g(n.map(d=>d.text).join("")).length>0&&e.push(n),n=[]};for(let d of t)/^\s+$/u.test(d.text)?r():n.push(d);return r(),e},L=(t,e)=>{let n=[...t],r=e==="lead"?n:[...n].reverse(),d=[];for(let u of r){if(g(u).length>0)break;d.push(u)}return(e==="lead"?d:[...d].reverse()).join("")},k=t=>t.replaceAll("\u200B",""),W=(t,e)=>{let n=e.pageWords[0];if(e.kind!=="glued"||e.pageWords.length!==1||n===void 0||e.sourceWords.length<2)return;let r=t[n.block],d=r===void 0?void 0:I(r),u=d===void 0?void 0:R(d)[n.word];if(u===void 0)return;let o=e.sourceWords.map(g),a=g(u.map(s=>s.text).join(""));if(u.map(s=>s.key).join("")!==a||o.join("")!==a)return;let p=[],c=0,i=0;for(let s=0;s<o.length-1;s++){let l=i+o[s].length;for(;c<u.length&&i+u[c].key.length<=l&&i<l;)i+=u[c++].key.length;if(i!==l)return;let f=c;for(;f<u.length&&u[f].key.length===0;)f++;let m=u.slice(c,f),h=L(e.sourceWords[s],"trail");if(k(m.map(E=>E.text).join(""))!==h+L(e.sourceWords[s+1],"lead"))return;let x="",b=0;for(;x.length<h.length&&b<m.length;)x+=k(m[b++].text);if(x!==h)return;p.push(u[c+b-1].end),c+=b}return p};function v(t,e){let n=e.filter(o=>o.kind==="glued");if(n.length===0)return{edits:[],repaired:0};let r=new Set,d=[],u=0;for(let o of n){let a=o.pageWords[0]?.block,p=W(t.blocks,o);if(!(p===void 0||a===void 0||p.some(c=>r.has(`${a}:${c}`)))){for(let c of p)r.add(`${a}:${c}`),d.push({kind:"insert-space",block:a,atChar:c});u+=1}}return{edits:d,repaired:u}}var M=(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&&e.respacings.filter(r=>r.kind==="split").length<=t.respacings.filter(r=>r.kind==="split").length;import{collapseBlanks as S}from"doc-ir/internal";var _="\u2022\u25AA\u25E6\u2023\xB7\u25CF\u2043",B=new RegExp(`^\\s*[${_}]\\s*`,"u"),N=/^\s*[-–—]\s+/u,O=/^\s*(\d{1,2})[.)]\s+/u,w=/^\s*[a-zA-Z][.)]\s+/u,C=/^\s*[IVXivx]{1,4}[.)]\s+/u;function y(t){let e=O.exec(t);if(e!==null)return{kind:"ordered",length:e[0].length,value:Number(e[1])};for(let[n,r]of[[B,"bullet"],[N,"bullet"],[C,"letter"],[w,"letter"]]){let d=n.exec(t);if(d!==null)return{kind:r,length:d[0].length}}}import{conservationKey as j}from"doc-ir";var P=3,U=/[.:;!?»"…)]$/u,V=t=>new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])","u").test(t),D=t=>j(t.split(/\s+/)[0]??"").length<=1,T=(t,e)=>S(e.map(n=>t.blocks[n]??"").join(" ")),Y=(t,e)=>{let n=[...t,...e];if(t.length===0||e.length===0||n.some(o=>o===null))return!1;let r=n;for(let o=1;o<r.length;o++)if(r[o].index!==r[o-1].index+1)return!1;let d=r[t.length-1],u=r[t.length];return Math.abs(d.lastSize-u.firstSize)<.01},K=(t,e)=>e.decision!=="abstain"&&(e.decision!=="lost"||t.decision==="lost")&&e.lostLetters<=t.lostLetters&&e.gluedWords<=t.gluedWords&&e.unmatchedPageWords<=t.unmatchedPageWords;function G(t,e){let n=t.units;if(n===void 0||e.decision==="abstain")return{edits:[],joined:0};let r=n.map(o=>o.blocks.flatMap(a=>e.sourceOfPageWords[a]??[])),d=o=>{let a=n[o],p=n[o+1];if(!a.joinable||!p.joinable||!a.adjacentToNext)return!1;let c=T(t,a.blocks),i=T(t,p.blocks);return c.length===0||U.test(c)||!V(i)||y(i)!==void 0||D(i)?!1:Y(r[o].slice(-P),r[o+1].slice(0,P))},u=[];for(let o=n.length-2;o>=0;o--)d(o)&&u.push({kind:"join-units",unit:o});return{edits:u,joined:u.length}}import{conservationKey as $,wordKeysOf as F}from"doc-ir";function H(t,e){let n=[],r=[];if(e.length===0)return{insertions:n,abstentions:r};let d=t.units,u=t.blocks.map(i=>F(i).length),o=u.length-1,a=i=>d?.findIndex(s=>s.blocks.includes(i))??-1,p=(i,s)=>{let l=a(i.block);if(l<0||d?.[l]?.paragraphOrHeading!==!0)return"anchor-in-container";let f=s==="before"?i.block+1:i.block-1;return!(s==="before"?i.word===(u[i.block]??0)-1:i.word===0)||a(f)===l?"loss-inside-block":l},c=i=>{let{before:s,after:l}=i;if(s==="unanchored"||l==="unanchored")return"anchor-unmatched";if(s==="document-edge"&&l==="document-edge")return"no-anchor";if(s!=="document-edge"&&l!=="document-edge"&&(l.block<s.block||l.block===s.block&&l.word<=s.word))return"anchors-out-of-order";let f=s==="document-edge"?void 0:p(s,"before");if(typeof f=="string")return f;let m=l==="document-edge"?void 0:p(l,"after");return typeof m=="string"?m:f===void 0?l!=="document-edge"&&l.block===0?m-1:"no-anchor":m===void 0?s!=="document-edge"&&s.block===o?f:"no-anchor":m===f+1&&d?.[f]?.adjacentToNext===!0?f:"blocks-not-adjacent"};for(let i of e){let s=c(i);typeof s=="string"?r.push(s):n.push({edit:{kind:"insert-unit-after",unit:s,text:i.sourceWords.join(" ")},letters:i.sourceWords.reduce((l,f)=>l+$(f).length,0)})}return{insertions:n,abstentions:r}}import{ReaderError as Le}from"doc-ir";import{MAX_PAYLOAD_BYTES as ye}from"doc-ir";export{ye as MAX_PAYLOAD_BYTES,Le as ReaderError,ae as conservationKey,G as cutParagraphEdits,v as gluedWordEdits,K as joinNoWorse,fe as lostWords,M as noWorse,H as placeLostPassages,pe as textConservation,me as wordKeysOf};
@@ -1,4 +1,4 @@
1
- import type { GlyphFragment } from "./glyph-positions";
1
+ import type { GlyphFragment } from "./glyph-positions.js";
2
2
  export declare const CENTRE_EM = 0.1;
3
3
  export declare const RAISE_EM = 0.5;
4
4
  export declare function composeAccents(glyphs: readonly GlyphFragment[]): GlyphFragment[];
@@ -1,2 +1,2 @@
1
- import type { GlyphFragment } from "./glyph-positions";
1
+ import type { GlyphFragment } from "./glyph-positions.js";
2
2
  export declare function dropDoubleDraws(glyphs: GlyphFragment[]): GlyphFragment[];
@@ -1,6 +1,6 @@
1
- import { ReaderError } from "../../../doc-ir/src/lib/reader-error";
2
- import { type Matrix2D } from "../../../doc-ir/src/layout/geometry";
3
- import { GRAPHICS_STATE_MAX_DEPTH, type PdfOp } from "./pdf-ops";
1
+ import { ReaderError } from "doc-ir";
2
+ import { type Matrix2D } from "../layout/geometry.js";
3
+ import { GRAPHICS_STATE_MAX_DEPTH, type PdfOp } from "./pdf-ops.js";
4
4
  export { GRAPHICS_STATE_MAX_DEPTH };
5
5
  export type NamedOp = PdfOp;
6
6
  export type GlyphAbstentionTag = "vertical-writing" | "text-operator";
@@ -1,5 +1,5 @@
1
- import { type FontScaleOf, type GlyphFragment, type HidePolicy, type NamedOp, type SymbolFontOf } from "./glyph-positions";
2
- import type { PdfTextRun } from "./pdf-source";
1
+ import { type FontScaleOf, type GlyphFragment, type HidePolicy, type NamedOp, type SymbolFontOf } from "./glyph-positions.js";
2
+ import type { PdfTextRun } from "./pdf-source.js";
3
3
  export interface GlyphRunOptions {
4
4
  pageObjId?: string | undefined;
5
5
  view?: readonly [number, number, number, number] | undefined;
@@ -1,4 +1,4 @@
1
- import type { GlyphFragment } from "./glyph-positions";
1
+ import type { GlyphFragment } from "./glyph-positions.js";
2
2
  export interface GlyphWindowOptions {
3
3
  readonly anchor: "centre" | "start";
4
4
  readonly leftSlackEm: number;
@@ -1,6 +1,6 @@
1
- import type { IRBlock } from "../../../doc-ir/src/lib/ir";
2
- import type { ImageAnchor, PageRegion } from "./pdf-model";
3
- import type { PdfTextRun } from "./pdf-source";
1
+ import type { IRBlock } from "doc-ir";
2
+ import type { ImageAnchor, PageRegion } from "./pdf-model.js";
3
+ import type { PdfTextRun } from "./pdf-source.js";
4
4
  export interface AsideFigure {
5
5
  readonly anchor: ImageAnchor;
6
6
  readonly lines: readonly PdfTextRun[][];
@@ -1,4 +1,4 @@
1
- import type { PositionedItem } from "./pdf-model";
1
+ import type { PositionedItem } from "./pdf-model.js";
2
2
  export interface BandedSplit<T> {
3
3
  above: T[][];
4
4
  left: T[][];
@@ -1,5 +1,5 @@
1
- import { type PdfObjectsDocument } from "./pdf-objects/document";
2
- import { type PictureScope } from "./pdf-image-pixels";
1
+ import { type PdfObjectsDocument } from "./pdf-objects/document.js";
2
+ import { type PictureScope } from "./pdf-image-pixels.js";
3
3
  export interface DecodedImageObject {
4
4
  readonly ref: string | undefined;
5
5
  readonly width: number;
@@ -1,5 +1,5 @@
1
- import type { CellLine } from "../../../doc-ir/src/layout/cell-text";
2
- import type { Fragment } from "../../../doc-ir/src/layout/geometry";
1
+ import type { CellLine } from "../layout/cell-text.js";
2
+ import type { Fragment } from "../layout/geometry.js";
3
3
  export declare const isNumberAlone: (text: string) => boolean;
4
4
  export declare const wouldFabricateNumber: (previous: string, next: string) => boolean;
5
5
  export declare const joinCellLines: (lines: readonly CellLine[], marginRight: number) => CellLine[];
@@ -1,4 +1,4 @@
1
- import type { PdfTextRun } from "./pdf-source";
1
+ import type { PdfTextRun } from "./pdf-source.js";
2
2
  export interface ColumnCut {
3
3
  cut: number;
4
4
  above?: number;
@@ -1,4 +1,4 @@
1
- import type { PdfObjectsDocument } from "./pdf-objects/document";
1
+ import type { PdfObjectsDocument } from "./pdf-objects/document.js";
2
2
  export interface OurDocumentInfo {
3
3
  producer?: string;
4
4
  creator?: string;