pdf-skryba 0.9.0 → 0.10.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.
package/dist/light.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/pdf-light.ts", "../src/pipeline/glued-word-repair.ts", "../src/pipeline/cut-paragraph-repair.ts", "../src/layout/list.ts", "../src/pipeline/lost-text-repair.ts"],
4
- "sourcesContent": ["/**\n * THE READER-FREE HALF OF THE 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"],
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 * (a labelling trial, 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 * (a study of the PDF libraries, 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
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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A,EACtE;AAEA,aAAW,WAAW,UAAU;AAC9B,UAAM,KAAK,MAAM,OAAO;AACxB,QAAI,OAAO,OAAO,SAAU,aAAY,KAAK,EAAE;AAAA,SAC1C;AACH,iBAAW,KAAK;AAAA,QACd,MAAM,EAAE,MAAM,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
6
  "names": ["conservationKey", "wordKeysOf", "u", "conservationKey", "noWorse", "conservationKey"]
7
7
  }
@@ -8,4 +8,4 @@ export interface DecodedImageObject {
8
8
  readonly data: Uint8Array;
9
9
  readonly heldBytes?: number;
10
10
  }
11
- export declare function ccittImageObjectOf(doc: PdfObjectsDocument, file: Uint8Array, scope: PictureScope, name: string, grey1Kind: number): DecodedImageObject | undefined;
11
+ export declare function ccittImageObjectOf(doc: PdfObjectsDocument, scope: PictureScope, name: string, grey1Kind: number): DecodedImageObject | undefined;
@@ -89,6 +89,7 @@ export interface PdfExtractResult {
89
89
  places: readonly LostPlace[];
90
90
  }>;
91
91
  textUnreadByPage: ReadonlyMap<number, PdfTextUnreadReason>;
92
+ unreadObjectsByPage: ReadonlyMap<number, number>;
92
93
  docFacts: PdfDocumentFacts;
93
94
  cost: ExtractionCost;
94
95
  images?: RawImage[];
@@ -1,8 +1,12 @@
1
1
  import { ReaderError } from "doc-ir";
2
- export type PdfObjectsRefusalReason = "syntax" | "truncated" | "nesting-too-deep" | "token-too-long" | "string-too-long" | "stream-length" | "stream-end" | "length-unresolved" | "startxref-missing" | "xref-offset" | "xref-syntax" | "xref-chain" | "xref-too-large" | "filter-unsupported" | "predictor" | "stream-decode" | "object-stream" | "xref-stream" | "xref-stale" | "ref-hops" | "page-tree" | "page-box" | "content-syntax" | "content-operands" | "content-too-long" | "inline-image" | "encrypted" | "to-unicode" | "value-too-large" | "document-too-large" | "glyphs-too-many" | "forms-too-many" | "font-tables-too-many" | "page-missing";
2
+ export type PdfObjectsRefusalReason = "syntax" | "truncated" | "nesting-too-deep" | "token-too-long" | "string-too-long" | "stream-length" | "stream-end" | "stream-too-large" | "length-unresolved" | "startxref-missing" | "xref-offset" | "xref-syntax" | "xref-chain" | "xref-too-large" | "filter-unsupported" | "predictor" | "stream-decode" | "object-stream" | "xref-stream" | "xref-stale" | "ref-hops" | "page-tree" | "page-box" | "content-syntax" | "content-operands" | "content-too-long" | "inline-image" | "encrypted" | "to-unicode" | "value-too-large" | "document-too-large" | "glyphs-too-many" | "forms-too-many" | "font-tables-too-many" | "page-missing";
3
3
  export declare class PdfObjectsRefusal extends ReaderError {
4
4
  readonly reason: PdfObjectsRefusalReason;
5
5
  readonly objectNumber?: number | undefined;
6
6
  readonly offset?: number | undefined;
7
7
  constructor(reason: PdfObjectsRefusalReason, objectNumber?: number | undefined, offset?: number | undefined);
8
8
  }
9
+ export declare const REFUSAL_IS_BOUND: Record<PdfObjectsRefusalReason, boolean>;
10
+ export declare function isSecurityRefusal(error: unknown): boolean;
11
+ export declare function rethrowSecurityRefusal(error: unknown): void;
12
+ export declare function partOrAbsent<T>(read: () => T): T | undefined;
@@ -2,3 +2,4 @@ import type { PdfObjectsDocument, PdfPageEntry } from "./pdf-objects/document.js
2
2
  import { type GlyphMemo } from "./pdf-glyph-source.js";
3
3
  import type { PdfOp } from "./pdf-ops.js";
4
4
  export declare function ourOpsOfPage(doc: PdfObjectsDocument, page: PdfPageEntry, memo?: GlyphMemo): PdfOp[];
5
+ export declare const UNREADABLE_XOBJECT_OP = "unreadableXObject";
@@ -44,6 +44,7 @@ export interface PdfSourcePage {
44
44
  glyphs: GlyphFragment[];
45
45
  glyphsUnavailable?: PdfTextUnreadReason;
46
46
  fontUnread?: true;
47
+ unreadObjects?: number;
47
48
  declaredOrder?: readonly string[];
48
49
  noteIds?: ReadonlySet<string>;
49
50
  reference?: PdfReferenceCycle[];
@@ -104,6 +105,7 @@ interface PageText {
104
105
  glyphs: GlyphFragment[];
105
106
  glyphsUnavailable?: PdfTextUnreadReason;
106
107
  fontUnread?: true;
108
+ unreadObjects?: number;
107
109
  runs: PdfTextRun[];
108
110
  reference: PdfReferenceCycle[];
109
111
  }
@@ -19,6 +19,7 @@ type ImageLoss = {
19
19
  };
20
20
  export declare function pdfImageUnreadNotices(lossByPage: ReadonlyMap<number, ImageLoss>, replaced: ReadonlySet<number>): DocumentNotice[] | undefined;
21
21
  export declare function pdfTextUnreadNotices(unreadByPage: ReadonlyMap<number, PdfTextUnreadReason>, replaced: ReadonlySet<number>): DocumentNotice[] | undefined;
22
+ export declare function pdfPartUnreadNotices(unreadByPage: ReadonlyMap<number, number>, replaced: ReadonlySet<number>): DocumentNotice[] | undefined;
22
23
  export declare const extractPdf: (bytes: Uint8Array, pageLanguage?: PageLanguage, opts?: {
23
24
  pageLimit?: number;
24
25
  firstPages?: number;
@@ -7,5 +7,5 @@ export { openPdfObjects } from "../extractor/pdf-objects/document.js";
7
7
  export { PdfObjectsRefusal } from "../extractor/pdf-objects/refusal.js";
8
8
  export { pdfPageTabs } from "../extractor/pdf-page-tabs.js";
9
9
  export { readPdfSource } from "../extractor/pdf-source.js";
10
- export { walkPage } from "../extractor/pdf-table-detector.js";
10
+ export { detectPdfTableGrids, walkPage } from "../extractor/pdf-table-detector.js";
11
11
  export { DEFAULT_HEADING_SIZE_RATIO } from "../layout/heading-sizes.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pdf-skryba",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Reads a PDF into a structured representation, and checks that no word was lost on the way.",
5
5
  "keywords": [
6
6
  "pdf",
@@ -71,7 +71,7 @@
71
71
  ],
72
72
  "dependencies": {
73
73
  "@cantoo/pdf-lib": "^2.11.1",
74
- "doc-ir": "^0.1.0"
74
+ "doc-ir": "^0.2.0"
75
75
  },
76
76
  "devDependencies": {
77
77
  "@arethetypeswrong/cli": "0.18.5",