pdf-skryba 0.10.1 → 0.10.2

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 * (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
- "mappings": ";AAkBA,SAAS,mBAAAA,kBAAiB,WAAW,kBAAkB,cAAAC,mBAAkB;;;ACgBzE,SAAS,uBAAoG;AAY7G,IAAM,OAAO;AAGb,IAAM,UAAU,CAAC,SACf,CAAC,GAAG,KAAK,SAAS,IAAI,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC,GAAG,KAAK,gBAAgB,EAAE,CAAC,CAAC,GAAG,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE;AAI9G,IAAM,UAAU,CAAC,UAAqC;AACpD,QAAM,QAAkB,CAAC;AACzB,MAAI,UAAkB,CAAC;AACvB,QAAM,QAAQ,MAAY;AACxB,QAAI,gBAAgB,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAG,OAAM,KAAK,OAAO;AACvF,cAAU,CAAC;AAAA,EACb;AACA,aAAW,KAAK,OAAO;AACrB,QAAI,SAAS,KAAK,EAAE,IAAI,EAAG,OAAM;AAAA,QAC5B,SAAQ,KAAK,CAAC;AAAA,EACrB;AACA,QAAM;AACN,SA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EAAE,QAAQ,CAAC;AAAA,MAChF,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;;;AJ9FA,SAAS,mBAAmB;AAG5B,SAAS,yBAAyB;",
6
- "names": ["conservationKey", "wordKeysOf", "u", "conservationKey", "noWorse", "conservationKey"]
4
+ "sourcesContent": ["/**\n * The reader-free half of the package (`pdf-skryba/light`): the conservation check of a PDF and the types it speaks\n * in. It must load no PDF reader, no zip and no XML, so that a consumer checking text pays for none of them.\n *\n * How a consumer checks a PDF: it hands back the text it published, block by block (`PublishedPage`), and gets what\n * was lost, invented, glued or split, in the coordinates of its own blocks, never in its markup. The three repairs come\n * back as `PageEdit`s the caller applies itself: the library proves what changes and where; writing the page is the\n * caller's job, since only the caller knows its markup.\n */\n\nexport { conservationKey, lostWords, textConservation, wordKeysOf } from \"doc-ir\";\nexport type {\n ConservationRule,\n ConservationRun,\n ConservationVerdict,\n PageEdit,\n PageWordAt,\n PublishedPage,\n Respacing,\n SourceWordLink,\n} from \"doc-ir\";\n\n/** The three repairs, as DECISIONS: each says what to change and where, and writes nothing. */\nexport { gluedWordEdits, noWorse } from \"../pipeline/glued-word-repair\";\nexport { cutParagraphEdits, noWorse as joinNoWorse } from \"../pipeline/cut-paragraph-repair\";\nexport { placeLostPassages } from \"../pipeline/lost-text-repair\";\nexport type { LostPassage } from \"doc-ir\";\nexport type { LostTextAbstention, LostTextInsertion } from \"../pipeline/lost-text-repair\";\n\n/** The document the reader hands back, and what it could not publish. */\nexport type { IRBlock, IRDoc, IRTab, ImageRef, Inline, InlineMark, TableData } from \"doc-ir\";\nexport type { DocumentNotice, PageLanguage, PdfTextUnreadReason, PictureRefusal } from \"doc-ir\";\nexport { ReaderError } from \"doc-ir\";\nexport type { ReaderCountDetail } from \"doc-ir\";\nexport type { ReaderLimits } from \"doc-ir\";\nexport { MAX_PAYLOAD_BYTES } from \"doc-ir\";\nexport type { VisionPort, VisionResult } from \"doc-ir\";\nexport type { PageLabelOverride } from \"doc-ir\";\n", "/**\n * Proves where a glued page word should be split again, from the PDF's own reading, and hands the spaces back to the\n * caller as edits. The caller applies them and re-checks the page with `noWorse`.\n *\n * THE RULE. A page token is split only when its letters, as the conservation check normalises them, are exactly the\n * concatenation of the two or more consecutive source words the word reading proved. A space goes at each boundary the\n * source gives, and nothing else changes. Anything less certain is left alone and stays counted as glued.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the first of the next, the page may carry\n * non-letters (\u00AB IV.1.1)Vrsta \u00BB). They are split as the source words carry them: the first word's trailing characters,\n * then the next word's leading ones. When the page's characters there are not exactly those, the token is left alone\n * rather than guessed.\n *\n * Offsets are indices in the text the caller published, block by block, so the decision holds for any markup.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One code point of a published block: its text, its letters as the check normalises them, and where it ends in\n * that block's text. */\ninterface CodePoint {\n readonly text: string;\n readonly key: string;\n readonly end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole surrogate pair), so that `end` is a UTF-16 index usable\n * with `slice`. */\nconst CODE_POINT = /[\\s\\S]/gu;\n\nconst splitCodePoints = (text: string): CodePoint[] =>\n [...text.matchAll(CODE_POINT)].map((match) => ({\n text: match[0],\n key: conservationKey(match[0]),\n end: match.index + match[0].length,\n }));\n\n/** The block's words as the check splits them: runs of non-space code points holding at least one letter. The same\n * split as doc-ir's `wordKeysOf`, kept by code point so that offsets can be located. */\nconst splitWords = (codePoints: readonly CodePoint[]): CodePoint[][] => {\n const words: CodePoint[][] = [];\n let current: CodePoint[] = [];\n const closeWord = (): void => {\n if (conservationKey(current.map((codePoint) => codePoint.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const codePoint of codePoints) {\n if (/^\\s+$/u.test(codePoint.text)) closeWord();\n else current.push(codePoint);\n }\n closeWord();\n return words;\n};\n\n/** The leading or trailing characters of a source word that carry no letter. */\nconst readNonLetterEdge = (word: string, side: \"lead\" | \"trail\"): string => {\n const characters = [...word];\n const ordered = side === \"lead\" ? characters : [...characters].reverse();\n const edge: string[] = [];\n for (const character of ordered) {\n if (conservationKey(character).length > 0) break;\n edge.push(character);\n }\n return (side === \"lead\" ? edge : [...edge].reverse()).join(\"\");\n};\n\n/** A renderer may put a zero-width space before a superscript glued to a word. It carries nothing the source says:\n * it is passed over between the words, and the space goes before it. */\nconst removeZeroWidthSpaces = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** The page token a respacing points at, or `undefined` when the respacing is not one glued page word made of two or\n * more source words. */\nconst findGluedToken = (blocks: readonly string[], respacing: Respacing): CodePoint[] | undefined => {\n const pageWord = respacing.pageWords[0];\n if (\n respacing.kind !== \"glued\" ||\n respacing.pageWords.length !== 1 ||\n pageWord === undefined ||\n respacing.sourceWords.length < 2\n )\n return undefined;\n const text = blocks[pageWord.block];\n if (text === undefined) return undefined;\n return splitWords(splitCodePoints(text))[pageWord.word];\n};\n\n/** How many of the non-letter code points between two source words belong to the first word, or `undefined` when they\n * are not exactly the first word's trailing characters followed by the next word's leading ones. */\nconst countTrailingCodePoints = (between: readonly CodePoint[], trail: string, lead: string): number | undefined => {\n if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join(\"\")) !== trail + lead) return undefined;\n let taken = \"\";\n let takenCount = 0;\n while (taken.length < trail.length && takenCount < between.length) {\n taken += removeZeroWidthSpaces(between[takenCount++]!.text);\n }\n return taken === trail ? takenCount : undefined;\n};\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst findSpaceInsertions = (blocks: readonly string[], respacing: Respacing): number[] | undefined => {\n const token = findGluedToken(blocks, respacing);\n if (token === undefined) return undefined;\n const sourceKeys = respacing.sourceWords.map(conservationKey);\n const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(\"\"));\n // Code point by code point, the letters must add up to the token's own (NFKC can join across characters), and the\n // token must be exactly the source words.\n if (token.map((codePoint) => codePoint.key).join(\"\") !== tokenKey || sourceKeys.join(\"\") !== tokenKey)\n return undefined;\n\n const offsets: number[] = [];\n let position = 0;\n let letterCount = 0;\n for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {\n const boundary = letterCount + sourceKeys[sourceIndex]!.length;\n // The code point carrying the first word's last letter must end exactly at the boundary.\n while (position < token.length && letterCount + token[position]!.key.length <= boundary && letterCount < boundary)\n letterCount += token[position++]!.key.length;\n if (letterCount !== boundary) return undefined;\n // The non-letters up to the next word's first letter, split as the source says.\n let nextLetter = position;\n while (nextLetter < token.length && token[nextLetter]!.key.length === 0) nextLetter++;\n const takenCount = countTrailingCodePoints(\n token.slice(position, nextLetter),\n readNonLetterEdge(respacing.sourceWords[sourceIndex]!, \"trail\"),\n readNonLetterEdge(respacing.sourceWords[sourceIndex + 1]!, \"lead\"),\n );\n if (takenCount === undefined) return undefined;\n offsets.push(token[position + takenCount - 1]!.end);\n position += takenCount;\n }\n return offsets;\n};\n\n/** The spaces this check proves, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. It writes nothing: composing a page is the caller's job. */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((respacing) => respacing.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const takenOffsets = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const respacing of glued) {\n const block = respacing.pageWords[0]?.block;\n const offsets = findSpaceInsertions(page.blocks, respacing);\n if (\n offsets === undefined ||\n block === undefined ||\n offsets.some((offset) => takenOffsets.has(`${block}:${offset}`))\n )\n continue;\n for (const atChar of offsets) {\n takenOffsets.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** How many respacings of the verdict are splits: a source word published as several page words. */\nconst countSplitWords = (verdict: ConservationVerdict): number =>\n verdict.respacings.filter((respacing) => respacing.kind === \"split\").length;\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the edits and re-checks,\n * because it writes the page; the rule for keeping or undoing a repair stays here, so that no caller keeps a page\n * that lost a letter. A repair is kept whole or not at all. */\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict, repaired: number): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n countSplitWords(after) <= countSplitWords(before);\n", "/**\n * Proves where two adjacent paragraphs of a published page should be one: the render cut a sentence between them.\n * The edits go back to the caller, who applies them and re-checks the page with `noWorse`.\n *\n * THE RULE. Two units of the page, adjacent and both joinable, become one only when two independent readings agree:\n * - the shape of the published text: the first does not end a sentence and the second starts with a word all in\n * lower case. A second unit that opens on a list marker (\u00AB a. \u00BB, \u00AB iv) \u00BB, \u00AB \u2013 \u00BB) or on a token of one letter is\n * never a continuation;\n * - the PDF itself: the last three words of the first and the first three of the second are six source words in a\n * row in the content stream reading, and the two edge words are set at the same font size. The link from page word\n * to source word is the conservation check's own, so nothing is read twice.\n * Anything else stays as it is. A paragraph cut in two is still all there and searchable; two paragraphs joined by\n * mistake make a sentence that never existed.\n *\n * WHY THE CALLER DECIDES WHAT IS JOINABLE. Measured inside table cells, where each line is a paragraph, the same rule\n * gave 65 joins on 39 French and English PDFs, one of them wrong: two items of a list whose bullet is drawn, not in\n * the text layer, so the second opens on a lower-case word the PDF reads right after the first. A cell packs items\n * without markers far more often than prose does. The paragraphs of one list item, and two cells side by side, stay\n * apart for the same reason.\n *\n * WHY A TOKEN OF ONE LETTER STOPS THE JOIN. A bullet drawn with a symbol font reads as \u00AB x \u00BB in the text layer, a\n * lower-case word the PDF reads right after the line before; the list marker reader does not catch it. Refusing a\n * one-letter opening cost none of the right joins measured. The accepted limit: a real continuation opening on \u00AB il \u00BB,\n * \u00AB y \u00BB, \u00AB \u00E0 \u00BB or \u00AB a \u00BB is refused too.\n * Tried and set aside: reading the font of the opening glyph to recognise a drawn bullet. It needs the font of each run\n * carried through `ConservationRun`, for two joins on one document.\n *\n * The one wrong join left: a page of search results where a snippet is joined to the next result's title, which is\n * in lower case and read right after it. Nothing separates the two without reading the meaning.\n * Two consecutive headings are not joined: measured, the rule would join a report title with \u00AB Executive Summary \u00BB.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { collapseBlanks } from \"doc-ir/internal\";\nimport { markerOf } from \"../layout/list\";\nimport {\n conservationKey,\n type ConservationVerdict,\n type PageEdit,\n type PublishedPage,\n type SourceWordLink,\n} from \"doc-ir\";\n\n/** How many words each side of the cut must bring, read in a row by the PDF (fewer when the unit has fewer).\n * Simulated on 39 French and English PDFs: 41 joins with three words, 48 with one; the stricter window is kept. */\nconst EDGE_WORD_COUNT = 3;\n\nconst SENTENCE_END = /[.:;!?\u00BB\"\u2026)]$/u;\n/** \u00AB suite de la phrase \u00BB yes, \u00AB iPhone \u00BB no. */\nconst startsLowercaseWord = (text: string): boolean => /^\\p{Ll}+(?![\\p{L}\\p{N}])/u.test(text);\n\n/** A unit opening on a token of one letter: a bullet drawn with a symbol font, not a word carried over. */\nconst startsWithSingleLetterToken = (text: string): boolean => conservationKey(text.split(/\\s+/)[0] ?? \"\").length <= 1;\n\n/** The text of one unit as this rule reads it: the texts of its blocks joined by a space, since a line break inside\n * a paragraph ends a block. */\nconst readUnitText = (page: PublishedPage, blocks: readonly number[]): string =>\n collapseBlanks(blocks.map((blockIndex) => page.blocks[blockIndex] ?? \"\").join(\" \"));\n\n/** Whether a page word is linked to a source word; `null` marks a page word the conservation check could not link. */\nconst isSourceWordLink = (link: SourceWordLink | null): link is SourceWordLink => link !== null;\n\n/** Whether the PDF reads `tail` then `head` as source words in a row, the two edge words at one size. */\nconst isReadInARow = (tail: readonly (SourceWordLink | null)[], head: readonly (SourceWordLink | null)[]): boolean => {\n if (tail.length === 0 || head.length === 0) return false;\n const links = [...tail, ...head];\n if (!links.every(isSourceWordLink)) return false;\n for (let index = 1; index < links.length; index++) {\n if (links[index]!.index !== links[index - 1]!.index + 1) return false;\n }\n const tailLast = links[tail.length - 1]!;\n const headFirst = links[tail.length]!;\n return Math.abs(tailLast.lastSize - headFirst.firstSize) < 0.01;\n};\n\n/** Whether the published text reads as one sentence cut in two: the first unit does not end it and the second carries\n * it on, opening neither on a list marker nor on a token of one letter. */\nconst hasContinuationShape = (firstText: string, secondText: string): boolean => {\n if (firstText.length === 0 || SENTENCE_END.test(firstText)) return false;\n if (!startsLowercaseWord(secondText)) return false;\n if (markerOf(secondText) !== undefined) return false;\n return !startsWithSingleLetterToken(secondText);\n};\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the joins and re-checks,\n * because it writes the page; the rule for keeping or undoing them stays here, so that no caller keeps a page that\n * lost a letter. */\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict): boolean =>\n after.decision !== \"abstain\" &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.lostLetters <= before.lostLetters &&\n after.gluedWords <= before.gluedWords &&\n after.unmatchedPageWords <= before.unmatchedPageWords;\n\n/**\n * The joins this rule proves, as edits for the caller to apply to its own page; it writes nothing, since joining two\n * paragraphs is knowledge of one markup.\n *\n * It abstains with no `units` from the caller (it cannot know what a unit is on its own), with a verdict that abstains\n * (the links between page words and source words are then not trusted), for a unit the caller did not mark\n * `joinable`, and when anything of the page sits between the two units.\n */\nexport function cutParagraphEdits(\n page: PublishedPage,\n verdict: ConservationVerdict,\n): { edits: PageEdit[]; joined: number } {\n const units = page.units;\n if (units === undefined || verdict.decision === \"abstain\") return { edits: [], joined: 0 };\n\n const unitSourceLinks: readonly (readonly (SourceWordLink | null)[])[] = units.map((unit) =>\n unit.blocks.flatMap((blockIndex) => verdict.sourceOfPageWords[blockIndex] ?? []),\n );\n\n const isCutAfter = (unitIndex: number): boolean => {\n const firstUnit = units[unitIndex]!;\n const secondUnit = units[unitIndex + 1]!;\n if (!firstUnit.joinable || !secondUnit.joinable || !firstUnit.adjacentToNext) return false;\n const firstText = readUnitText(page, firstUnit.blocks);\n const secondText = readUnitText(page, secondUnit.blocks);\n if (!hasContinuationShape(firstText, secondText)) return false;\n return isReadInARow(\n unitSourceLinks[unitIndex]!.slice(-EDGE_WORD_COUNT),\n unitSourceLinks[unitIndex + 1]!.slice(0, EDGE_WORD_COUNT),\n );\n };\n\n // Right to left, so that applying a join never shifts a unit still to be looked at.\n const edits: PageEdit[] = [];\n for (let unitIndex = units.length - 2; unitIndex >= 0; unitIndex--) {\n if (isCutAfter(unitIndex)) edits.push({ kind: \"join-units\", unit: unitIndex });\n }\n return { edits, joined: edits.length };\n}\n", "/** The lists a PDF never declares, found in the markers and the hanging indent of its lines.\n * Not here: how a list becomes document blocks, nor paragraph grouping, both in `extractor/pdf-paragraphs.ts`. */\nimport { maxOf } from \"../lib/extent\";\nimport { SAME_LINE_PT } from \"./tolerances\";\n\n/**\n * The lists of a PDF, without a model.\n *\n * The rule: an item is a line indented against the body; a list is a run of at least two items, at least half of\n * which carry a readable marker.\n * A marker alone is not enough: a dash opening a sentence, a reference number or a date carry one. The indent alone\n * is not enough either: it finds far too many runs.\n * Chosen bias: the rule under-detects. A missed list loses no text; an invented list lies about the structure.\n * Not kept: the nesting level, drawn from successive quantised indents.\n *\n * BULLETS: A LIST ONLY IN THE SIMPLE CASE. A bullet is what this reader reads worst (a symbol-font letter, a dash glued\n * to its word, a vector disc, a wrapped line taken for an item), and the list is what lets the marker be REMOVED, so a\n * misread marker would make a false list. `listRuns` therefore publishes no run of bullets or dashes: such a run stays\n * paragraphs, the marker kept in the text (nothing removed, nothing lost). Only `bulletRuns` publishes a bulleted list,\n * under its own conditions. Measured on 51 French and English PDFs: 84 lists, 318 items, 0 invented list.\n */\n\n/**\n * The markers. The bullet character is often absent from the text layer (drawn beside it), so the pattern never\n * decides alone: the indent carries the signal and the marker confirms.\n *\n * And when the character IS there, it can be wrong (see the written limits below): a symbol font writes its bullet as\n * \u00AB x \u00BB or as a private code point, and only the font would tell. The font is not read here.\n */\n/** The bullet characters the list reader knows, once. */\nconst BULLET_CHARS = \"\u2022\u25AA\u25E6\u2023\u00B7\u25CF\u2043\";\n/** A line opening on a bullet. Its behaviour, with the four other marker patterns below, is frozen as a matrix in\n * `./list.markers.test.ts`: one line per example, one column per rule, so a drift shows as a cell. */\nexport const BULLET = new RegExp(`^\\\\s*[${BULLET_CHARS}]\\\\s*`, \"u\");\n/**\n * THE BLANK AFTER THE DASH IS REQUIRED, AND THAT IS A DECISION. Word 2007 glues its dash to its word (\u00AB -Ensures\n * Safety of the patient \u00BB), so such items publish as paragraphs.\n *\n * Accepting a glued dash was built and measured, then dropped. Over 39 French and English PDFs, 22 lines open on a\n * dash with NO blank after it, in 3 documents:\n * \u00B7 7 REAL items, where the dash IS the bullet (read on the page image);\n * \u00B7 15 that are not, and the two conditions already hold every one of them out of any list on their own: two\n * wrapped lines continuing \u00AB ALK\u2013positive \u00BB (not indented), \u00AB -30- \u00BB (the end mark of a press release, not\n * indented), and a timeline (\u00AB -Jan 2014--CAAS approves\u2026 \u00BB, 11 lines, never two indented in a row).\n * So the rule produced no false list at all, and it was still dropped. The text of the 7 items already comes out one\n * item per line: the list was a comfort, and its only effect on the text was to REMOVE the leading dash from 7 items.\n * A character of the document less, for nothing findable more. To reopen the day a document really loses something\n * here.\n */\nexport const DASH = /^\\s*[-\u2013\u2014]\\s+/u;\nexport const NUMBERED = /^\\s*(\\d{1,2})[.)]\\s+/u;\nexport const LETTERED = /^\\s*[a-zA-Z][.)]\\s+/u;\nexport const ROMAN = /^\\s*[IVXivx]{1,4}[.)]\\s+/u;\n\n/** The indent is quantised: two lines at 53.8 and 54.1 are at the same level. */\nconst INDENT_QUANTUM_PT = 3;\n/** A lone item is not a list: it is an indented paragraph. */\nconst MIN_ITEMS = 2;\n\n/*\n * WRITTEN LIMIT, NOT A DEFECT TO FIX. A labelling re-read of French and English documents found 35 items published as\n * plain paragraphs, in 8 documents, in three shapes: marked items that are NOT indented (20), several items fused into\n * one block (8), and word markers such as \u00AB Pas 1 : \u00BB (7). No text is lost; it stays searchable.\n * Tried and set aside: a run of CONSECUTIVE numbers (n, n+1\u2026) standing in for the indent. Measured over 34 French and\n * English PDFs: 7 runs, 17 items, no false list, and roughly half of the 20 unindented items, since any block slipped\n * between two items breaks the run. Too much mechanism for that gain. To reopen only if a real document loses\n * something because of a missed list.\n *\n * THREE MORE FAMILIES OF BULLET, MEASURED AND LEFT ALONE (the text already comes out line by line in all three, so the\n * drawn bullet is a comfort, and a marker that is not read is a marker that cannot be removed by mistake). The glued\n * dash is a fourth, written at `DASH` above.\n *\n * 1. **A BULLET PAINTED IN A SYMBOL FONT.** The same glyph comes out three different ways, because a symbol font's\n * glyphs have no character identity and the Unicode value a reader gives them is an accident of the font's cmap (a\n * symbolic TrueType (3,0) cmap maps to 0xF000 + code; ISO 32000-1 \u00A79.6.6.4):\n * SymbolMT 0xB7 \u2192 \u00AB \u2022 \u00BB U+2022, 68 runs, 6 documents: read\n * Wingdings 0xFC \u2192 U+F0FC, 17 runs, 1 document: a private code point, published as a tofu box\n * SymbolMT 0x78 \u2192 \u00AB x \u00BB U+0078, 24 runs, 1 document: a LETTER\n * The character cannot be the test, so the FONT would have to be: over 39 French and English PDFs, every run painted\n * in a font named for a symbol family is 116 runs, 9 fonts, 8 documents, ALL of ONE character and ALL bullets: 0 run\n * of prose, 0 run longer than one character. The discriminant is clean; its price is not. It needs the font name\n * resolved, a new field on every text run, and a new field on every line. Built and measured that way, it gave ONE\n * list of 6 items whose 6 lines already come out one per line. To reopen only if a document loses text for it.\n * Also tried: the private-use range U+E000\u2013U+F8FF as the test, which PyMuPDF4LLM does with U+F0B7 and U+F0A7\n * hard-coded. No new reading, 17 lines on the corpus, all bullets, 0 false; but it catches only the Wingdings\n * shape, not the \u00AB x \u00BB, and it publishes a list in place of lines that are already right.\n *\n * 2. **A DISC DRAWN IN VECTOR, not written.** One document marks 37 lines with a filled circle of 3.7 to 3.8 pt; all 37\n * sit 8.2 to 8.4 pt to the left of their line, on its baseline band (dy 2.1 to 2.6 pt): geometry clean enough to\n * attach. What stops it is elsewhere and it is bigger: every page of that document publishes as ONE TABLE, and a\n * table cell's blocks are built without the paragraph grouping, so no list is ever looked for inside a cell. The\n * marker would change nothing. And the size is no discriminant on its own: another document draws a watch with 484\n * small paths of 26 different sizes, 1.2 to 6.3 pt, 15 of which sit just left of a line.\n * 3. **A WRAPPED LINE TAKEN FOR AN ITEM.** A date published as an item of its own: it is the end of the line above,\n * indented like the items around it and carrying no marker, which the \u00AB half of them marked \u00BB rule lets in. Counted\n * over every item the 39 French and English PDFs publish (78), it is the ONLY one. One case is not a family, and no\n * text is lost.\n */\n\nexport const quantiseIndent = (x: number): number => Math.round(x / INDENT_QUANTUM_PT) * INDENT_QUANTUM_PT;\n\n/**\n * `letter` is a letter or a Roman numeral: \u00AB a. \u00BB, \u00AB iv) \u00BB. It counts as a marker for the list rule, but it never\n * leaves the text. A document list has no marker type, so the only ordered rendering counts 1, 2, 3: stripping \u00AB a. \u00BB\n * would replace every letter with a number, and the letters would be lost. A run of letters is therefore a BULLET list\n * whose items keep \u00AB a. \u00BB in their text: the simplest form that loses nothing and still says \"these are items\". Set\n * aside: no list at all (the items would then read as loose paragraphs), and a marker type in the document model (a\n * change to every renderer for one document).\n */\ntype MarkerKind = \"bullet\" | \"ordered\" | \"letter\";\n\nexport interface Marker {\n kind: MarkerKind;\n /** What the marker occupies at the head of the text, removed from the rendering only when the list's own marker\n * replaces it. */\n length: number;\n /** The number read, on an ordered marker that carries one. */\n value?: number;\n}\n\n/**\n * The marker at the head of a line, if any. A marker is read, not interpreted: \"ordered\" is what a number says, not\n * an inference on intent.\n *\n * It reads the text and nothing else: a marker the text cannot name is a written limit here, not a parameter (see\n * above).\n */\nexport function markerOf(text: string): Marker | undefined {\n const numbered = NUMBERED.exec(text);\n if (numbered !== null) return { kind: \"ordered\", length: numbered[0].length, value: Number(numbered[1]) };\n for (const [pattern, kind] of [\n [BULLET, \"bullet\"],\n [DASH, \"bullet\"],\n [ROMAN, \"letter\"],\n [LETTERED, \"letter\"],\n ] as const) {\n const match = pattern.exec(text);\n if (match !== null) return { kind, length: match[0].length };\n }\n return undefined;\n}\n\nexport interface ListCandidate {\n /** Indented against the document's body: the necessary condition. */\n indented: boolean;\n marker: Marker | undefined;\n /** The block's left edge, its marker INCLUDED: the lowest left of its lines. */\n left?: number;\n /** Where a numbered block's text starts (`itemTextLeft`). Absent: no reading,\n * or two readings that disagree. */\n textLeft?: number;\n /** Present on a paragraph block: where it sits on the page (`blockReading`). */\n geometry?: BlockGeometry;\n /** Present when the block opens on a real bullet character of its own (`blockReading`). */\n bullet?: BulletLead;\n}\n\ninterface ListRun {\n /** Inclusive. */\n start: number;\n /** Inclusive. */\n end: number;\n ordered: boolean;\n}\n\n/**\n * The runs of items in a sequence of consecutive blocks.\n *\n * A block joins the current run when it is indented; the run closes at the first block that is not. It is kept only\n * with at least `MIN_ITEMS` blocks, at least half of them marked. `ordered` follows the majority of the markers read.\n *\n * Tried and set aside: requiring the run's MARKED blocks to share one quantised indent (the literature's \u00AB bullet\n * partner detection AT THE SAME LEVEL \u00BB, of which only the partner is kept). It was written to hold back the one false\n * list the symbol-font marker produced (eight booklet pages imposed on one sheet, columns not cut, markers at 138,\n * 144, 312 and 318 pt). With the markers actually read, the level changes NOTHING over 39 French and English PDFs. A\n * guard that guards nothing is mechanism, so it is not here: to reopen with the page that needs it.\n */\nexport function listRuns(candidates: readonly ListCandidate[]): ListRun[] {\n const runs: ListRun[] = [];\n let start: number | undefined;\n\n const closeRun = (end: number): void => {\n if (start === undefined) return;\n const runCandidates = candidates.slice(start, end + 1);\n const marked = runCandidates.filter((candidate) => candidate.marker !== undefined);\n const countOfKind = (kind: MarkerKind): number =>\n marked.filter((candidate) => candidate.marker?.kind === kind).length;\n // A run of bullets or dashes is no list here (see the header; the simple bulleted case goes through `bulletRuns`).\n // The majority decides, as for `ordered`, and a tie falls on the side of ABSTENTION.\n const isBulleted = countOfKind(\"bullet\") * 2 >= marked.length;\n if (runCandidates.length >= MIN_ITEMS && marked.length * 2 >= runCandidates.length && !isBulleted) {\n const ordered = countOfKind(\"ordered\") * 2 > marked.length;\n runs.push({ start, end, ordered });\n }\n start = undefined;\n };\n\n for (const [index, candidate] of candidates.entries()) {\n if (candidate.indented) {\n start ??= index;\n continue;\n }\n closeRun(index - 1);\n }\n closeRun(candidates.length - 1);\n return runs;\n}\n\n/**\n * THE SIMPLE BULLETED RUN. A run of consecutive paragraph blocks is a bulleted list when ALL of these hold:\n * - at least `MIN_ITEMS` items, each opening on a real bullet character\n * (\u2022 \u25AA \u25E6 \u2023 \u25CF) that is a run of its own: not a dash, not a symbol-font letter\n * (\u00AB x \u00BB), not glued to its text (`blockReading`);\n * - the markers are at one x, the item texts at one x right of the marker, and\n * every wrapped line of an item is at the item-text x, never back at the\n * marker x (each within `BULLET_RUN_MAX_DRIFT_PT`);\n * - GUARD 1: no item carries a second bullet character (bullets laid out in two\n * columns: \u00AB \u25AA Safe Operations \u25AA Delivery of high-quality\u2026 \u00BB);\n * - indentation is NOT required.\n * Anything else stays paragraphs, marker kept in the text.\n *\n * GUARD 2, THE TAIL: an unmarked block at exactly the item-text x directly under the last item, no further below than\n * the list's own line spacing, is that item's continuation (a last item cut in two blocks) and is returned as `tail`.\n * The list's line spacing is the largest line pitch inside its own wrapped items; with none to measure it from, the\n * whole list is REJECTED (bias: abstain). Beyond that spacing the block is a paragraph of its own and the list stays.\n *\n * BULLET_RUN_MAX_DRIFT_PT = 1 pt, starting value to calibrate (the coordinate noise of `SAME_LINE_PT`). Measured over\n * 51 French and English PDFs: 84 runs (318 items) kept, every marker, text and wrapped line within 1 pt; the 14 runs\n * rejected fail on wrapped lines that are not at the text x (12), on item texts at 86.2 against 89.5 pt (1) and on a\n * bullet glued to its text (1); two of them also hold a bullet line inside an item.\n */\nconst BULLET_RUN_MAX_DRIFT_PT = SAME_LINE_PT;\n/** How much farther than the list's own line pitch a tail may start, in points: the same noise. Starting value to calibrate. */\nconst BULLET_TAIL_MAX_GAP_SLACK_PT = 1;\n\nconst BULLET_LEAD_CHARS = new Set([\"\u2022\", \"\u25AA\", \"\u25E6\", \"\u2023\", \"\u25CF\"]);\nconst ANY_BULLET_LEAD = /[\u2022\u25AA\u25E6\u2023\u25CF]/u;\n\n/** The pieces of a line `blockReading` needs: its text, left edge, baseline (decreasing down the page) and its first two items. */\nexport interface BlockLine {\n text: string;\n left: number;\n y: number;\n lead?: { text: string; nextLeft: number };\n}\n\nexport interface BlockGeometry {\n firstLeft: number;\n /** Baseline of the first line, and of the last. */\n firstY: number;\n lastY: number;\n /** The largest distance between two consecutive lines of the block; absent for a one-line block. */\n pitch?: number;\n}\n\nexport interface BulletLead {\n markerLeft: number;\n textLeft: number;\n /** The left edge of every line after the first. */\n continuationLefts: number[];\n /** Another bullet character after the first one, anywhere in the block. */\n secondBullet: boolean;\n}\n\n/** What the simple-bullet rule reads of a block's lines: where the block sits, and its bullet if it opens on a real one of its own. */\nexport function blockReading(lines: readonly BlockLine[]): { geometry?: BlockGeometry; bullet?: BulletLead } {\n const firstLine = lines[0];\n if (firstLine === undefined) return {};\n const lastLine = lines[lines.length - 1]!;\n const pitches = lines.slice(1).map((line, index) => lines[index]!.y - line.y);\n const geometry: BlockGeometry = {\n firstLeft: firstLine.left,\n firstY: firstLine.y,\n lastY: lastLine.y,\n ...(pitches.length > 0 ? { pitch: maxOf(pitches, (pitch) => pitch) } : {}),\n };\n const leadText = firstLine.lead?.text.trim();\n if (\n firstLine.lead === undefined ||\n leadText === undefined ||\n !BULLET_LEAD_CHARS.has(leadText) ||\n !firstLine.text.trimStart().startsWith(leadText)\n )\n return { geometry };\n const textAfterLead = lines\n .map((line) => line.text)\n .join(\" \")\n .trimStart()\n .slice(leadText.length);\n return {\n geometry,\n bullet: {\n markerLeft: firstLine.left,\n textLeft: firstLine.lead.nextLeft,\n continuationLefts: lines.slice(1).map((line) => line.left),\n secondBullet: ANY_BULLET_LEAD.test(textAfterLead),\n },\n };\n}\n\nexport interface BulletRun {\n /** First and last item, inclusive. */\n start: number;\n end: number;\n /** The index of the unmarked block that goes on with the last item, when there is one. */\n tail?: number;\n}\n\nconst isNear = (a: number, b: number): boolean => Math.abs(a - b) <= BULLET_RUN_MAX_DRIFT_PT;\n\n/** The simple bulleted runs among consecutive blocks: see the rule above. */\nexport function bulletRuns(candidates: readonly ListCandidate[]): BulletRun[] {\n const runs: BulletRun[] = [];\n let index = 0;\n while (index < candidates.length) {\n if (candidates[index]!.bullet === undefined) {\n index++;\n continue;\n }\n let end = index;\n while (candidates[end + 1]?.bullet !== undefined) end++;\n const run = checkBulletRun(candidates, index, end);\n if (run !== undefined) runs.push(run);\n index = end + 1;\n }\n return runs;\n}\n\n/** The largest value of a list, or `undefined` for an empty one. */\nconst largestOf = (values: readonly number[]): number | undefined =>\n values.length > 0 ? maxOf(values, (value) => value) : undefined;\n\n/** Are the items' markers at one x, their texts at one x right of the marker, every wrapped line at the text's x, and\n * no second bullet inside an item? */\nconst isSimpleBulletRun = (items: readonly BulletLead[], markerLeft: number, textLeft: number): boolean =>\n textLeft - markerLeft > BULLET_RUN_MAX_DRIFT_PT &&\n items.every(\n (item) =>\n isNear(item.markerLeft, markerLeft) &&\n isNear(item.textLeft, textLeft) &&\n !item.secondBullet &&\n item.continuationLefts.every((left) => isNear(left, textLeft)),\n );\n\n/** The bulleted run from `start` to `end` with its tail, or `undefined` when the run is not simple. */\nconst checkBulletRun = (candidates: readonly ListCandidate[], start: number, end: number): BulletRun | undefined => {\n if (end - start + 1 < MIN_ITEMS) return undefined;\n const items = candidates.slice(start, end + 1).map((candidate) => candidate.bullet!);\n const { markerLeft, textLeft } = items[0]!;\n if (!isSimpleBulletRun(items, markerLeft, textLeft)) return undefined;\n\n const nextCandidate = candidates[end + 1];\n if (\n nextCandidate?.geometry === undefined ||\n nextCandidate.marker !== undefined ||\n nextCandidate.bullet !== undefined ||\n !isNear(nextCandidate.geometry.firstLeft, textLeft)\n )\n return { start, end };\n const pitches = candidates.slice(start, end + 1).flatMap((candidate) => candidate.geometry?.pitch ?? []);\n // ITEMS WITHOUT A WRAPPED LINE STILL HAVE A LINE SPACING: the pitch between two consecutive one-line items\n // (five one-line questions followed by a block at the text's x must stay a list).\n const itemPitches = candidates.slice(start, end).flatMap((candidate, index) => {\n const below = candidates[start + index + 1]!.geometry;\n const itemGeometry = candidate.geometry;\n return itemGeometry === undefined || below === undefined\n ? []\n : [itemGeometry.lastY - below.firstY].filter((distance) => distance > 0);\n });\n const spacing = largestOf(pitches) ?? largestOf(itemPitches);\n if (spacing === undefined) return undefined;\n const gap = candidates[end]!.geometry!.lastY - nextCandidate.geometry.firstY;\n // The tail lies BELOW the last item: a block read after a jump up the page (another column) is never one.\n return gap > 0 && gap <= spacing + BULLET_TAIL_MAX_GAP_SLACK_PT ? { start, end, tail: end + 1 } : { start, end };\n};\n\n/**\n * HOW FAR A BLOCK MAY SIT FROM AN ITEM'S TEXT AND STILL BE ALIGNED ON IT. Starting value to calibrate: 1 pt, the\n * coordinate-noise tolerance. Measured on French and English PDFs:\n * - aligned: an item's text start read twice (after its marker, on its second line) agrees to 0.05 pt on 53 of 64\n * items; the one unnumbered block that belongs to an item (the last line of an item split off) is 0.0 pt from its\n * item's text;\n * - not aligned: the nearest disagreement is 1.3 pt, on a form, and the nearest block after an item that does not\n * continue it is 6.7 pt away.\n * Gap between the two populations: 0.05 to 1.3 pt.\n */\nconst ITEM_ALIGN_TOLERANCE_PT = SAME_LINE_PT;\n\n/**\n * WHERE AN ITEM'S TEXT STARTS, from two independent readings: where the text resumes after the marker on the first\n * line, and the left of the second line (a hanging indent). Both present, they must agree, or this abstains; one\n * present, it stands alone. Abstaining means no block can continue the item.\n */\nexport function itemTextLeft(readings: {\n afterMarker?: number | undefined;\n secondLine?: number | undefined;\n}): number | undefined {\n const { afterMarker, secondLine } = readings;\n if (afterMarker !== undefined && secondLine !== undefined)\n return Math.abs(afterMarker - secondLine) <= ITEM_ALIGN_TOLERANCE_PT ? afterMarker : undefined;\n return afterMarker ?? secondLine;\n}\n\n/** What an ordered run becomes: blocks left as paragraphs, and lists whose items\n * are block indices, a numbered block first. */\nexport type OrderedPiece = { kind: \"paragraph\"; index: number } | { kind: \"list\"; first: number; items: number[][] };\n\n/**\n * AN ORDERED RUN PUBLISHES THE DOCUMENT'S OWN NUMBERS.\n *\n * An ordered list counts its items, so an unnumbered block let in as an item shifts every number after it (\u00AB 1. \u00BB to\n * \u00AB 5. \u00BB published as 3 to 7). The left edge of a block includes its marker, and an unnumbered block (a letter or a\n * bullet has no number) is never an item of its own:\n * - aligned on the TEXT of the item before it (the number further left), it is that item's next paragraph;\n * - otherwise it closes the list; before the first number it stays a paragraph.\n * GUARD: a list is kept only when its numbers follow exactly (first, first+1\u2026, no gap, no duplicate) over at least\n * `MIN_ITEMS` items. Otherwise every block stays a paragraph, its written number in its text. The PDF libraries\n * studied keep the written number; none checks the sequence.\n *\n * Set aside: letting in a NON-indented block aligned on the item's text. It would put a \u00AB b) \u00BB and a \u00AB c) \u00BB back into\n * their item, but the same geometry is a body paragraph after a list whose markers hang in the margin (three body\n * paragraphs 0.0 pt from the text of the bullet before them). Nothing tells the two apart, so only blocks already in\n * the run are candidates.\n */\nexport function orderedPieces(candidates: readonly ListCandidate[], start: number, end: number): OrderedPiece[] {\n const pieces: OrderedPiece[] = [];\n let items: number[][] = [];\n let numbers: number[] = [];\n let openingItem: ListCandidate | undefined;\n\n const closeList = (): void => {\n const isExactSequence = numbers.every((number, index) => number === numbers[0]! + index);\n if (items.length >= MIN_ITEMS && isExactSequence) pieces.push({ kind: \"list\", first: numbers[0]!, items });\n else for (const index of items.flat()) pieces.push({ kind: \"paragraph\", index });\n items = [];\n numbers = [];\n openingItem = undefined;\n };\n\n for (let index = start; index <= end; index++) {\n const candidate = candidates[index]!;\n const value = candidate.marker?.kind === \"ordered\" ? candidate.marker.value : undefined;\n if (value !== undefined) {\n items.push([index]);\n numbers.push(value);\n openingItem = candidate;\n } else if (openingItem !== undefined && continuesItem(openingItem, candidate)) {\n items[items.length - 1]!.push(index);\n } else {\n closeList();\n pieces.push({ kind: \"paragraph\", index });\n }\n }\n closeList();\n return pieces;\n}\n\n/** Whether `block` is the next paragraph of `item`: aligned on the item's text, which starts right of its marker. */\nconst continuesItem = (item: ListCandidate, block: ListCandidate): boolean =>\n item.left !== undefined &&\n item.textLeft !== undefined &&\n block.left !== undefined &&\n item.textLeft - item.left > ITEM_ALIGN_TOLERANCE_PT &&\n Math.abs(block.left - item.textLeft) <= ITEM_ALIGN_TOLERANCE_PT;\n", "/**\n * Decides where a passage the render lost goes back into the published page, as its own unit between the two adjacent\n * units that hold its source neighbours. It hands the caller the edit and the letters it puts back, or why it\n * abstains; applying the edit, re-checking the page and keeping or undoing the repair are the caller's.\n *\n * THE RULE. A lost passage is a run of consecutive source words neither reading of the conservation check found. Its\n * neighbours are the source words right before and right after it. It goes back only when:\n * - each neighbour is a word the page matched (not an alternate text, a list number or a re-spacing: those have no\n * single place in the page);\n * - the neighbour before is the last word of a paragraph or heading unit, the one after the first word of the next\n * unit, with nothing between the two;\n * - at the start or the end of the document, the one neighbour opens the page's first block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB: a loss inside a paragraph, a table cell or a list, or an\n * image between the two paragraphs. A paragraph cut in the wrong place reads as if nothing were wrong; a \u00AB N characters\n * are not published \u00BB notice does not.\n *\n * THE UNDO IS THE CALLER'S. This module hands back only what the re-check needs: for each passage placed, the edit\n * and the number of letters it puts back (`LostTextInsertion`); for each passage left out, why\n * (`LostTextAbstention`). A caller that wants an exact repair keeps it only when the lost letters drop by exactly the\n * letters handed back and nothing else of the page moves.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are read in content stream order. Measured on\n * 871 paragraphs cut from 45 renders: 426 put back with the page's letters exactly as before, 22 put back elsewhere,\n * where the content stream reads them; some of those read better than the render did, some worse (a second column read\n * line by line). Tried and not kept: also requiring the blocks on each side to follow the source's order. It caught 8\n * of the 22 and cost 17 exact repairs. Text back in the page is what search needs; a paragraph slightly out of place\n * is the lesser defect.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back: a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back, for the caller's accounting. */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Whether `later` sits strictly after `earlier` in the page's reading order (block, then word). */\nconst isAfterInPageOrder = (later: PageWordAt, earlier: PageWordAt): boolean =>\n later.block > earlier.block || (later.block === earlier.block && later.word > earlier.word);\n\n/** Where each lost passage goes, as an edit for the caller to apply, or why it goes nowhere.\n *\n * It reasons on the page's units (`PublishedPage.units`), never on markup. The reason of each abstention travels to the\n * caller, so that a reader of the result knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container`, the same\n * answer as for a page whose anchors sit where a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = wordCountByBlock.length - 1;\n const findUnitOfBlock = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const findAnchorUnit = (anchor: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const unitIndex = findUnitOfBlock(anchor.block);\n if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The loss must sit at the unit's edge: the anchor before is the unit's last word, the anchor after its first.\n const neighbourBlock = side === \"before\" ? anchor.block + 1 : anchor.block - 1;\n const isAtEdge = side === \"before\" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;\n if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return \"loss-inside-block\";\n return unitIndex;\n };\n\n /** The unit the passage goes after (`-1`: before the first unit), or why it goes nowhere. */\n const placePassage = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\" && !isAfterInPageOrder(after, before))\n return \"anchors-out-of-order\";\n const unitBefore = before === \"document-edge\" ? undefined : findAnchorUnit(before, \"before\");\n if (typeof unitBefore === \"string\") return unitBefore;\n const unitAfter = after === \"document-edge\" ? undefined : findAnchorUnit(after, \"after\");\n if (typeof unitAfter === \"string\") return unitAfter;\n // At the start of the document, the passage goes before the unit that opens the page's first block.\n if (unitBefore === undefined) {\n if (unitAfter === undefined || after === \"document-edge\" || after.block !== 0) return \"no-anchor\";\n return unitAfter - 1;\n }\n // At the end of the document, the passage goes after the unit that closes the page's last block.\n if (unitAfter === undefined) {\n if (before === \"document-edge\" || before.block !== lastBlock) return \"no-anchor\";\n return unitBefore;\n }\n if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return \"blocks-not-adjacent\";\n return unitBefore;\n };\n\n for (const passage of passages) {\n const placement = placePassage(passage);\n if (typeof placement === \"string\") {\n abstentions.push(placement);\n continue;\n }\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: placement, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey(word).length, 0),\n });\n }\n return { insertions, abstentions };\n}\n"],
5
+ "mappings": ";AAUA,SAAS,mBAAAA,kBAAiB,WAAW,kBAAkB,cAAAC,mBAAkB;;;ACQzE,SAAS,uBAAoG;AAY7G,IAAM,aAAa;AAEnB,IAAM,kBAAkB,CAAC,SACvB,CAAC,GAAG,KAAK,SAAS,UAAU,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,EAC7C,MAAM,MAAM,CAAC;AAAA,EACb,KAAK,gBAAgB,MAAM,CAAC,CAAC;AAAA,EAC7B,KAAK,MAAM,QAAQ,MAAM,CAAC,EAAE;AAC9B,EAAE;AAIJ,IAAM,aAAa,CAAC,eAAoD;AACtE,QAAM,QAAuB,CAAC;AAC9B,MAAI,UAAuB,CAAC;AAC5B,QAAM,YAAY,MAAY;AAC5B,QAAI,gBAAgB,QAAQ,IAAI,CAAC,cAAc,UAAU,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAG,OAAM,KAAK,OAAO;AACvG,cAAU,CAAC;AAAA,EACb;AACA,aAAW,aAAa,YAAY;AAClC,QAAI,SAAS,KAAK,UAAU,IAAI,EAAG,WAAU;AAAA,QACxC,SAAQ,KAAK,SAAS;AAAA,EAC7B;AACA,YAAU;AACV,SAAO;AACT;AAGA,IAAM,oBAAoB,CAAC,MAAc,SAAmC;AAC1E,QAAM,aAAa,CAAC,GAAG,IAAI;AAC3B,QAAM,UAAU,SAAS,SAAS,aAAa,CAAC,GAAG,UAAU,EAAE,QAAQ;AACvE,QAAM,OAAiB,CAAC;AACxB,aAAW,aAAa,SAAS;AAC/B,QAAI,gBAAgB,SAAS,EAAE,SAAS,EAAG;AAC3C,SAAK,KAAK,SAAS;AAAA,EACrB;AACA,UAAQ,SAAS,SAAS,OAAO,CAAC,GAAG,IAAI,EAAE,QAAQ,GAAG,KAAK,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ACjC,kBAAY,KAAK,SAAS;AAC1B;AAAA,IACF;AACA,eAAW,KAAK;AAAA,MACd,MAAM,EAAE,MAAM,qBAAqB,MAAM,WAAW,MAAM,QAAQ,YAAY,KAAK,GAAG,EAAE;AAAA,MACxF,SAAS,QAAQ,YAAY,OAAO,CAAC,aAAa,SAAS,cAAcA,iBAAgB,IAAI,EAAE,QAAQ,CAAC;AAAA,IAC1G,CAAC;AAAA,EACH;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;;;AJ/FA,SAAS,mBAAmB;AAG5B,SAAS,yBAAyB;",
6
+ "names": ["conservationKey", "wordKeysOf", "conservationKey", "noWorse", "conservationKey"]
7
7
  }
package/dist/light.min.js CHANGED
@@ -1 +1 @@
1
- import{conservationKey as ae,lostWords as fe,textConservation as pe,wordKeysOf as me}from"doc-ir";import{conservationKey as g}from"doc-ir";var A=/[\s\S]/gu,I=t=>[...t.matchAll(A)].map(e=>({text:e[0],key:g(e[0]),end:e.index+e[0].length})),R=t=>{let e=[],n=[],r=()=>{g(n.map(d=>d.text).join("")).length>0&&e.push(n),n=[]};for(let d of t)/^\s+$/u.test(d.text)?r():n.push(d);return r(),e},L=(t,e)=>{let n=[...t],r=e==="lead"?n:[...n].reverse(),d=[];for(let u of r){if(g(u).length>0)break;d.push(u)}return(e==="lead"?d:[...d].reverse()).join("")},k=t=>t.replaceAll("\u200B",""),W=(t,e)=>{let n=e.pageWords[0];if(e.kind!=="glued"||e.pageWords.length!==1||n===void 0||e.sourceWords.length<2)return;let r=t[n.block],d=r===void 0?void 0:I(r),u=d===void 0?void 0:R(d)[n.word];if(u===void 0)return;let o=e.sourceWords.map(g),a=g(u.map(s=>s.text).join(""));if(u.map(s=>s.key).join("")!==a||o.join("")!==a)return;let p=[],c=0,i=0;for(let s=0;s<o.length-1;s++){let l=i+o[s].length;for(;c<u.length&&i+u[c].key.length<=l&&i<l;)i+=u[c++].key.length;if(i!==l)return;let f=c;for(;f<u.length&&u[f].key.length===0;)f++;let m=u.slice(c,f),h=L(e.sourceWords[s],"trail");if(k(m.map(E=>E.text).join(""))!==h+L(e.sourceWords[s+1],"lead"))return;let x="",b=0;for(;x.length<h.length&&b<m.length;)x+=k(m[b++].text);if(x!==h)return;p.push(u[c+b-1].end),c+=b}return p};function v(t,e){let n=e.filter(o=>o.kind==="glued");if(n.length===0)return{edits:[],repaired:0};let r=new Set,d=[],u=0;for(let o of n){let a=o.pageWords[0]?.block,p=W(t.blocks,o);if(!(p===void 0||a===void 0||p.some(c=>r.has(`${a}:${c}`)))){for(let c of p)r.add(`${a}:${c}`),d.push({kind:"insert-space",block:a,atChar:c});u+=1}}return{edits:d,repaired:u}}var M=(t,e,n)=>e.lostLetters<=t.lostLetters&&(e.decision!=="lost"||t.decision==="lost")&&e.decision!=="abstain"&&e.gluedWords<=t.gluedWords-n&&e.unmatchedPageWords<=t.unmatchedPageWords&&e.respacings.filter(r=>r.kind==="split").length<=t.respacings.filter(r=>r.kind==="split").length;import{collapseBlanks as S}from"doc-ir/internal";var _="\u2022\u25AA\u25E6\u2023\xB7\u25CF\u2043",B=new RegExp(`^\\s*[${_}]\\s*`,"u"),N=/^\s*[-–—]\s+/u,O=/^\s*(\d{1,2})[.)]\s+/u,w=/^\s*[a-zA-Z][.)]\s+/u,C=/^\s*[IVXivx]{1,4}[.)]\s+/u;function y(t){let e=O.exec(t);if(e!==null)return{kind:"ordered",length:e[0].length,value:Number(e[1])};for(let[n,r]of[[B,"bullet"],[N,"bullet"],[C,"letter"],[w,"letter"]]){let d=n.exec(t);if(d!==null)return{kind:r,length:d[0].length}}}import{conservationKey as j}from"doc-ir";var P=3,U=/[.:;!?»"…)]$/u,V=t=>new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])","u").test(t),D=t=>j(t.split(/\s+/)[0]??"").length<=1,T=(t,e)=>S(e.map(n=>t.blocks[n]??"").join(" ")),Y=(t,e)=>{let n=[...t,...e];if(t.length===0||e.length===0||n.some(o=>o===null))return!1;let r=n;for(let o=1;o<r.length;o++)if(r[o].index!==r[o-1].index+1)return!1;let d=r[t.length-1],u=r[t.length];return Math.abs(d.lastSize-u.firstSize)<.01},K=(t,e)=>e.decision!=="abstain"&&(e.decision!=="lost"||t.decision==="lost")&&e.lostLetters<=t.lostLetters&&e.gluedWords<=t.gluedWords&&e.unmatchedPageWords<=t.unmatchedPageWords;function G(t,e){let n=t.units;if(n===void 0||e.decision==="abstain")return{edits:[],joined:0};let r=n.map(o=>o.blocks.flatMap(a=>e.sourceOfPageWords[a]??[])),d=o=>{let a=n[o],p=n[o+1];if(!a.joinable||!p.joinable||!a.adjacentToNext)return!1;let c=T(t,a.blocks),i=T(t,p.blocks);return c.length===0||U.test(c)||!V(i)||y(i)!==void 0||D(i)?!1:Y(r[o].slice(-P),r[o+1].slice(0,P))},u=[];for(let o=n.length-2;o>=0;o--)d(o)&&u.push({kind:"join-units",unit:o});return{edits:u,joined:u.length}}import{conservationKey as $,wordKeysOf as F}from"doc-ir";function H(t,e){let n=[],r=[];if(e.length===0)return{insertions:n,abstentions:r};let d=t.units,u=t.blocks.map(i=>F(i).length),o=u.length-1,a=i=>d?.findIndex(s=>s.blocks.includes(i))??-1,p=(i,s)=>{let l=a(i.block);if(l<0||d?.[l]?.paragraphOrHeading!==!0)return"anchor-in-container";let f=s==="before"?i.block+1:i.block-1;return!(s==="before"?i.word===(u[i.block]??0)-1:i.word===0)||a(f)===l?"loss-inside-block":l},c=i=>{let{before:s,after:l}=i;if(s==="unanchored"||l==="unanchored")return"anchor-unmatched";if(s==="document-edge"&&l==="document-edge")return"no-anchor";if(s!=="document-edge"&&l!=="document-edge"&&(l.block<s.block||l.block===s.block&&l.word<=s.word))return"anchors-out-of-order";let f=s==="document-edge"?void 0:p(s,"before");if(typeof f=="string")return f;let m=l==="document-edge"?void 0:p(l,"after");return typeof m=="string"?m:f===void 0?l!=="document-edge"&&l.block===0?m-1:"no-anchor":m===void 0?s!=="document-edge"&&s.block===o?f:"no-anchor":m===f+1&&d?.[f]?.adjacentToNext===!0?f:"blocks-not-adjacent"};for(let i of e){let s=c(i);typeof s=="string"?r.push(s):n.push({edit:{kind:"insert-unit-after",unit:s,text:i.sourceWords.join(" ")},letters:i.sourceWords.reduce((l,f)=>l+$(f).length,0)})}return{insertions:n,abstentions:r}}import{ReaderError as Le}from"doc-ir";import{MAX_PAYLOAD_BYTES as ye}from"doc-ir";export{ye as MAX_PAYLOAD_BYTES,Le as ReaderError,ae as conservationKey,G as cutParagraphEdits,v as gluedWordEdits,K as joinNoWorse,fe as lostWords,M as noWorse,H as placeLostPassages,pe as textConservation,me as wordKeysOf};
1
+ import{conservationKey as me,lostWords as ge,textConservation as pe,wordKeysOf as be}from"doc-ir";import{conservationKey as p}from"doc-ir";var P=/[\s\S]/gu,T=n=>[...n.matchAll(P)].map(e=>({text:e[0],key:p(e[0]),end:e.index+e[0].length})),E=n=>{let e=[],t=[],o=()=>{p(t.map(r=>r.text).join("")).length>0&&e.push(t),t=[]};for(let r of n)/^\s+$/u.test(r.text)?o():t.push(r);return o(),e},b=(n,e)=>{let t=[...n],o=e==="lead"?t:[...t].reverse(),r=[];for(let d of o){if(p(d).length>0)break;r.push(d)}return(e==="lead"?r:[...r].reverse()).join("")},h=n=>n.replaceAll("\u200B",""),C=(n,e)=>{let t=e.pageWords[0];if(e.kind!=="glued"||e.pageWords.length!==1||t===void 0||e.sourceWords.length<2)return;let o=n[t.block];if(o!==void 0)return E(T(o))[t.word]},W=(n,e,t)=>{if(h(n.map(d=>d.text).join(""))!==e+t)return;let o="",r=0;for(;o.length<e.length&&r<n.length;)o+=h(n[r++].text);return o===e?r:void 0},A=(n,e)=>{let t=C(n,e);if(t===void 0)return;let o=e.sourceWords.map(p),r=p(t.map(c=>c.text).join(""));if(t.map(c=>c.key).join("")!==r||o.join("")!==r)return;let d=[],i=0,l=0;for(let c=0;c<o.length-1;c++){let f=l+o[c].length;for(;i<t.length&&l+t[i].key.length<=f&&l<f;)l+=t[i++].key.length;if(l!==f)return;let s=i;for(;s<t.length&&t[s].key.length===0;)s++;let u=W(t.slice(i,s),b(e.sourceWords[c],"trail"),b(e.sourceWords[c+1],"lead"));if(u===void 0)return;d.push(t[i+u-1].end),i+=u}return d};function R(n,e){let t=e.filter(i=>i.kind==="glued");if(t.length===0)return{edits:[],repaired:0};let o=new Set,r=[],d=0;for(let i of t){let l=i.pageWords[0]?.block,c=A(n.blocks,i);if(!(c===void 0||l===void 0||c.some(f=>o.has(`${l}:${f}`)))){for(let f of c)o.add(`${l}:${f}`),r.push({kind:"insert-space",block:l,atChar:f});d+=1}}return{edits:r,repaired:d}}var x=n=>n.respacings.filter(e=>e.kind==="split").length,I=(n,e,t)=>e.lostLetters<=n.lostLetters&&(e.decision!=="lost"||n.decision==="lost")&&e.decision!=="abstain"&&e.gluedWords<=n.gluedWords-t&&e.unmatchedPageWords<=n.unmatchedPageWords&&x(e)<=x(n);import{collapseBlanks as O}from"doc-ir/internal";var B="\u2022\u25AA\u25E6\u2023\xB7\u25CF\u2043",S=new RegExp(`^\\s*[${B}]\\s*`,"u"),_=/^\s*[-–—]\s+/u,N=/^\s*(\d{1,2})[.)]\s+/u,v=/^\s*[a-zA-Z][.)]\s+/u,M=/^\s*[IVXivx]{1,4}[.)]\s+/u;function L(n){let e=N.exec(n);if(e!==null)return{kind:"ordered",length:e[0].length,value:Number(e[1])};for(let[t,o]of[[S,"bullet"],[_,"bullet"],[M,"letter"],[v,"letter"]]){let r=t.exec(n);if(r!==null)return{kind:o,length:r[0].length}}}import{conservationKey as j}from"doc-ir";var k=3,w=/[.:;!?»"…)]$/u,U=n=>new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])","u").test(n),V=n=>j(n.split(/\s+/)[0]??"").length<=1,y=(n,e)=>O(e.map(t=>n.blocks[t]??"").join(" ")),D=n=>n!==null,K=(n,e)=>{if(n.length===0||e.length===0)return!1;let t=[...n,...e];if(!t.every(D))return!1;for(let d=1;d<t.length;d++)if(t[d].index!==t[d-1].index+1)return!1;let o=t[n.length-1],r=t[n.length];return Math.abs(o.lastSize-r.firstSize)<.01},Y=(n,e)=>n.length===0||w.test(n)||!U(e)||L(e)!==void 0?!1:!V(e),G=(n,e)=>e.decision!=="abstain"&&(e.decision!=="lost"||n.decision==="lost")&&e.lostLetters<=n.lostLetters&&e.gluedWords<=n.gluedWords&&e.unmatchedPageWords<=n.unmatchedPageWords;function $(n,e){let t=n.units;if(t===void 0||e.decision==="abstain")return{edits:[],joined:0};let o=t.map(i=>i.blocks.flatMap(l=>e.sourceOfPageWords[l]??[])),r=i=>{let l=t[i],c=t[i+1];if(!l.joinable||!c.joinable||!l.adjacentToNext)return!1;let f=y(n,l.blocks),s=y(n,c.blocks);return Y(f,s)?K(o[i].slice(-k),o[i+1].slice(0,k)):!1},d=[];for(let i=t.length-2;i>=0;i--)r(i)&&d.push({kind:"join-units",unit:i});return{edits:d,joined:d.length}}import{conservationKey as F,wordKeysOf as H}from"doc-ir";var X=(n,e)=>n.block>e.block||n.block===e.block&&n.word>e.word;function z(n,e){let t=[],o=[];if(e.length===0)return{insertions:t,abstentions:o};let r=n.units,d=n.blocks.map(s=>H(s).length),i=d.length-1,l=s=>r?.findIndex(u=>u.blocks.includes(s))??-1,c=(s,u)=>{let a=l(s.block);if(a<0||r?.[a]?.paragraphOrHeading!==!0)return"anchor-in-container";let m=u==="before"?s.block+1:s.block-1;return!(u==="before"?s.word===(d[s.block]??0)-1:s.word===0)||l(m)===a?"loss-inside-block":a},f=s=>{let{before:u,after:a}=s;if(u==="unanchored"||a==="unanchored")return"anchor-unmatched";if(u==="document-edge"&&a==="document-edge")return"no-anchor";if(u!=="document-edge"&&a!=="document-edge"&&!X(a,u))return"anchors-out-of-order";let m=u==="document-edge"?void 0:c(u,"before");if(typeof m=="string")return m;let g=a==="document-edge"?void 0:c(a,"after");return typeof g=="string"?g:m===void 0?g===void 0||a==="document-edge"||a.block!==0?"no-anchor":g-1:g===void 0?u==="document-edge"||u.block!==i?"no-anchor":m:g!==m+1||r?.[m]?.adjacentToNext!==!0?"blocks-not-adjacent":m};for(let s of e){let u=f(s);if(typeof u=="string"){o.push(u);continue}t.push({edit:{kind:"insert-unit-after",unit:u,text:s.sourceWords.join(" ")},letters:s.sourceWords.reduce((a,m)=>a+F(m).length,0)})}return{insertions:t,abstentions:o}}import{ReaderError as ye}from"doc-ir";import{MAX_PAYLOAD_BYTES as Te}from"doc-ir";export{Te as MAX_PAYLOAD_BYTES,ye as ReaderError,me as conservationKey,$ as cutParagraphEdits,R as gluedWordEdits,G as joinNoWorse,ge as lostWords,I as noWorse,z as placeLostPassages,pe as textConservation,be as wordKeysOf};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pdf-skryba",
3
- "version": "0.10.1",
3
+ "version": "0.10.2",
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",
@@ -54,7 +54,7 @@
54
54
  "test": "vitest run",
55
55
  "lint": "eslint --max-warnings 0 src scripts",
56
56
  "format:check": "prettier --check src scripts",
57
- "typecheck": "tsc --noEmit && node node_modules/typescript7/bin/tsc --noEmit",
57
+ "typecheck": "node node_modules/typescript/bin/tsc --noEmit && node node_modules/typescript7/bin/tsc --noEmit",
58
58
  "lint:pack": "publint run --strict && attw --pack . --profile esm-only",
59
59
  "prepack": "npm run build"
60
60
  },
@@ -86,7 +86,7 @@
86
86
  "tsx": "4.23.15",
87
87
  "typescript": "6.0.3",
88
88
  "typescript-eslint": "8.74.0",
89
- "typescript7": "npm:typescript@^7.0.2",
89
+ "typescript7": "npm:typescript@7.0.2",
90
90
  "vitest": "5.1.2"
91
91
  },
92
92
  "allowScripts": {