@embedpdf/engine-core 3.0.0-next.12 → 3.0.0-next.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/{AbortError-CRSooKsk.cjs → AbortError-Cq2igpZ6.cjs} +2 -2
  2. package/dist/{AbortError-CRSooKsk.cjs.map → AbortError-Cq2igpZ6.cjs.map} +1 -1
  3. package/dist/{AbortError-8-9JAX1Y.js → AbortError-DHqPBnYc.js} +2 -2
  4. package/dist/{AbortError-8-9JAX1Y.js.map → AbortError-DHqPBnYc.js.map} +1 -1
  5. package/dist/{AnnotationListSnapshot-x6tKulNV.d.cts → AnnotationListSnapshot-D3mFut1e.d.cts} +1155 -171
  6. package/dist/{AnnotationListSnapshot-x6tKulNV.d.ts → AnnotationListSnapshot-D3mFut1e.d.ts} +1155 -171
  7. package/dist/{DocumentSecurityService-CK0pejAK.d.cts → DocumentSecurityService-ClTZc0zO.d.cts} +2 -2
  8. package/dist/{DocumentSecurityService-9MawYxP-.d.ts → DocumentSecurityService-_JRjqvoI.d.ts} +2 -2
  9. package/dist/{Engine-Ds0ytbl6.d.ts → Engine-Bx0NOfmd.d.cts} +166 -11
  10. package/dist/{Engine--0XF0UAK.d.cts → Engine-DxtpCYcP.d.ts} +166 -11
  11. package/dist/{PageInsertBlankInput-CzShuSJI.cjs → PageInsertBlankInput-CqXBmFhN.cjs} +37 -2
  12. package/dist/PageInsertBlankInput-CqXBmFhN.cjs.map +1 -0
  13. package/dist/{PageInsertBlankInput-WKY0tr6S.js → PageInsertBlankInput-cHq9-i-z.js} +37 -2
  14. package/dist/PageInsertBlankInput-cHq9-i-z.js.map +1 -0
  15. package/dist/{builders-8Hl1AYNU.cjs → builders-Bqm8yTpi.cjs} +1470 -4
  16. package/dist/builders-Bqm8yTpi.cjs.map +1 -0
  17. package/dist/{builders-DOjcKDWQ.js → builders-Dqo2X-dt.js} +1351 -5
  18. package/dist/builders-Dqo2X-dt.js.map +1 -0
  19. package/dist/conformance.cjs +1079 -13
  20. package/dist/conformance.cjs.map +1 -1
  21. package/dist/conformance.d.cts +70 -3
  22. package/dist/conformance.d.ts +70 -3
  23. package/dist/conformance.js +1079 -14
  24. package/dist/conformance.js.map +1 -1
  25. package/dist/{fold-C7I5GpBz.cjs → fold-2V29cxCV.cjs} +2 -2
  26. package/dist/{fold-C7I5GpBz.cjs.map → fold-2V29cxCV.cjs.map} +1 -1
  27. package/dist/{fold-BfyxxwS6.js → fold-CdEJTBTn.js} +2 -2
  28. package/dist/{fold-BfyxxwS6.js.map → fold-CdEJTBTn.js.map} +1 -1
  29. package/dist/index.cjs +33 -4
  30. package/dist/index.d.cts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +5 -5
  33. package/dist/{resolver-D-jumvgM.cjs → resolver-CYVNV4hn.cjs} +216 -10
  34. package/dist/resolver-CYVNV4hn.cjs.map +1 -0
  35. package/dist/{resolver-CHG4waXL.js → resolver-inAVzsWt.js} +157 -11
  36. package/dist/resolver-inAVzsWt.js.map +1 -0
  37. package/dist/runtime.cjs +34 -5
  38. package/dist/runtime.d.cts +192 -5
  39. package/dist/runtime.d.ts +192 -5
  40. package/dist/runtime.js +6 -6
  41. package/dist/{schemas-DOyVEPk7.js → schemas-BLARNCgx.js} +420 -4
  42. package/dist/schemas-BLARNCgx.js.map +1 -0
  43. package/dist/{schemas-RChsAMWw.cjs → schemas-DIqFMmrC.cjs} +581 -3
  44. package/dist/schemas-DIqFMmrC.cjs.map +1 -0
  45. package/dist/wire.cjs +228 -12
  46. package/dist/wire.cjs.map +1 -1
  47. package/dist/wire.d.cts +415 -4
  48. package/dist/wire.d.ts +415 -4
  49. package/dist/wire.js +199 -13
  50. package/dist/wire.js.map +1 -1
  51. package/package.json +1 -1
  52. package/dist/PageInsertBlankInput-CzShuSJI.cjs.map +0 -1
  53. package/dist/PageInsertBlankInput-WKY0tr6S.js.map +0 -1
  54. package/dist/builders-8Hl1AYNU.cjs.map +0 -1
  55. package/dist/builders-DOjcKDWQ.js.map +0 -1
  56. package/dist/resolver-CHG4waXL.js.map +0 -1
  57. package/dist/resolver-D-jumvgM.cjs.map +0 -1
  58. package/dist/schemas-DOyVEPk7.js.map +0 -1
  59. package/dist/schemas-RChsAMWw.cjs.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embedpdf/engine-core",
3
- "version": "3.0.0-next.12",
3
+ "version": "3.0.0-next.13",
4
4
  "private": false,
5
5
  "description": "Engine v3 core: AbortablePromise, Engine/DocumentHandle interfaces, DTOs, wire schemas, error codes, and a transport-agnostic conformance harness shared by every Engine implementation.",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- {"version":3,"file":"PageInsertBlankInput-CzShuSJI.cjs","names":[],"sources":["../src/errors/EngineErrorCode.ts","../src/annotation/subtype.ts","../src/text/charmap.ts","../src/mutation/PageInsertBlankInput.ts"],"sourcesContent":["export const EngineErrorCode = {\n Unknown: 'Unknown',\n InvalidArg: 'InvalidArg',\n DocNotOpen: 'DocNotOpen',\n DocOpenFailed: 'DocOpenFailed',\n DocPasswordRequired: 'DocPasswordRequired',\n DocPasswordIncorrect: 'DocPasswordIncorrect',\n /**\n * A share-token exchange (`open({ kind: 'share' })`) needs the grant's\n * passphrase: none was supplied, or the supplied one was rejected —\n * indistinguishable by design, mirroring the server. Prompt and retry\n * with `sharePassword`. Distinct from `DocPasswordRequired`, which is\n * about the PDF's own encryption password.\n */\n SharePasswordRequired: 'SharePasswordRequired',\n Aborted: 'Aborted',\n Network: 'Network',\n Unauthenticated: 'Unauthenticated',\n Forbidden: 'Forbidden',\n NotFound: 'NotFound',\n WireFormat: 'WireFormat',\n RuntimeUnavailable: 'RuntimeUnavailable',\n /**\n * Annotation/page reference could not be resolved. Surfaced when:\n * - `AnnotationRef.kind === 'objectNumber'` but the document has no\n * annotation with that indirect object number on the addressed page\n * - `AnnotationRef.kind === 'nm'` but no annotation on the page has\n * that `/NM`\n * - `AnnotationRef.kind === 'index'` but the supplied `RevisionToken`\n * does not match the current per-page generation\n * - `AnnotationRef.kind === 'index'` but `index` is out of range for\n * the page's current annotation count\n */\n InvalidReference: 'InvalidReference',\n /**\n * A weak-annotation structural edit (delete/move) was attempted while the\n * caller does not have sole active edit presence for that page. This is a\n * collaboration guard for index-addressed annotations; stable pages and\n * non-shifting annotation updates do not use it.\n */\n WeakAnnotationSessionConflict: 'WeakAnnotationSessionConflict',\n /**\n * A layer write lost its optimistic-concurrency check: the layer's\n * durable version advanced (another writer — typically another server\n * replica — committed) between the operation's prepare and its commit,\n * and the server exhausted its rebase-and-retry budget. Retryable: the\n * operation was NOT applied; re-issue it against the new state.\n */\n LayerVersionConflict: 'LayerVersionConflict',\n /**\n * The requested operation is typed but not yet wired in this engine\n * version. The wire shape stays valid; clients can detect this with\n * `EngineError.is(err, EngineErrorCode.NotImplemented)` and degrade\n * gracefully.\n */\n NotImplemented: 'NotImplemented',\n /**\n * The PDF was loadable enough for PDFium to parse, but violates a\n * structural invariant the engine relies on. Surfaced for the rare\n * spec-violating PDF that ships a direct (non-indirect) page\n * dictionary in the /Pages tree — see `EPDFPage_GetObjectNumber`\n * returning `0`. PDFium creation paths (`FPDFPage_New`,\n * `EPDFPage_CreateAnnot`) always produce indirect objects, so this\n * error code is intentionally not used for engine-produced state;\n * it specifically signals \"this input file is broken in a way we\n * cannot work around without compromising stable identity\".\n *\n * Distinct from `DocOpenFailed` (PDFium refused to load the bytes\n * at all) and `NotFound` (a well-formed page/annotation/etc. simply\n * doesn't exist).\n */\n MalformedPdf: 'MalformedPdf',\n} as const;\n\nexport type EngineErrorCode = (typeof EngineErrorCode)[keyof typeof EngineErrorCode];\n","/**\n * Closed-world string catalog of annotation subtypes the v3 wire format knows\n * about. The TypeScript discriminated union `AnnotationDTO` is keyed on this\n * literal type. PDFium's integer subtype code is mapped onto these strings\n * by the reader registry.\n *\n * `unsupported` is the forward-compat fallback for any PDF subtype that\n * the engine has not implemented a reader for yet. Unknown subtypes never\n * silently disappear from the wire — they round-trip as\n * `{ subtype: 'unsupported', rawSubtypeCode }`.\n */\nexport const ANNOTATION_SUBTYPES = [\n 'text',\n 'link',\n 'free-text',\n 'line',\n 'square',\n 'circle',\n 'polygon',\n 'polyline',\n 'highlight',\n 'underline',\n 'squiggly',\n 'strikeout',\n 'stamp',\n 'caret',\n 'ink',\n 'popup',\n 'file-attachment',\n 'redact',\n 'widget',\n 'unsupported',\n] as const;\n\nexport type AnnotationSubtype = (typeof ANNOTATION_SUBTYPES)[number];\n\n/**\n * PDFium subtype codes from `FPDFAnnot_GetSubtype`. Mirrors\n * `FPDF_ANNOTATION_SUBTYPE` in `public/fpdf_annot.h`. We keep this here\n * (rather than importing from @embedpdf/engine-runtime) so the engine-core\n * package has zero PDFium dependency.\n */\nexport const PdfAnnotationSubtypeCode = {\n UNKNOWN: 0,\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n RICHMEDIA: 26,\n XFAWIDGET: 27,\n REDACT: 28,\n} as const;\n\nexport type PdfAnnotationSubtypeCode =\n (typeof PdfAnnotationSubtypeCode)[keyof typeof PdfAnnotationSubtypeCode];\n\n/**\n * Map from PDFium codes to wire-stable string subtypes. Codes the engine\n * recognises as a v3 subtype (or maps to 'unsupported' if not yet wired).\n */\nexport const PDF_CODE_TO_SUBTYPE: Readonly<Record<number, AnnotationSubtype>> = Object.freeze({\n [PdfAnnotationSubtypeCode.TEXT]: 'text',\n [PdfAnnotationSubtypeCode.LINK]: 'link',\n [PdfAnnotationSubtypeCode.FREETEXT]: 'free-text',\n [PdfAnnotationSubtypeCode.LINE]: 'line',\n [PdfAnnotationSubtypeCode.SQUARE]: 'square',\n [PdfAnnotationSubtypeCode.CIRCLE]: 'circle',\n [PdfAnnotationSubtypeCode.POLYGON]: 'polygon',\n [PdfAnnotationSubtypeCode.POLYLINE]: 'polyline',\n [PdfAnnotationSubtypeCode.HIGHLIGHT]: 'highlight',\n [PdfAnnotationSubtypeCode.UNDERLINE]: 'underline',\n [PdfAnnotationSubtypeCode.SQUIGGLY]: 'squiggly',\n [PdfAnnotationSubtypeCode.STRIKEOUT]: 'strikeout',\n [PdfAnnotationSubtypeCode.STAMP]: 'stamp',\n [PdfAnnotationSubtypeCode.CARET]: 'caret',\n [PdfAnnotationSubtypeCode.INK]: 'ink',\n [PdfAnnotationSubtypeCode.POPUP]: 'popup',\n [PdfAnnotationSubtypeCode.FILEATTACHMENT]: 'file-attachment',\n [PdfAnnotationSubtypeCode.WIDGET]: 'widget',\n [PdfAnnotationSubtypeCode.REDACT]: 'redact',\n});\n\n/**\n * Reverse map for write paths that need to turn a wire subtype back into the\n * PDFium integer code without importing the zod-backed annotation registry.\n */\nexport const PDF_SUBTYPE_TO_CODE: Readonly<Record<AnnotationSubtype, PdfAnnotationSubtypeCode>> =\n Object.freeze({\n text: PdfAnnotationSubtypeCode.TEXT,\n link: PdfAnnotationSubtypeCode.LINK,\n 'free-text': PdfAnnotationSubtypeCode.FREETEXT,\n line: PdfAnnotationSubtypeCode.LINE,\n square: PdfAnnotationSubtypeCode.SQUARE,\n circle: PdfAnnotationSubtypeCode.CIRCLE,\n polygon: PdfAnnotationSubtypeCode.POLYGON,\n polyline: PdfAnnotationSubtypeCode.POLYLINE,\n highlight: PdfAnnotationSubtypeCode.HIGHLIGHT,\n underline: PdfAnnotationSubtypeCode.UNDERLINE,\n squiggly: PdfAnnotationSubtypeCode.SQUIGGLY,\n strikeout: PdfAnnotationSubtypeCode.STRIKEOUT,\n stamp: PdfAnnotationSubtypeCode.STAMP,\n caret: PdfAnnotationSubtypeCode.CARET,\n ink: PdfAnnotationSubtypeCode.INK,\n popup: PdfAnnotationSubtypeCode.POPUP,\n 'file-attachment': PdfAnnotationSubtypeCode.FILEATTACHMENT,\n redact: PdfAnnotationSubtypeCode.REDACT,\n widget: PdfAnnotationSubtypeCode.WIDGET,\n unsupported: PdfAnnotationSubtypeCode.UNKNOWN,\n });\n\nexport function subtypeFromCode(code: number): AnnotationSubtype {\n return PDF_CODE_TO_SUBTYPE[code] ?? 'unsupported';\n}\n","import type { PageTextSnapshot } from '../dto/PageTextSnapshot';\n\n/**\n * Character↔text index translation — the ONE place the two text index\n * spaces of a page meet.\n *\n * A page has two index spaces:\n *\n * - CHARACTER space: PDFium's internal character list, the space geometry\n * runs tile (`PageGeometryRun.charStart`), hit-testing addresses, and\n * selection ranges live in. Size: `PageTextSnapshot.charCount`.\n * - TEXT space: UTF-16 code-unit offsets into the extracted string\n * `PageTextSnapshot.text` — what search matching and slicing operate on.\n *\n * They diverge in exactly two ways, both encoded by `charMap` anchors:\n * - a non-printing character occupies a character slot but contributes\n * ZERO text units (PDFium's `char_indices_` skip list);\n * - a supplementary-plane character contributes TWO text units (a\n * surrogate pair) once extraction is UTF-16-faithful.\n *\n * `charMap` semantics (see {@link CharMapAnchor}): an implicit head anchor\n * `[0, 0]`; between anchors every character advances the text by exactly one\n * unit; an anchor sits at `i + 1` whenever character `i` contributed\n * something other than one unit. Absent/empty map = identity\n * (`charCount === text.length`). `charMapViolation` is the validator both\n * the wire schema and engine builders share — malformed maps are rejected,\n * never silently repaired.\n *\n * Boundary model: a \"character boundary\" `c` ∈ [0, charCount] sits BEFORE\n * character `c`; `boundaryTextOffset(s, charCount) === text.length` always.\n * All ranges are half-open in both spaces.\n */\n\n/**\n * One anchor of the character→text mapping: from character index `char`\n * onward (until the next anchor), boundary `c` maps to text offset\n * `text + (c - char)`.\n */\nexport type CharMapAnchor = readonly [char: number, text: number];\n\n/** Direction to resolve a text offset that falls on a zero-width plateau —\n * see {@link charBoundaryAtTextOffset}. */\nexport type CharBoundaryBias = 'start' | 'end';\n\nconst clampInt = (value: number, lo: number, hi: number): number =>\n Math.min(Math.max(Math.floor(value), lo), hi);\n\n/** The greatest anchor with `anchor.char <= boundary` (implicit head [0,0]). */\nfunction anchorAtOrBefore(map: ReadonlyArray<CharMapAnchor>, boundary: number): CharMapAnchor {\n let lo = 0;\n let hi = map.length - 1;\n let best: CharMapAnchor | null = null;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n if (map[mid][0] <= boundary) {\n best = map[mid];\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return best ?? [0, 0];\n}\n\n/**\n * Text offset of character boundary `boundary` (clamped into\n * [0, charCount]). For a dropped character this is the offset of the next\n * real text unit — exactly what half-open slicing needs at either end.\n */\nexport function boundaryTextOffset(snapshot: PageTextSnapshot, boundary: number): number {\n const b = clampInt(boundary, 0, snapshot.charCount);\n const map = snapshot.charMap;\n if (!map || map.length === 0) return Math.min(b, snapshot.text.length);\n const [char, text] = anchorAtOrBefore(map, b);\n return text + (b - char);\n}\n\n/**\n * The character boundary for a text offset, with explicit plateau bias:\n *\n * - `'start'`: the GREATEST boundary whose text offset is <= `offset` —\n * scans forward past zero-width characters, so a range start never\n * includes a dropped character that precedes its first real unit.\n * - `'end'`: the SMALLEST boundary whose text offset is >= `offset` —\n * stops before zero-width characters, so a range end never swallows a\n * dropped character that follows its last real unit.\n *\n * An offset inside a surrogate pair resolves outward under both biases\n * (start → the pair's character, end → past it), so a clipped astral\n * character is always covered whole. Prefer {@link charRangeForTextOffsets}\n * — the two biases exist to be used as a PAIR.\n */\nexport function charBoundaryAtTextOffset(\n snapshot: PageTextSnapshot,\n offset: number,\n bias: CharBoundaryBias,\n): number {\n const target = clampInt(offset, 0, snapshot.text.length);\n let lo = 0;\n let hi = snapshot.charCount;\n if (bias === 'start') {\n // Greatest boundary with B(boundary) <= target. B(0) = 0 <= target always.\n while (lo < hi) {\n const mid = lo + Math.ceil((hi - lo) / 2);\n if (boundaryTextOffset(snapshot, mid) <= target) lo = mid;\n else hi = mid - 1;\n }\n return lo;\n }\n // Smallest boundary with B(boundary) >= target. B(charCount) = text.length\n // >= target always (offset is clamped).\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (boundaryTextOffset(snapshot, mid) >= target) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n}\n\n/**\n * The character range whose text projection is exactly\n * `text.slice(startOffset, endOffset)` — THE inverse used by search-hit\n * conversion and select-by-text. Start is right-biased and end left-biased\n * (see {@link charBoundaryAtTextOffset}), so zero-width characters adjacent\n * to the range fall OUTSIDE it on both sides.\n *\n * A non-empty text range can never invert: `end > start` implies\n * `B(end) >= endOffset > startOffset >= B(start)`, which forces\n * `end > start` by monotonicity. Empty input (`endOffset <= startOffset`)\n * normalizes to the end-rule boundary of `startOffset` on both sides.\n */\nexport function charRangeForTextOffsets(\n snapshot: PageTextSnapshot,\n startOffset: number,\n endOffset: number,\n): { start: number; end: number } {\n if (endOffset <= startOffset) {\n const b = charBoundaryAtTextOffset(snapshot, startOffset, 'end');\n return { start: b, end: b };\n }\n return {\n start: charBoundaryAtTextOffset(snapshot, startOffset, 'start'),\n end: charBoundaryAtTextOffset(snapshot, endOffset, 'end'),\n };\n}\n\n/**\n * THE copy primitive: the text projection of the half-open character range\n * `[charStart, charEnd)`. Dropped characters inside the range contribute\n * nothing; a supplementary character contributes its full surrogate pair.\n * `sliceTextByChars(s, 0, s.charCount) === s.text` always.\n */\nexport function sliceTextByChars(\n snapshot: PageTextSnapshot,\n charStart: number,\n charEnd: number,\n): string {\n if (charEnd <= charStart) return '';\n return snapshot.text.slice(\n boundaryTextOffset(snapshot, charStart),\n boundaryTextOffset(snapshot, charEnd),\n );\n}\n\n/**\n * First invariant violation of a snapshot's char map, or null when valid.\n * Shared by the wire schema (rejects malformed bodies) and engine builders\n * (dev-mode assertion). The invariants:\n *\n * 1. absent/empty map ⇒ identity, so `charCount === text.length`;\n * 2. anchor chars strictly increasing, each in [1, charCount];\n * 3. step rule: against the previous anchor (implicit head [0, 0]), the\n * character just before each anchor contributed exactly 0 units\n * (dropped) or 2 (surrogate pair):\n * `t₂ - (t₁ + (c₂ - c₁ - 1)) ∈ {0, 2}`;\n * 4. tail: `lastText + (charCount - lastChar) === text.length`\n * (equivalently `boundaryTextOffset(s, charCount) === text.length`).\n */\nexport function charMapViolation(\n charCount: number,\n textLength: number,\n charMap: ReadonlyArray<CharMapAnchor> | undefined,\n): string | null {\n if (!charMap || charMap.length === 0) {\n return charCount === textLength\n ? null\n : `identity map requires charCount (${charCount}) === text length (${textLength})`;\n }\n let prevChar = 0;\n let prevText = 0;\n for (let i = 0; i < charMap.length; i++) {\n const [char, text] = charMap[i];\n if (!Number.isInteger(char) || !Number.isInteger(text)) {\n return `anchor ${i} is not integer-valued`;\n }\n if (char <= prevChar) {\n return `anchor ${i} char ${char} not strictly after ${prevChar}`;\n }\n if (char > charCount) {\n return `anchor ${i} char ${char} outside [1, ${charCount}]`;\n }\n const step = text - (prevText + (char - prevChar - 1));\n if (step !== 0 && step !== 2) {\n return `anchor ${i} implies a character contributing ${step} text units (expected 0 or 2)`;\n }\n prevChar = char;\n prevText = text;\n }\n const tail = prevText + (charCount - prevChar);\n if (tail !== textLength) {\n return `map projects charCount to ${tail}, but text length is ${textLength}`;\n }\n return null;\n}\n","import type { PdfSize } from '../geometry/primitives';\n\n/**\n * Upper bound on `count` for a single `pages.insertBlank()` call. A CONTRACT\n * cap, enforced identically by every engine (the cloud input schema carries\n * the same number), so a UI never discovers a lower server limit by surprise.\n * Larger batches are a loop at the call site.\n */\nexport const PAGE_INSERT_BLANK_MAX_COUNT = 100;\n\n/**\n * Spec for `pages.insertBlank()`: create `count` blank pages of `size`.\n *\n * `size` is explicit and in PDF points, un-rotated — the same convention as\n * `PageLayout.size`. The \"match my neighbour\" default developers expect is a\n * registry read, so it lives in the page-edit capability, not here: the\n * engine wire never guesses (the `rotateBy` law).\n */\nexport interface PageInsertBlankSpec {\n /** Page size in PDF points. Both dimensions must be finite and > 0. */\n size: PdfSize;\n /** Pages to create, in `[1, PAGE_INSERT_BLANK_MAX_COUNT]`. Default 1. */\n count?: number;\n}\n"],"mappings":";AAAA,MAAa,kBAAkB;CAC7B,SAAS;CACT,YAAY;CACZ,YAAY;CACZ,eAAe;CACf,qBAAqB;CACrB,sBAAsB;;;;;;;;CAQtB,uBAAuB;CACvB,SAAS;CACT,SAAS;CACT,iBAAiB;CACjB,WAAW;CACX,UAAU;CACV,YAAY;CACZ,oBAAoB;;;;;;;;;;;;CAYpB,kBAAkB;;;;;;;CAOlB,+BAA+B;;;;;;;;CAQ/B,sBAAsB;;;;;;;CAOtB,gBAAgB;;;;;;;;;;;;;;;;CAgBhB,cAAc;AAChB;;;;;;;;;;;;;;AC7DA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAUA,MAAa,2BAA2B;CACtC,SAAS;CACT,MAAM;CACN,MAAM;CACN,UAAU;CACV,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,UAAU;CACV,WAAW;CACX,WAAW;CACX,UAAU;CACV,WAAW;CACX,OAAO;CACP,OAAO;CACP,KAAK;CACL,OAAO;CACP,gBAAgB;CAChB,OAAO;CACP,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,aAAa;CACb,SAAS;CACT,WAAW;CACX,QAAQ;CACR,WAAW;CACX,WAAW;CACX,QAAQ;AACV;;;;;AASA,MAAa,sBAAmE,OAAO,OAAO;EAC3F,yBAAyB,OAAO;EAChC,yBAAyB,OAAO;EAChC,yBAAyB,WAAW;EACpC,yBAAyB,OAAO;EAChC,yBAAyB,SAAS;EAClC,yBAAyB,SAAS;EAClC,yBAAyB,UAAU;EACnC,yBAAyB,WAAW;EACpC,yBAAyB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ACjC,OAAO,cAAc,aACjB,OACA,oCAAoC,UAAU,qBAAqB,WAAW;CAEpF,IAAI,WAAW;CACf,IAAI,WAAW;CACf,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,CAAC,MAAM,QAAQ,QAAQ;EAC7B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,CAAC,OAAO,UAAU,IAAI,GACnD,OAAO,UAAU,EAAE;EAErB,IAAI,QAAQ,UACV,OAAO,UAAU,EAAE,QAAQ,KAAK,sBAAsB;EAExD,IAAI,OAAO,WACT,OAAO,UAAU,EAAE,QAAQ,KAAK,eAAe,UAAU;EAE3D,MAAM,OAAO,QAAQ,YAAY,OAAO,WAAW;EACnD,IAAI,SAAS,KAAK,SAAS,GACzB,OAAO,UAAU,EAAE,oCAAoC,KAAK;EAE9D,WAAW;EACX,WAAW;CACb;CACA,MAAM,OAAO,YAAY,YAAY;CACrC,IAAI,SAAS,YACX,OAAO,6BAA6B,KAAK,uBAAuB;CAElE,OAAO;AACT;;;;;;;;;AC7MA,MAAa,8BAA8B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"PageInsertBlankInput-WKY0tr6S.js","names":[],"sources":["../src/errors/EngineErrorCode.ts","../src/annotation/subtype.ts","../src/text/charmap.ts","../src/mutation/PageInsertBlankInput.ts"],"sourcesContent":["export const EngineErrorCode = {\n Unknown: 'Unknown',\n InvalidArg: 'InvalidArg',\n DocNotOpen: 'DocNotOpen',\n DocOpenFailed: 'DocOpenFailed',\n DocPasswordRequired: 'DocPasswordRequired',\n DocPasswordIncorrect: 'DocPasswordIncorrect',\n /**\n * A share-token exchange (`open({ kind: 'share' })`) needs the grant's\n * passphrase: none was supplied, or the supplied one was rejected —\n * indistinguishable by design, mirroring the server. Prompt and retry\n * with `sharePassword`. Distinct from `DocPasswordRequired`, which is\n * about the PDF's own encryption password.\n */\n SharePasswordRequired: 'SharePasswordRequired',\n Aborted: 'Aborted',\n Network: 'Network',\n Unauthenticated: 'Unauthenticated',\n Forbidden: 'Forbidden',\n NotFound: 'NotFound',\n WireFormat: 'WireFormat',\n RuntimeUnavailable: 'RuntimeUnavailable',\n /**\n * Annotation/page reference could not be resolved. Surfaced when:\n * - `AnnotationRef.kind === 'objectNumber'` but the document has no\n * annotation with that indirect object number on the addressed page\n * - `AnnotationRef.kind === 'nm'` but no annotation on the page has\n * that `/NM`\n * - `AnnotationRef.kind === 'index'` but the supplied `RevisionToken`\n * does not match the current per-page generation\n * - `AnnotationRef.kind === 'index'` but `index` is out of range for\n * the page's current annotation count\n */\n InvalidReference: 'InvalidReference',\n /**\n * A weak-annotation structural edit (delete/move) was attempted while the\n * caller does not have sole active edit presence for that page. This is a\n * collaboration guard for index-addressed annotations; stable pages and\n * non-shifting annotation updates do not use it.\n */\n WeakAnnotationSessionConflict: 'WeakAnnotationSessionConflict',\n /**\n * A layer write lost its optimistic-concurrency check: the layer's\n * durable version advanced (another writer — typically another server\n * replica — committed) between the operation's prepare and its commit,\n * and the server exhausted its rebase-and-retry budget. Retryable: the\n * operation was NOT applied; re-issue it against the new state.\n */\n LayerVersionConflict: 'LayerVersionConflict',\n /**\n * The requested operation is typed but not yet wired in this engine\n * version. The wire shape stays valid; clients can detect this with\n * `EngineError.is(err, EngineErrorCode.NotImplemented)` and degrade\n * gracefully.\n */\n NotImplemented: 'NotImplemented',\n /**\n * The PDF was loadable enough for PDFium to parse, but violates a\n * structural invariant the engine relies on. Surfaced for the rare\n * spec-violating PDF that ships a direct (non-indirect) page\n * dictionary in the /Pages tree — see `EPDFPage_GetObjectNumber`\n * returning `0`. PDFium creation paths (`FPDFPage_New`,\n * `EPDFPage_CreateAnnot`) always produce indirect objects, so this\n * error code is intentionally not used for engine-produced state;\n * it specifically signals \"this input file is broken in a way we\n * cannot work around without compromising stable identity\".\n *\n * Distinct from `DocOpenFailed` (PDFium refused to load the bytes\n * at all) and `NotFound` (a well-formed page/annotation/etc. simply\n * doesn't exist).\n */\n MalformedPdf: 'MalformedPdf',\n} as const;\n\nexport type EngineErrorCode = (typeof EngineErrorCode)[keyof typeof EngineErrorCode];\n","/**\n * Closed-world string catalog of annotation subtypes the v3 wire format knows\n * about. The TypeScript discriminated union `AnnotationDTO` is keyed on this\n * literal type. PDFium's integer subtype code is mapped onto these strings\n * by the reader registry.\n *\n * `unsupported` is the forward-compat fallback for any PDF subtype that\n * the engine has not implemented a reader for yet. Unknown subtypes never\n * silently disappear from the wire — they round-trip as\n * `{ subtype: 'unsupported', rawSubtypeCode }`.\n */\nexport const ANNOTATION_SUBTYPES = [\n 'text',\n 'link',\n 'free-text',\n 'line',\n 'square',\n 'circle',\n 'polygon',\n 'polyline',\n 'highlight',\n 'underline',\n 'squiggly',\n 'strikeout',\n 'stamp',\n 'caret',\n 'ink',\n 'popup',\n 'file-attachment',\n 'redact',\n 'widget',\n 'unsupported',\n] as const;\n\nexport type AnnotationSubtype = (typeof ANNOTATION_SUBTYPES)[number];\n\n/**\n * PDFium subtype codes from `FPDFAnnot_GetSubtype`. Mirrors\n * `FPDF_ANNOTATION_SUBTYPE` in `public/fpdf_annot.h`. We keep this here\n * (rather than importing from @embedpdf/engine-runtime) so the engine-core\n * package has zero PDFium dependency.\n */\nexport const PdfAnnotationSubtypeCode = {\n UNKNOWN: 0,\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n RICHMEDIA: 26,\n XFAWIDGET: 27,\n REDACT: 28,\n} as const;\n\nexport type PdfAnnotationSubtypeCode =\n (typeof PdfAnnotationSubtypeCode)[keyof typeof PdfAnnotationSubtypeCode];\n\n/**\n * Map from PDFium codes to wire-stable string subtypes. Codes the engine\n * recognises as a v3 subtype (or maps to 'unsupported' if not yet wired).\n */\nexport const PDF_CODE_TO_SUBTYPE: Readonly<Record<number, AnnotationSubtype>> = Object.freeze({\n [PdfAnnotationSubtypeCode.TEXT]: 'text',\n [PdfAnnotationSubtypeCode.LINK]: 'link',\n [PdfAnnotationSubtypeCode.FREETEXT]: 'free-text',\n [PdfAnnotationSubtypeCode.LINE]: 'line',\n [PdfAnnotationSubtypeCode.SQUARE]: 'square',\n [PdfAnnotationSubtypeCode.CIRCLE]: 'circle',\n [PdfAnnotationSubtypeCode.POLYGON]: 'polygon',\n [PdfAnnotationSubtypeCode.POLYLINE]: 'polyline',\n [PdfAnnotationSubtypeCode.HIGHLIGHT]: 'highlight',\n [PdfAnnotationSubtypeCode.UNDERLINE]: 'underline',\n [PdfAnnotationSubtypeCode.SQUIGGLY]: 'squiggly',\n [PdfAnnotationSubtypeCode.STRIKEOUT]: 'strikeout',\n [PdfAnnotationSubtypeCode.STAMP]: 'stamp',\n [PdfAnnotationSubtypeCode.CARET]: 'caret',\n [PdfAnnotationSubtypeCode.INK]: 'ink',\n [PdfAnnotationSubtypeCode.POPUP]: 'popup',\n [PdfAnnotationSubtypeCode.FILEATTACHMENT]: 'file-attachment',\n [PdfAnnotationSubtypeCode.WIDGET]: 'widget',\n [PdfAnnotationSubtypeCode.REDACT]: 'redact',\n});\n\n/**\n * Reverse map for write paths that need to turn a wire subtype back into the\n * PDFium integer code without importing the zod-backed annotation registry.\n */\nexport const PDF_SUBTYPE_TO_CODE: Readonly<Record<AnnotationSubtype, PdfAnnotationSubtypeCode>> =\n Object.freeze({\n text: PdfAnnotationSubtypeCode.TEXT,\n link: PdfAnnotationSubtypeCode.LINK,\n 'free-text': PdfAnnotationSubtypeCode.FREETEXT,\n line: PdfAnnotationSubtypeCode.LINE,\n square: PdfAnnotationSubtypeCode.SQUARE,\n circle: PdfAnnotationSubtypeCode.CIRCLE,\n polygon: PdfAnnotationSubtypeCode.POLYGON,\n polyline: PdfAnnotationSubtypeCode.POLYLINE,\n highlight: PdfAnnotationSubtypeCode.HIGHLIGHT,\n underline: PdfAnnotationSubtypeCode.UNDERLINE,\n squiggly: PdfAnnotationSubtypeCode.SQUIGGLY,\n strikeout: PdfAnnotationSubtypeCode.STRIKEOUT,\n stamp: PdfAnnotationSubtypeCode.STAMP,\n caret: PdfAnnotationSubtypeCode.CARET,\n ink: PdfAnnotationSubtypeCode.INK,\n popup: PdfAnnotationSubtypeCode.POPUP,\n 'file-attachment': PdfAnnotationSubtypeCode.FILEATTACHMENT,\n redact: PdfAnnotationSubtypeCode.REDACT,\n widget: PdfAnnotationSubtypeCode.WIDGET,\n unsupported: PdfAnnotationSubtypeCode.UNKNOWN,\n });\n\nexport function subtypeFromCode(code: number): AnnotationSubtype {\n return PDF_CODE_TO_SUBTYPE[code] ?? 'unsupported';\n}\n","import type { PageTextSnapshot } from '../dto/PageTextSnapshot';\n\n/**\n * Character↔text index translation — the ONE place the two text index\n * spaces of a page meet.\n *\n * A page has two index spaces:\n *\n * - CHARACTER space: PDFium's internal character list, the space geometry\n * runs tile (`PageGeometryRun.charStart`), hit-testing addresses, and\n * selection ranges live in. Size: `PageTextSnapshot.charCount`.\n * - TEXT space: UTF-16 code-unit offsets into the extracted string\n * `PageTextSnapshot.text` — what search matching and slicing operate on.\n *\n * They diverge in exactly two ways, both encoded by `charMap` anchors:\n * - a non-printing character occupies a character slot but contributes\n * ZERO text units (PDFium's `char_indices_` skip list);\n * - a supplementary-plane character contributes TWO text units (a\n * surrogate pair) once extraction is UTF-16-faithful.\n *\n * `charMap` semantics (see {@link CharMapAnchor}): an implicit head anchor\n * `[0, 0]`; between anchors every character advances the text by exactly one\n * unit; an anchor sits at `i + 1` whenever character `i` contributed\n * something other than one unit. Absent/empty map = identity\n * (`charCount === text.length`). `charMapViolation` is the validator both\n * the wire schema and engine builders share — malformed maps are rejected,\n * never silently repaired.\n *\n * Boundary model: a \"character boundary\" `c` ∈ [0, charCount] sits BEFORE\n * character `c`; `boundaryTextOffset(s, charCount) === text.length` always.\n * All ranges are half-open in both spaces.\n */\n\n/**\n * One anchor of the character→text mapping: from character index `char`\n * onward (until the next anchor), boundary `c` maps to text offset\n * `text + (c - char)`.\n */\nexport type CharMapAnchor = readonly [char: number, text: number];\n\n/** Direction to resolve a text offset that falls on a zero-width plateau —\n * see {@link charBoundaryAtTextOffset}. */\nexport type CharBoundaryBias = 'start' | 'end';\n\nconst clampInt = (value: number, lo: number, hi: number): number =>\n Math.min(Math.max(Math.floor(value), lo), hi);\n\n/** The greatest anchor with `anchor.char <= boundary` (implicit head [0,0]). */\nfunction anchorAtOrBefore(map: ReadonlyArray<CharMapAnchor>, boundary: number): CharMapAnchor {\n let lo = 0;\n let hi = map.length - 1;\n let best: CharMapAnchor | null = null;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n if (map[mid][0] <= boundary) {\n best = map[mid];\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return best ?? [0, 0];\n}\n\n/**\n * Text offset of character boundary `boundary` (clamped into\n * [0, charCount]). For a dropped character this is the offset of the next\n * real text unit — exactly what half-open slicing needs at either end.\n */\nexport function boundaryTextOffset(snapshot: PageTextSnapshot, boundary: number): number {\n const b = clampInt(boundary, 0, snapshot.charCount);\n const map = snapshot.charMap;\n if (!map || map.length === 0) return Math.min(b, snapshot.text.length);\n const [char, text] = anchorAtOrBefore(map, b);\n return text + (b - char);\n}\n\n/**\n * The character boundary for a text offset, with explicit plateau bias:\n *\n * - `'start'`: the GREATEST boundary whose text offset is <= `offset` —\n * scans forward past zero-width characters, so a range start never\n * includes a dropped character that precedes its first real unit.\n * - `'end'`: the SMALLEST boundary whose text offset is >= `offset` —\n * stops before zero-width characters, so a range end never swallows a\n * dropped character that follows its last real unit.\n *\n * An offset inside a surrogate pair resolves outward under both biases\n * (start → the pair's character, end → past it), so a clipped astral\n * character is always covered whole. Prefer {@link charRangeForTextOffsets}\n * — the two biases exist to be used as a PAIR.\n */\nexport function charBoundaryAtTextOffset(\n snapshot: PageTextSnapshot,\n offset: number,\n bias: CharBoundaryBias,\n): number {\n const target = clampInt(offset, 0, snapshot.text.length);\n let lo = 0;\n let hi = snapshot.charCount;\n if (bias === 'start') {\n // Greatest boundary with B(boundary) <= target. B(0) = 0 <= target always.\n while (lo < hi) {\n const mid = lo + Math.ceil((hi - lo) / 2);\n if (boundaryTextOffset(snapshot, mid) <= target) lo = mid;\n else hi = mid - 1;\n }\n return lo;\n }\n // Smallest boundary with B(boundary) >= target. B(charCount) = text.length\n // >= target always (offset is clamped).\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (boundaryTextOffset(snapshot, mid) >= target) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n}\n\n/**\n * The character range whose text projection is exactly\n * `text.slice(startOffset, endOffset)` — THE inverse used by search-hit\n * conversion and select-by-text. Start is right-biased and end left-biased\n * (see {@link charBoundaryAtTextOffset}), so zero-width characters adjacent\n * to the range fall OUTSIDE it on both sides.\n *\n * A non-empty text range can never invert: `end > start` implies\n * `B(end) >= endOffset > startOffset >= B(start)`, which forces\n * `end > start` by monotonicity. Empty input (`endOffset <= startOffset`)\n * normalizes to the end-rule boundary of `startOffset` on both sides.\n */\nexport function charRangeForTextOffsets(\n snapshot: PageTextSnapshot,\n startOffset: number,\n endOffset: number,\n): { start: number; end: number } {\n if (endOffset <= startOffset) {\n const b = charBoundaryAtTextOffset(snapshot, startOffset, 'end');\n return { start: b, end: b };\n }\n return {\n start: charBoundaryAtTextOffset(snapshot, startOffset, 'start'),\n end: charBoundaryAtTextOffset(snapshot, endOffset, 'end'),\n };\n}\n\n/**\n * THE copy primitive: the text projection of the half-open character range\n * `[charStart, charEnd)`. Dropped characters inside the range contribute\n * nothing; a supplementary character contributes its full surrogate pair.\n * `sliceTextByChars(s, 0, s.charCount) === s.text` always.\n */\nexport function sliceTextByChars(\n snapshot: PageTextSnapshot,\n charStart: number,\n charEnd: number,\n): string {\n if (charEnd <= charStart) return '';\n return snapshot.text.slice(\n boundaryTextOffset(snapshot, charStart),\n boundaryTextOffset(snapshot, charEnd),\n );\n}\n\n/**\n * First invariant violation of a snapshot's char map, or null when valid.\n * Shared by the wire schema (rejects malformed bodies) and engine builders\n * (dev-mode assertion). The invariants:\n *\n * 1. absent/empty map ⇒ identity, so `charCount === text.length`;\n * 2. anchor chars strictly increasing, each in [1, charCount];\n * 3. step rule: against the previous anchor (implicit head [0, 0]), the\n * character just before each anchor contributed exactly 0 units\n * (dropped) or 2 (surrogate pair):\n * `t₂ - (t₁ + (c₂ - c₁ - 1)) ∈ {0, 2}`;\n * 4. tail: `lastText + (charCount - lastChar) === text.length`\n * (equivalently `boundaryTextOffset(s, charCount) === text.length`).\n */\nexport function charMapViolation(\n charCount: number,\n textLength: number,\n charMap: ReadonlyArray<CharMapAnchor> | undefined,\n): string | null {\n if (!charMap || charMap.length === 0) {\n return charCount === textLength\n ? null\n : `identity map requires charCount (${charCount}) === text length (${textLength})`;\n }\n let prevChar = 0;\n let prevText = 0;\n for (let i = 0; i < charMap.length; i++) {\n const [char, text] = charMap[i];\n if (!Number.isInteger(char) || !Number.isInteger(text)) {\n return `anchor ${i} is not integer-valued`;\n }\n if (char <= prevChar) {\n return `anchor ${i} char ${char} not strictly after ${prevChar}`;\n }\n if (char > charCount) {\n return `anchor ${i} char ${char} outside [1, ${charCount}]`;\n }\n const step = text - (prevText + (char - prevChar - 1));\n if (step !== 0 && step !== 2) {\n return `anchor ${i} implies a character contributing ${step} text units (expected 0 or 2)`;\n }\n prevChar = char;\n prevText = text;\n }\n const tail = prevText + (charCount - prevChar);\n if (tail !== textLength) {\n return `map projects charCount to ${tail}, but text length is ${textLength}`;\n }\n return null;\n}\n","import type { PdfSize } from '../geometry/primitives';\n\n/**\n * Upper bound on `count` for a single `pages.insertBlank()` call. A CONTRACT\n * cap, enforced identically by every engine (the cloud input schema carries\n * the same number), so a UI never discovers a lower server limit by surprise.\n * Larger batches are a loop at the call site.\n */\nexport const PAGE_INSERT_BLANK_MAX_COUNT = 100;\n\n/**\n * Spec for `pages.insertBlank()`: create `count` blank pages of `size`.\n *\n * `size` is explicit and in PDF points, un-rotated — the same convention as\n * `PageLayout.size`. The \"match my neighbour\" default developers expect is a\n * registry read, so it lives in the page-edit capability, not here: the\n * engine wire never guesses (the `rotateBy` law).\n */\nexport interface PageInsertBlankSpec {\n /** Page size in PDF points. Both dimensions must be finite and > 0. */\n size: PdfSize;\n /** Pages to create, in `[1, PAGE_INSERT_BLANK_MAX_COUNT]`. Default 1. */\n count?: number;\n}\n"],"mappings":";AAAA,MAAa,kBAAkB;CAC7B,SAAS;CACT,YAAY;CACZ,YAAY;CACZ,eAAe;CACf,qBAAqB;CACrB,sBAAsB;;;;;;;;CAQtB,uBAAuB;CACvB,SAAS;CACT,SAAS;CACT,iBAAiB;CACjB,WAAW;CACX,UAAU;CACV,YAAY;CACZ,oBAAoB;;;;;;;;;;;;CAYpB,kBAAkB;;;;;;;CAOlB,+BAA+B;;;;;;;;CAQ/B,sBAAsB;;;;;;;CAOtB,gBAAgB;;;;;;;;;;;;;;;;CAgBhB,cAAc;AAChB;;;;;;;;;;;;;;AC7DA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAUA,MAAa,2BAA2B;CACtC,SAAS;CACT,MAAM;CACN,MAAM;CACN,UAAU;CACV,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,UAAU;CACV,WAAW;CACX,WAAW;CACX,UAAU;CACV,WAAW;CACX,OAAO;CACP,OAAO;CACP,KAAK;CACL,OAAO;CACP,gBAAgB;CAChB,OAAO;CACP,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,aAAa;CACb,SAAS;CACT,WAAW;CACX,QAAQ;CACR,W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;;;;;AAQA,SAAgB,iBACd,UACA,WACA,SACQ;CACR,IAAI,WAAW,WAAW,OAAO;CACjC,OAAO,SAAS,KAAK,MACnB,mBAAmB,UAAU,SAAS,GACtC,mBAAmB,UAAU,OAAO,CACtC;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,iBACd,WACA,YACA,SACe;CACf,IAAI,CAAC,WAAW,QAAQ,WAAW,GACjC,OAAO,cAAc,aACjB,OACA,oCAAoC,UAAU,qBAAqB,WAAW;CAEpF,IAAI,WAAW;CACf,IAAI,WAAW;CACf,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,CAAC,MAAM,QAAQ,QAAQ;EAC7B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,CAAC,OAAO,UAAU,IAAI,GACnD,OAAO,UAAU,EAAE;EAErB,IAAI,QAAQ,UACV,OAAO,UAAU,EAAE,QAAQ,KAAK,sBAAsB;EAExD,IAAI,OAAO,WACT,OAAO,UAAU,EAAE,QAAQ,KAAK,eAAe,UAAU;EAE3D,MAAM,OAAO,QAAQ,YAAY,OAAO,WAAW;EACnD,IAAI,SAAS,KAAK,SAAS,GACzB,OAAO,UAAU,EAAE,oCAAoC,KAAK;EAE9D,WAAW;EACX,WAAW;CACb;CACA,MAAM,OAAO,YAAY,YAAY;CACrC,IAAI,SAAS,YACX,OAAO,6BAA6B,KAAK,uBAAuB;CAElE,OAAO;AACT;;;;;;;;;AC7MA,MAAa,8BAA8B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"builders-8Hl1AYNU.cjs","names":["EngineError","EngineErrorCode","EngineError","EngineErrorCode","EngineError","EngineErrorCode","foldText","toOriginalRange","foldText","isRotatedGeometryRun","foldText"],"sources":["../src/dto/PdfAction.ts","../src/dto/PageRender.ts","../src/dto/PdfSaveMode.ts","../src/identity/PageObjectNumber.ts","../src/identity/AnnotationStableId.ts","../src/revision/RevisionToken.ts","../src/revision/WeakAnnotationState.ts","../src/annotation/primitives.ts","../src/resource/BinarySource.ts","../src/resource/binaryMetadata.ts","../src/annotation/kinds/file-attachment/normalize.ts","../src/annotation/kinds/stamp/normalize.ts","../src/annotation/normalize.ts","../src/annotation/relationships.ts","../src/annotation/comments.ts","../src/mutation/AnnotationMutationImpactPolicy.ts","../src/annotation/appearance.ts","../src/identity/FormFieldRef.ts","../src/search/literal.ts","../src/search/regex.ts","../src/search/matcher.ts","../src/search/snippet.ts","../src/text/layout.ts","../src/search/rects.ts","../src/search/epoch.ts","../src/auth/scope/pdf-bits.ts","../src/auth/scope/builders.ts"],"sourcesContent":["import type { PdfDestination } from './PdfDestination';\n\n/** Normalized values of an action dictionary's `/S` name. */\nexport type PdfActionType = PdfActionNode['type'];\n\n/**\n * One Hide `/T` or ResetForm `/Fields` entry. Deliberately UNSCOPED: a\n * dictionary reference carries no page, so resolution (a name to widgets, an\n * object number to an annotation or field) is the interpreter's job — never\n * the extractor's.\n */\nexport type PdfActionTargetRef =\n | { kind: 'name'; name: string }\n | { kind: 'objectNumber'; objectNumber: number };\n\n/**\n * Decoded SubmitForm `/Flags` word (ISO 32000-2:2020 Table 240) plus the raw\n * value. `exclude` is DERIVED from bit 1 — never stored separately, so the\n * two cannot disagree. Note the two easily-missed positions verified against\n * the spec: bit 12 is `ExclFKey` (not \"ExclFDFTemplate\") and bit 13 is\n * reserved/undefined, so `EmbedForm` is bit 14.\n */\nexport interface SubmitFormFlags {\n raw: number;\n /** Bit 1: set → `fields` lists EXCLUDED fields. */\n exclude: boolean;\n /** Bit 2: submit designated valueless fields too, as name-only entries. */\n includeNoValueFields: boolean;\n /** Bits 3/6/9 folded into one verdict: bit 9 SubmitPDF dominates (\"all\n * other flags shall be ignored except GetMethod\"), else bit 6 XFDF, else\n * bit 3 HTML Form format, else FDF (the Table 240 default). */\n format: 'fdf' | 'html' | 'xfdf' | 'pdf';\n /** Bit 4. ISO makes GetMethod meaningful only with ExportFormat set, and\n * the bit-9 rule keeps it alive for SubmitPDF — so `'get'` only for\n * `'html'` and `'pdf'`; everything else posts. */\n method: 'post' | 'get';\n /** Bit 5 (meaningful only with ExportFormat; passed through — this stack\n * does not capture click coordinates). */\n submitCoordinates: boolean;\n /** Bit 7 (FDF only): include incremental updates via FDF `Differences`. */\n includeAppendSaves: boolean;\n /** Bit 8 (FDF only): include markup annotations. */\n includeAnnotations: boolean;\n /** Bit 10: convert date-like values to the standard date format. */\n canonicalFormat: boolean;\n /** Bit 11 (FDF, with IncludeAnnotations): only the current user's\n * annotations. */\n exclNonUserAnnots: boolean;\n /** Bit 12: the submitted FDF excludes its `F` entry. */\n exclFKey: boolean;\n /** Bit 14 (bit 13 is reserved): the FDF `F` entry embeds the source PDF. */\n embedForm: boolean;\n}\n\n/**\n * The one Table-240 decode, shared by the reader, the schema's producers,\n * and tests — so bit semantics cannot fork.\n */\nexport const decodeSubmitFormFlags = (raw: number): SubmitFormFlags => {\n const bit = (n: number): boolean => (raw & (1 << (n - 1))) !== 0;\n const format = bit(9) ? 'pdf' : bit(6) ? 'xfdf' : bit(3) ? 'html' : 'fdf';\n return {\n raw,\n exclude: bit(1),\n includeNoValueFields: bit(2),\n format,\n method: bit(4) && (format === 'html' || format === 'pdf') ? 'get' : 'post',\n submitCoordinates: bit(5),\n includeAppendSaves: bit(7),\n includeAnnotations: bit(8),\n canonicalFormat: bit(10),\n exclNonUserAnnots: bit(11),\n exclFKey: bit(12),\n embedForm: bit(14),\n };\n};\n\n/**\n * SubmitForm's extracted intent. ATOMIC on purpose: either every required\n * component resolved (a complete, executable payload) or the node carries no\n * payload at all — partial states are unrepresentable. An unreadable\n * REQUIRED component (`/F`) degrades the whole node to `unknown` +\n * `payload-dropped` at read time instead.\n */\nexport interface SubmitFormPayload {\n /** Resolved `/F` URL — a `<< /FS /URL >>` file specification (7.11.5,\n * `/UF` preferred over `/F` per 7.11.2); a bare string `/F` is accepted\n * as a producer-compat extension. */\n url: string;\n /**\n * `null` = `/Fields` ABSENT → Include/Exclude is ignored and every field\n * except NoExport-flagged ones is submitted (Table 239). `[]` =\n * present-but-empty: include mode submits NOTHING, exclude mode submits\n * everything eligible — presence and emptiness are different states.\n */\n fields: PdfActionTargetRef[] | null;\n flags: SubmitFormFlags;\n /** `/CharSet` (PDF 2.0), extracted but not encoded by this stack. */\n charSet?: string;\n}\n\ninterface PdfActionNodeCommon {\n /** Raw `/S` name, retained for unknown and future action types. */\n subtype: string;\n /** Normalized `/Next` children in PDF order. */\n next: PdfActionNode[];\n}\n\n/**\n * One detached node in a normalized PDF action tree, discriminated on the\n * interpreter that would execute it. Every executable arm carries its full\n * payload — a `goto` without a destination or a `uri` without a URI is\n * unrepresentable. A payload the reader cannot materialize degrades the node\n * to `unknown` (original `/S` kept on `subtype`) and appends the tree-level\n * `'payload-dropped'` warning.\n */\nexport type PdfActionNode = PdfActionNodeCommon &\n (\n | { type: 'javascript'; script: string }\n | { type: 'goto'; destination: PdfDestination }\n | { type: 'uri'; uri: string; isMap: boolean }\n | { type: 'named'; name: string }\n | { type: 'hide'; targets: PdfActionTargetRef[]; hide: boolean }\n | {\n type: 'reset-form';\n /**\n * `null` = `/Fields` ABSENT → reset every field (`exclude` is\n * meaningless). `[]` = present-but-empty: with `exclude` false reset\n * NOTHING, with `exclude` true reset EVERYTHING — PDFium's executor\n * branches on presence first.\n */\n fields: PdfActionTargetRef[] | null;\n exclude: boolean;\n }\n /** Reported, never executed. */\n | { type: 'goto-remote'; filePath: string }\n | { type: 'goto-embedded'; filePath: string }\n | { type: 'launch'; filePath: string }\n /** ISO allows `/Rendition` to carry `/JS`; preserved, not collected. */\n | { type: 'rendition'; script?: string }\n /** Recognized; executable only when `payload` is present. Absent payload\n * = extracted by an older runtime (skew) — the node stays\n * recognized-inert exactly as before this payload existed. */\n | { type: 'submit-form'; payload?: SubmitFormPayload }\n | { type: 'thread' }\n | { type: 'sound' }\n | { type: 'movie' }\n | { type: 'import-data' }\n | { type: 'set-ocg-state' }\n | { type: 'transition' }\n | { type: 'goto-3d-view' }\n | { type: 'unknown' }\n );\n\nexport type PdfActionWarning =\n | 'cycle-dropped'\n | 'malformed-next'\n | 'incomplete'\n /** A node's payload could not be read; that node degraded to `unknown`. */\n | 'payload-dropped';\n\n/**\n * One extracted action root plus the native reader's safety verdict.\n * Consumers must never execute a tree whose `incomplete` flag is true.\n */\nexport interface PdfActionTree {\n /** Null when the model was valid but its root exceeded a safety bound. */\n root: PdfActionNode | null;\n incomplete: boolean;\n /** Raw native bits, retained so newer warnings survive older SDKs.\n * TS-detected warnings (`payload-dropped`) appear only in `warnings`. */\n warningFlags: number;\n warnings: PdfActionWarning[];\n}\n\nexport interface PdfFieldActions {\n keystroke?: PdfActionTree;\n format?: PdfActionTree;\n validate?: PdfActionTree;\n calculate?: PdfActionTree;\n}\n\nexport interface PdfPageActions {\n open?: PdfActionTree;\n close?: PdfActionTree;\n}\n\nexport interface PdfAnnotationActions {\n activate?: PdfActionTree;\n cursorEnter?: PdfActionTree;\n cursorExit?: PdfActionTree;\n mouseDown?: PdfActionTree;\n mouseUp?: PdfActionTree;\n focus?: PdfActionTree;\n blur?: PdfActionTree;\n pageOpen?: PdfActionTree;\n pageClose?: PdfActionTree;\n pageVisible?: PdfActionTree;\n pageInvisible?: PdfActionTree;\n}\n\nexport interface NamedJavaScriptAction {\n /** Name-tree key. Array order is the PDF boot order. */\n name: string;\n action: PdfActionTree;\n}\n\n/** Catalog-owned actions. Page actions stay on their owning PageLayout. */\nexport interface DocumentActionsSnapshot {\n nameTreeScripts: NamedJavaScriptAction[];\n /** Action-form `/OpenAction`. Mutually exclusive with `openDestination` —\n * `/OpenAction` is one entry, a dictionary or an array. */\n openAction: PdfActionTree | null;\n /** Destination-form `/OpenAction` — the initial view, not an action.\n * Optional on the wire for skew tolerance (absent ≡ null); the schema\n * defaults it, so parsed snapshots always carry the key. */\n openDestination?: PdfDestination | null;\n willClose?: PdfActionTree;\n willSave?: PdfActionTree;\n didSave?: PdfActionTree;\n willPrint?: PdfActionTree;\n didPrint?: PdfActionTree;\n}\n\n/**\n * Aggregate guard applied across every action model read by one job. Native\n * limits are per model; this prevents a document containing many models from\n * creating an unbounded detached snapshot.\n */\nexport interface ActionReadBudget {\n maxModels: number;\n maxNodes: number;\n maxScriptCodeUnits: number;\n /** Hide `/T` + ResetForm/SubmitForm `/Fields` entries, aggregate across\n * the job. */\n maxTargetEntries: number;\n /** Payload string code units (URIs, submit URLs/CharSets, names, file\n * paths, name-tree script names), aggregate across the job. Reserved\n * BEFORE allocation. */\n maxPayloadCodeUnits: number;\n}\n","import { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport type { PdfRect, PdfRotation } from '../geometry/primitives';\n\nexport type PageRenderEncodedFormat = 'png' | 'webp' | 'bmp';\n\n/**\n * Formats that are acceptable for cacheable cloud HTTP render endpoints.\n * BMP and raw RGBA stay local-only because they are intentionally huge.\n */\nexport type PageNetworkRenderFormat = 'png' | 'webp';\n\nexport type PageRenderFormat = PageRenderEncodedFormat | 'rgba';\n\nexport type PageRenderBackground = 'white' | 'transparent';\n\nexport type PageRenderViewport =\n | {\n /**\n * Render one PDF user-space unit as `scale` device pixels. Callers\n * that care about devicePixelRatio should fold it into this value.\n */\n kind: 'scale';\n scale?: number;\n }\n | {\n /**\n * Exact output width in device pixels. Height preserves the region's\n * aspect ratio after rotation.\n */\n kind: 'width';\n width: number;\n };\n\nexport type PageRenderTarget =\n | { kind: 'page' }\n | {\n kind: 'rect';\n /**\n * PDF user-space rectangle. Same convention as annotation rects:\n * top > bottom, origin at the PDF page's bottom-left.\n */\n rect: PdfRect;\n };\n\nexport interface PageRenderOptions {\n target?: PageRenderTarget;\n viewport?: PageRenderViewport;\n rotation?: PdfRotation;\n background?: PageRenderBackground;\n includeAnnotations?: boolean;\n /**\n * Output-pixel budget: the renderer rejects (InvalidArg) instead of\n * allocating when `outputWidth × outputHeight` exceeds it. A WIDTH\n * lattice bounds width but not height — a 1×14,400pt page still\n * explodes vertically — so the guard lives where the allocation\n * happens (the decode-bomb-guard pattern). SERVER requests carry it\n * from the deployment's render policy; LOCAL engines inject it only\n * when `localEngine({ renderPolicy })` configured a budget — the\n * default local policy stays continuous and unbudgeted (exactness is\n * the local product promise).\n */\n maxOutputPixels?: number;\n}\n\nexport interface PageImageOptions extends PageRenderOptions {\n format?: PageRenderEncodedFormat;\n quality?: number;\n}\n\nexport interface PageRenderQuery {\n options: PageImageOptions;\n contentVersion?: number;\n annotationVersion?: number;\n}\n\n/**\n * Raw renderer output shared by local workers and server workers. The pixel\n * buffer is a first-class ArrayBuffer so worker transports can transfer\n * ownership instead of cloning it.\n */\nexport interface PageRaster {\n width: number;\n height: number;\n stride: number;\n color: 'rgba8';\n premultipliedAlpha: false;\n data: ArrayBuffer;\n}\n\nexport interface PageImageResult {\n width?: number;\n height?: number;\n format: PageRenderEncodedFormat;\n contentType: string;\n source: PageImageSource;\n}\n\nexport type PageImageSource = { kind: 'bytes'; bytes: Uint8Array } | { kind: 'url'; url: string };\n\nexport interface PageImageObjectUrl {\n url: string;\n revoke(): void;\n}\n\nexport interface PageImageHandle extends PageImageResult {\n objectUrl(signal?: AbortSignal): Promise<PageImageObjectUrl>;\n}\n\nexport interface PageImageBlobSource {\n blob(signal?: AbortSignal): Promise<Blob>;\n}\n\nexport function createPageImageHandle(\n result: PageImageResult,\n blobSource: PageImageBlobSource,\n): PageImageHandle {\n return {\n ...result,\n async objectUrl(signal?: AbortSignal) {\n if (typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) {\n throw new EngineError(\n EngineErrorCode.RuntimeUnavailable,\n 'Object URLs are not available in this environment',\n );\n }\n\n const blob = await blobSource.blob(signal);\n const url = URL.createObjectURL(blob);\n return { url, revoke: () => URL.revokeObjectURL(url) };\n },\n };\n}\n","export type PdfSaveMode = 'incremental' | 'rewrite';\n\nexport const DEFAULT_PDF_SAVE_MODE: PdfSaveMode = 'incremental';\n","/**\n * PDF indirect object number for a page.\n *\n * Resolved via the PDFium runtime helper `EPDFPage_GetObjectNumber(pagePtr)`.\n * Always > 0 for well-formed PDFs. This replaces the v2 page index as the\n * primary addressing key. The page index is kept on `PageHandle` as display\n * metadata only, because it can shift when pages are inserted, deleted, or\n * reordered while a session is open.\n */\nexport type PageObjectNumber = number;\n\n/**\n * Type guard for the rare malformed-PDF case where a page is a direct\n * object. The engine treats `0` as malformed and throws `EngineError(NotFound)`\n * before any page-level operation.\n */\nexport function isValidPageObjectNumber(value: unknown): value is PageObjectNumber {\n return typeof value === 'number' && Number.isInteger(value) && value > 0;\n}\n","/**\n * The two durable ways to address an annotation across reads.\n *\n * `objectNumber` is the PDF indirect object number, returned by\n * `EPDFAnnot_GetObjectNumber(annotPtr)`. It is `> 0` for indirect objects\n * (the overwhelming common case) and `0` for direct objects (rare, legacy\n * PDFs). When the engine sees `0` it falls back to `nm` if present, or\n * promotes the annotation to a weak ref (`AnnotationRef.kind === 'index'`).\n *\n * `nm` is the value of the annotation's `/NM` entry. The v3 engine never\n * writes `/NM` on read — clients can opt into symbolic IDs by passing one to\n * `create()`, but reads never mutate the document.\n */\nexport type AnnotationStableId =\n | { kind: 'objectNumber'; value: number }\n | { kind: 'nm'; value: string };\n\n/**\n * URL-safe encoding of a stable id, used by the cloud HTTP surface as the\n * `:annotKey` route parameter. Decoded by the server back into an\n * `AnnotationStableId` via `decodeStableIdKey`.\n *\n * Format:\n * `{ kind: 'objectNumber', value: 42 }` -> `'obj:42'`\n * `{ kind: 'nm', value: 'foo bar' }` -> `'nm:foo bar'`\n *\n * The caller is responsible for `encodeURIComponent`-ing the result before\n * splicing it into a URL path; `wirePaths.layerAnnotationByKey` already does\n * that. /NM values are opaque strings and may contain anything; the\n * `nm:` prefix lets the decoder distinguish them from numeric ids\n * unambiguously.\n */\nexport function encodeStableIdKey(id: AnnotationStableId): string {\n if (id.kind === 'objectNumber') {\n if (!Number.isInteger(id.value) || id.value <= 0) {\n throw new RangeError(\n `encodeStableIdKey: objectNumber must be a positive integer, got ${id.value}`,\n );\n }\n return `obj:${id.value}`;\n }\n return `nm:${id.value}`;\n}\n\n/**\n * Inverse of `encodeStableIdKey`. Returns `null` for malformed input so\n * the server can answer 400 InvalidArg with a useful message instead of\n * throwing.\n *\n * The input is the already-`decodeURIComponent`-ed segment from the route\n * path. Empty `/NM` values are rejected: `nm:` with no suffix is not a\n * valid identity.\n */\nexport function decodeStableIdKey(key: string): AnnotationStableId | null {\n if (key.startsWith('obj:')) {\n const rest = key.slice('obj:'.length);\n const n = Number.parseInt(rest, 10);\n if (!Number.isInteger(n) || n <= 0 || String(n) !== rest) return null;\n return { kind: 'objectNumber', value: n };\n }\n if (key.startsWith('nm:')) {\n const value = key.slice('nm:'.length);\n if (value.length === 0) return null;\n return { kind: 'nm', value };\n }\n return null;\n}\n","import type { PageObjectNumber } from '../identity/PageObjectNumber';\n\n/**\n * Opaque token a client must hand back when addressing an annotation by\n * `(pageObjectNumber, index)`. The engine validates strict equality against\n * its own `RevisionStore`; mismatches throw `EngineError(InvalidReference)`.\n *\n * Bleed-over prevention: `docSessionId` ties a token to one open session,\n * so a token minted before close-and-reopen is rejected by the new session.\n */\nexport interface RevisionToken {\n docSessionId: string;\n pageObjectNumber: PageObjectNumber;\n generation: number;\n}\n\nexport function revisionTokensEqual(a: RevisionToken, b: RevisionToken): boolean {\n return (\n a.docSessionId === b.docSessionId &&\n a.pageObjectNumber === b.pageObjectNumber &&\n a.generation === b.generation\n );\n}\n","/**\n * Tri-state knowledge about weak annotation identities on a page.\n *\n * `known(false)` is a stronger claim than \"we have not looked yet\": it means\n * the page's annotations were scanned and every annotation had a durable\n * identity. Cloud/CDN manifests must only publish boolean weak flags from a\n * known state.\n */\nexport type WeakAnnotationState =\n | { kind: 'unknown' }\n | { kind: 'known'; hasAnyWeakAnnotations: boolean };\n\nexport const UNKNOWN_WEAK_ANNOTATION_STATE: WeakAnnotationState = { kind: 'unknown' };\n\nexport function knownWeakAnnotationState(hasAnyWeakAnnotations: boolean): WeakAnnotationState {\n return { kind: 'known', hasAnyWeakAnnotations };\n}\n","/**\n * Wire-stable annotation primitives that are NOT pure geometry.\n *\n * Geometry primitives (points, rects, sizes, quads, rotation) now live in\n * `../geometry` as the canonical `Pdf*` vocabulary. The aliases below are\n * TRANSITIONAL re-exports kept only so existing consumers keep compiling\n * during the geometry consolidation; new code should import `Pdf*` directly\n * from `../geometry`.\n *\n * These do not depend on PDFium or any browser/Node surface; they are\n * the lingua franca between local engine, cloud engine, and server.\n */\n\nimport type { PdfPoint, PdfRect, PdfRotation, PdfSize } from '../geometry/primitives';\n\n/** @deprecated Use `PdfPoint` from `../geometry`. */\nexport type Point = PdfPoint;\n/** @deprecated Use `PdfRect` from `../geometry`. */\nexport type Rect = PdfRect;\n/** @deprecated Use `PdfSize` from `../geometry`. */\nexport type Size = PdfSize;\n/** @deprecated Use `PdfRotation` from `../geometry`. */\nexport type Rotation = PdfRotation;\n\n/**\n * sRGB color. Components are 0..255 integers. Engines normalize PDFium's\n * device color space into sRGB at read time.\n *\n * Colour carries NO alpha: annotation transparency is a separate concern\n * stored in `/CA` and surfaced as the `opacity` style field, so there is a\n * single source of truth for transparency. See `ColorStyleFields.opacity`.\n */\nexport interface Color {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * /LE entries (line endings). Maps PDFium FPDFAnnot_GetLineEndings codes\n * onto the spec names. We use kebab-case so the wire format is stable\n * across language ports.\n */\nexport type LineEnding =\n | 'none'\n | 'square'\n | 'circle'\n | 'diamond'\n | 'open-arrow'\n | 'closed-arrow'\n | 'butt'\n | 'r-open-arrow'\n | 'r-closed-arrow'\n | 'slash';\n\n/**\n * The `/LE` pair carried by line and polyline annotations: the ending\n * drawn at the start point and the ending drawn at the end point.\n */\nexport interface LineEndings {\n start: LineEnding;\n end: LineEnding;\n}\n\n/**\n * The 14 standard PDF fonts a free-text annotation's `/DA` can name. We use\n * kebab-case so the wire format is stable across language ports; the engine\n * maps these onto PDFium's `FPDF_STANDARD_FONT` integer codes at write time.\n */\nexport type StandardFont =\n | 'courier'\n | 'courier-bold'\n | 'courier-bold-oblique'\n | 'courier-oblique'\n | 'helvetica'\n | 'helvetica-bold'\n | 'helvetica-bold-oblique'\n | 'helvetica-oblique'\n | 'times-roman'\n | 'times-bold'\n | 'times-bold-italic'\n | 'times-italic'\n | 'symbol'\n | 'zapf-dingbats';\n\n/**\n * Font selector for a free-text annotation: either one of the 14 PDF\n * {@link StandardFont} names, or the `key` of a font registered through\n * `engine.fonts` (local/WASM engine only).\n *\n * The `(string & {})` arm keeps the standard-font literals auto-completing\n * while still accepting any registered key. Because the standard names are\n * matched first at write time, those 14 names are reserved: don't register a\n * custom font under a key like `'helvetica'`.\n */\nexport type FreeTextFont = StandardFont | (string & {});\n\n/**\n * Horizontal text alignment (`/Q`) for free-text annotations. Maps onto the\n * ISO 32000 §12.7.3.3 quadding codes 0/1/2 at write time.\n */\nexport type TextAlignment = 'left' | 'center' | 'right';\n\n/**\n * Free-text `/IT` intent. `free-text` is a plain text box; `free-text-callout`\n * adds a `/CL` leader line pointing at the called-out region.\n */\nexport type FreeTextIntent = 'free-text' | 'free-text-callout';\n\n/** Caret `/IT` intent used by an Acrobat-compatible replace-text edit. */\nexport type CaretIntent = 'replace';\n\n/** Strikeout `/IT` intent used by the subordinate part of a replace-text edit. */\nexport type StrikeoutIntent = 'strikeout-text-edit';\n\n/** Ink `/IT` intent used by an Acrobat-compatible freehand highlighter. */\nexport type InkIntent = 'ink-highlight';\n\n/**\n * Effective blend mode of an annotation's normal appearance stream (`/AP /N`).\n * Values use CSS-compatible kebab-case so the wire vocabulary is portable; the\n * engine maps them onto PDFium's `FPDF_BLENDMODE` integer codes.\n */\nexport type BlendMode =\n | 'normal'\n | 'multiply'\n | 'screen'\n | 'overlay'\n | 'darken'\n | 'lighten'\n | 'color-dodge'\n | 'color-burn'\n | 'hard-light'\n | 'soft-light'\n | 'difference'\n | 'exclusion'\n | 'hue'\n | 'saturation'\n | 'color'\n | 'luminosity';\n\n/**\n * Border/line style for shape annotations — the `/BS /S` (border style)\n * subset PDFium can author. Maps onto the ISO 32000 §8.4.3.3 border style\n * names. Cloudy borders are a SEPARATE concern (`/BE` border effect),\n * surfaced as `cloudyIntensity` on the shape DTO, not as a border style.\n *\n * kebab-/lower-case so the wire format is stable across language ports;\n * the engine maps these onto PDFium's integer codes at write time.\n */\nexport type AnnotationBorderStyle = 'solid' | 'dashed' | 'beveled' | 'inset';\n\n/**\n * `/RD` (rectangle differences) for shape annotations — the four margins,\n * in PDF points, between the annotation `/Rect` and the geometry actually\n * drawn inside it. Used so a thick/cloudy border has room to render\n * without being clipped by the `/Rect`. y-up PDF user space, so each value\n * is a non-negative inset from the corresponding `/Rect` edge.\n */\nexport interface PdfRectDifferences {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\n/**\n * The `/RT` (reply type) relationship an annotation declares toward the\n * annotation its `/IRT` points at (ISO 32000 §12.5.6.2). Wire-stable\n * kebab/lower-case strings; the engine maps these onto PDFium's\n * `FPDF_ANNOT_REPLY_TYPE` integer codes at read/write time.\n *\n * 'reply' -> `/R` a comment-thread reply (the ISO default when\n * `/IRT` is present but `/RT` is absent).\n * 'group' -> `/Group` a subordinate part of one logical annotation\n * group (e.g. the Caret of a text-edit pair).\n */\nexport type AnnotationReplyType = 'reply' | 'group';\n\n/** The two ISO 32000 §12.5.6.3 standard state models (Table 174). */\nexport type KnownAnnotationStateModel = 'review' | 'marked';\n\n/**\n * The `/StateModel` of an annotation-state text annotation — ISO 32000\n * §12.5.6.3. The standard models are `'review'` and `'marked'`, but the\n * PDF stores the entry as a free text string and Acrobat supports\n * registering custom state models, so the type stays open. The\n * `(string & {})` arm keeps the standard literals auto-completing while\n * accepting any custom model (the {@link FreeTextFont} pattern).\n *\n * Known values are wire-stable lowercase; the engine maps them onto the\n * capitalized PDF spellings (`Review`, `Marked`) at read/write time.\n * Unknown values round-trip verbatim in both directions.\n */\nexport type AnnotationStateModel = KnownAnnotationStateModel | (string & {});\n\n/** The ISO 32000 §12.5.6.3 standard states (Table 174). */\nexport type KnownAnnotationState =\n | 'accepted'\n | 'rejected'\n | 'cancelled'\n | 'completed'\n | 'none'\n | 'marked'\n | 'unmarked';\n\n/**\n * The `/State` an annotation-state text annotation sets — ISO 32000\n * §12.5.6.3. `'accepted' | 'rejected' | 'cancelled' | 'completed' |\n * 'none'` belong to the `'review'` model; `'marked' | 'unmarked'` to the\n * `'marked'` model. Open for the same reason as\n * {@link AnnotationStateModel}: custom models bring custom states.\n *\n * States are PER USER and live on separate text annotations replying\n * (`/IRT`) to their target — never on the target itself. The `/T` of the\n * state annotation names who set it; later changes by the same user\n * chain as replies to their previous state annotation, latest wins.\n */\nexport type AnnotationState = KnownAnnotationState | (string & {});\n\n/**\n * Bitset wrapper for the `/F` (Annotation Flags) PDF entry. We expose each\n * bit as its own boolean so callers don't have to know the bit positions.\n */\nexport interface AnnotationFlags {\n invisible: boolean;\n hidden: boolean;\n print: boolean;\n noZoom: boolean;\n noRotate: boolean;\n noView: boolean;\n readOnly: boolean;\n locked: boolean;\n toggleNoView: boolean;\n lockedContents: boolean;\n}\n\nexport const NO_ANNOTATION_FLAGS: AnnotationFlags = {\n invisible: false,\n hidden: false,\n print: false,\n noZoom: false,\n noRotate: false,\n noView: false,\n readOnly: false,\n locked: false,\n toggleNoView: false,\n lockedContents: false,\n};\n","/**\n * Inline binary payloads for annotation drafts/patches.\n *\n * Public rule (see also `annotation/normalize.ts`): binary data is a call\n * ARGUMENT, never engine state. Callers put bytes directly on the draft\n * field that names their role (stamp `source`, future file-attachment\n * `file`); normalization replaces each such field with a `ResourceRef`\n * and moves the bytes into a `WireResourceMap` that travels out-of-band\n * (worker: transferable buffers; cloud: multipart parts). After the call,\n * the only durable home for the bytes is the PDF itself.\n */\n\n/**\n * Richest accepted input for a binary field. `mimeType` is advisory only —\n * every engine sniffs magic bytes and the sniffed format wins (the server\n * cannot trust a declared type anyway).\n */\nexport type BinarySource = Uint8Array | Blob | BinaryPayload;\n\nexport interface BinaryPayload {\n data: Uint8Array | Blob;\n /** Advisory only — engines always sniff magic bytes. */\n mimeType?: string;\n /** Optional display/file name (multipart `filename`, future /UF). */\n name?: string;\n}\n\n/**\n * A resolved binary payload in wire form: a PRIVATE COPY of the caller's\n * bytes, owned by the call and ready to ship (worker transfer list or\n * multipart part body). Ownership is the whole point: the local engine puts\n * `bytes` on a postMessage transfer list, which detaches the buffer, and a\n * `BinarySource` is a borrowed argument — never the caller's buffer to lose.\n * Blob sources yield fresh bytes by construction; Uint8Array sources are\n * copied here so a full-span view is not silently aliased and killed.\n */\nexport interface WireResource {\n bytes: ArrayBuffer;\n mimeType?: string;\n name?: string;\n}\n\n/** Keyed resources accompanying one mutation. Keys are allocator-generated (`r0`, `r1`, …). */\nexport type WireResourceMap = Record<string, WireResource>;\n\n/** What replaces a `BinarySource` field in the wire form of a draft/patch. */\nexport interface ResourceRef {\n resource: string;\n}\n\nfunction isBlob(value: unknown): value is Blob {\n return typeof Blob !== 'undefined' && value instanceof Blob;\n}\n\n/**\n * Copy a Uint8Array view into a fresh, exactly-sized ArrayBuffer the call\n * owns. Always copies — even when the view spans its whole buffer — because\n * the result may be transferred to a worker (detaching it), and the view is\n * the caller's. Returning `view.buffer` here would let one transfer zero\n * the caller's bytes (a stamp library's Uint8Array became single-use).\n * Callers wanting a zero-copy hand-off need an explicit \"give\" form, as\n * `pages.insert` has for bare ArrayBuffers; `BinarySource` has none.\n */\nfunction toOwnedArrayBuffer(view: Uint8Array): ArrayBuffer {\n const copy = new ArrayBuffer(view.byteLength);\n new Uint8Array(copy).set(view);\n return copy;\n}\n\n/**\n * Resolve any accepted `BinarySource` form into a `WireResource`.\n * Async because Blob bytes can only be read asynchronously.\n */\nexport async function resolveBinarySource(source: BinarySource): Promise<WireResource> {\n if (source instanceof Uint8Array) {\n return { bytes: toOwnedArrayBuffer(source) };\n }\n if (isBlob(source)) {\n const blobName = blobFileName(source);\n return {\n bytes: await source.arrayBuffer(),\n mimeType: source.type || undefined,\n ...(blobName !== undefined ? { name: blobName } : {}),\n };\n }\n const { data, mimeType, name } = source;\n const inner =\n data instanceof Uint8Array\n ? {\n bytes: toOwnedArrayBuffer(data),\n mimeType: undefined as string | undefined,\n name: undefined as string | undefined,\n }\n : {\n bytes: await data.arrayBuffer(),\n mimeType: data.type || undefined,\n name: blobFileName(data),\n };\n const resolvedName = name ?? inner.name;\n return {\n bytes: inner.bytes,\n ...((mimeType ?? inner.mimeType) ? { mimeType: mimeType ?? inner.mimeType } : {}),\n ...(resolvedName !== undefined ? { name: resolvedName } : {}),\n };\n}\n\n/** A browser `File` is a Blob with a `name` — pick it up so attachment\n * drafts can pass a `File` directly without repeating the file name. */\nfunction blobFileName(blob: Blob): string | undefined {\n const name = (blob as File).name;\n return typeof name === 'string' && name.length > 0 ? name : undefined;\n}\n","/**\n * Magic-byte format detection for inline binary payloads.\n *\n * Ported from v2 (`@embedpdf/models` image-metadata). Declared mime types\n * are never trusted — the sniffed format is canonical on every engine and\n * on the server. Raster formats include intrinsic pixel dimensions (used\n * for aspect-ratio fitting); PDF only identifies the format.\n */\n\nexport type BinaryMimeType = 'image/png' | 'image/jpeg' | 'application/pdf';\n\nexport type BinaryMetadata =\n | { mimeType: 'image/png'; width: number; height: number }\n | { mimeType: 'image/jpeg'; width: number; height: number }\n | { mimeType: 'application/pdf' };\n\n/**\n * Detect format (and intrinsic dimensions for rasters) of a binary buffer.\n *\n * @returns metadata, or `null` for unsupported/corrupt data\n */\nexport function sniffBinaryMetadata(buffer: ArrayBuffer): BinaryMetadata | null {\n if (buffer.byteLength < 4) return null;\n\n const bytes = new Uint8Array(buffer);\n\n if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {\n return parsePng(buffer);\n }\n\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return parseJpeg(buffer);\n }\n\n if (bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46) {\n return { mimeType: 'application/pdf' };\n }\n\n return null;\n}\n\nfunction parsePng(buffer: ArrayBuffer): BinaryMetadata | null {\n if (buffer.byteLength < 24) return null;\n const view = new DataView(buffer);\n const width = view.getUint32(16);\n const height = view.getUint32(20);\n if (width === 0 || height === 0) return null;\n return { mimeType: 'image/png', width, height };\n}\n\nfunction parseJpeg(buffer: ArrayBuffer): BinaryMetadata | null {\n const bytes = new Uint8Array(buffer);\n let offset = 2;\n\n while (offset + 4 < bytes.byteLength) {\n if (bytes[offset] !== 0xff) return null;\n\n const marker = bytes[offset + 1];\n\n // SOF0 through SOF3 (baseline, progressive, lossless)\n if (marker >= 0xc0 && marker <= 0xc3) {\n if (offset + 9 > bytes.byteLength) return null;\n const view = new DataView(buffer, offset + 5);\n const height = view.getUint16(0);\n const width = view.getUint16(2);\n if (width === 0 || height === 0) return null;\n return { mimeType: 'image/jpeg', width, height };\n }\n\n // Skip non-SOF markers\n if (marker === 0xd8 || marker === 0xd9) {\n offset += 2;\n } else if (marker === 0xff) {\n offset += 1;\n } else {\n const segLen = (bytes[offset + 2] << 8) | bytes[offset + 3];\n offset += 2 + segLen;\n }\n }\n\n return null;\n}\n","import type { FileAttachmentDraft, FileAttachmentWireDraft, WireAttachmentFile } from './draft';\nimport type { AttachmentFileSource } from '../../../dto/Attachment';\nimport { EngineError } from '../../../errors/EngineError';\nimport { EngineErrorCode } from '../../../errors/EngineErrorCode';\nimport {\n resolveBinarySource,\n type WireResource,\n type WireResourceMap,\n} from '../../../resource/BinarySource';\n\n/**\n * Resolve an attachment `file` into its wire halves: metadata into the\n * JSON body, bytes into the resource map. Unlike stamps there is NO\n * format allowlist — attaching arbitrary files is the point — so the\n * declared mime type wins (attachment formats cannot be reliably sniffed;\n * the writer falls back to `application/octet-stream` when absent).\n *\n * Shared by the file-attachment annotation draft (below) and the\n * document-level `attachments.create` mutation — one vocabulary, one\n * normalizer for both homes a file can enter a PDF through.\n */\nexport async function normalizeAttachmentFileSource(\n file: AttachmentFileSource,\n key: string,\n): Promise<{ wireFile: WireAttachmentFile; resource: WireResource }> {\n const resolved = await resolveBinarySource(file.data);\n const name = file.name ?? resolved.name;\n if (!name) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'attachment file requires a name — pass { data, name } or a File whose name is set',\n );\n }\n const mimeType = file.mimeType ?? resolved.mimeType;\n return {\n wireFile: {\n resource: key,\n name,\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(file.description !== undefined ? { description: file.description } : {}),\n },\n resource: { bytes: resolved.bytes, ...(mimeType !== undefined ? { mimeType } : {}), name },\n };\n}\n\nexport async function normalizeFileAttachmentDraft(\n draft: FileAttachmentDraft,\n allocateKey: () => string,\n): Promise<{ wire: FileAttachmentWireDraft; resources: WireResourceMap }> {\n const { file, ...rest } = draft;\n const key = allocateKey();\n const { wireFile, resource } = await normalizeAttachmentFileSource(file, key);\n return { wire: { ...rest, file: wireFile }, resources: { [key]: resource } };\n}\n","import { EngineError } from '../../../errors/EngineError';\nimport { EngineErrorCode } from '../../../errors/EngineErrorCode';\nimport {\n resolveBinarySource,\n type BinarySource,\n type WireResource,\n type WireResourceMap,\n} from '../../../resource/BinarySource';\nimport { sniffBinaryMetadata } from '../../../resource/binaryMetadata';\nimport type { StampDraft, StampWireDraft } from './draft';\nimport type { StampPatch, StampWirePatch } from './patch';\n\n/**\n * Resolve + validate a stamp `source`. Sniffing happens here — before any\n * transport — so callers get a fast `InvalidArg` instead of a worker/HTTP\n * round-trip. The sniffed mime type overwrites whatever was declared.\n */\nasync function resolveStampSource(source: BinarySource): Promise<WireResource> {\n const resolved = await resolveBinarySource(source);\n const meta = sniffBinaryMetadata(resolved.bytes);\n if (!meta) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'stamp source must be PNG, JPEG, or single-page PDF bytes (format is detected from the data, not the declared mime type)',\n );\n }\n return { ...resolved, mimeType: meta.mimeType };\n}\n\nexport async function normalizeStampDraft(\n draft: StampDraft,\n allocateKey: () => string,\n): Promise<{ wire: StampWireDraft; resources: WireResourceMap }> {\n const { source, ...rest } = draft;\n const resolved = await resolveStampSource(source);\n const key = allocateKey();\n return { wire: { ...rest, source: { resource: key } }, resources: { [key]: resolved } };\n}\n\nexport async function normalizeStampPatch(\n patch: StampPatch,\n allocateKey: () => string,\n): Promise<{ wire: StampWirePatch; resources: WireResourceMap }> {\n if (patch.source === undefined) {\n const { source: _source, ...rest } = patch;\n return { wire: rest, resources: {} };\n }\n const { source, ...rest } = patch;\n const resolved = await resolveStampSource(source);\n const key = allocateKey();\n return { wire: { ...rest, source: { resource: key } }, resources: { [key]: resolved } };\n}\n","import type {\n AnnotationDraft,\n AnnotationPatch,\n WireAnnotationDraft,\n WireAnnotationPatch,\n} from './kinds';\nimport type { WireResourceMap } from '../resource/BinarySource';\n// Deep imports (not the kind barrels): keeps this module — and the zod-free\n// `shared` entrypoint that re-exports it — free of the kinds' Zod schemas.\nimport { normalizeFileAttachmentDraft } from './kinds/file-attachment/normalize';\nimport { normalizeStampDraft, normalizeStampPatch } from './kinds/stamp/normalize';\n\n/**\n * The one shared splitter between authoring and wire forms — every engine\n * (local, cloud) and no one else runs this; transports never reimplement it.\n *\n * Uniform rule, zero per-kind exceptions: any `BinarySource` field on a\n * draft/patch is replaced by `{ resource: key }` and its bytes move into\n * the returned `WireResourceMap` (worker: transfer list; cloud: multipart\n * `resource:{key}` parts). Kinds without binary fields pass through\n * untouched with an empty map — their wire form IS their authoring form.\n *\n * Zod-free by design: schemas validate the returned wire form; the\n * authoring types are TypeScript-only sugar.\n */\n\nexport interface NormalizedDraft {\n wire: WireAnnotationDraft;\n resources: WireResourceMap;\n}\n\nexport interface NormalizedPatch {\n wire: WireAnnotationPatch;\n resources: WireResourceMap;\n}\n\nfunction createResourceKeyAllocator(): () => string {\n let next = 0;\n return () => `r${next++}`;\n}\n\nexport async function normalizeAnnotationDraft(draft: AnnotationDraft): Promise<NormalizedDraft> {\n switch (draft.subtype) {\n case 'stamp':\n return normalizeStampDraft(draft, createResourceKeyAllocator());\n case 'file-attachment':\n return normalizeFileAttachmentDraft(draft, createResourceKeyAllocator());\n default:\n return { wire: draft, resources: {} };\n }\n}\n\nexport async function normalizeAnnotationPatch(patch: AnnotationPatch): Promise<NormalizedPatch> {\n switch (patch.subtype) {\n case 'stamp':\n return normalizeStampPatch(patch, createResourceKeyAllocator());\n default:\n return { wire: patch, resources: {} };\n }\n}\n","/**\n * Pure, dependency-free composition of the flat annotation list into\n * reply/group threads. No PDFium, no browser, no zod — safe to import from\n * the cloud SDK, the local engine, and any UI plugin.\n *\n * The engine surfaces `/IRT` + `/RT` as flat edges on every DTO\n * ({@link AnnotationBase.inReplyTo} / {@link AnnotationBase.replyType}); it\n * deliberately does NOT nest replies/group members, because each of those\n * is itself a first-class annotation in the page list. This module turns\n * those edges into the shape a comments sidebar wants.\n *\n * See ISO 32000 §12.5.6.2:\n * - `/RT /R` -> a comment-thread reply (default when `/RT` is absent)\n * - `/RT /Group` -> a subordinate part of one logical annotation group\n */\n\nimport type { AnnotationBase } from './base';\nimport type { AnnotationDTO } from './kinds';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\n\n/**\n * Where a single annotation sits in the reply/group taxonomy.\n *\n * 'top-level' no `/IRT` — a primary annotation / thread root.\n * 'reply' `/IRT` + `/RT /R` (or `/RT` absent) — a comment.\n * 'grouped-subordinate' `/IRT` + `/RT /Group` — a visual part of a group.\n */\nexport type AnnotationRelationKind = 'top-level' | 'reply' | 'grouped-subordinate';\n\n/**\n * Classify one annotation by its relationship edge alone. Mirrors the\n * spec's \"practical parser rule\": no `/IRT` is top-level; `/RT /Group` is\n * a grouped subordinate; anything else with an `/IRT` is a reply (the\n * engine has already normalized a missing `/RT` to `'reply'`).\n */\nexport function classifyRelation(\n a: Pick<AnnotationBase, 'inReplyTo' | 'replyType'>,\n): AnnotationRelationKind {\n if (!a.inReplyTo) return 'top-level';\n return a.replyType === 'group' ? 'grouped-subordinate' : 'reply';\n}\n\n/**\n * One composed thread: a primary annotation plus the annotations that\n * point at it.\n *\n * - `groupedParts` (`/RT /Group`) are visual/helper parts of one logical\n * annotation — a sidebar should fold them into the primary, NOT list\n * them as separate comments. Group-level fields (Contents, T, Subj, …)\n * come from the primary; the subordinate's copies are ignored.\n * - `replies` (`/RT /R`) are real comment-thread entries shown threaded\n * under the primary.\n *\n * A primary may legitimately have BOTH (e.g. a StrikeOut with a Caret\n * group part and a Text reply).\n */\nexport interface AnnotationThread<T extends AnnotationDTO = AnnotationDTO> {\n primary: T;\n /** `/RT /Group` children — merge into the primary, don't list separately. */\n groupedParts: T[];\n /** `/RT /R` (or default) children — show as threaded comments. */\n replies: T[];\n}\n\n/**\n * Stable string key for an {@link AnnotationRef}, used to match a child's\n * `inReplyTo` against a candidate parent's `ref`. Both sides are produced\n * by the engine with the same identity precedence (objectNumber, then nm,\n * then index), so equal keys mean \"same annotation\".\n */\nexport function refKey(ref: AnnotationRef): string {\n switch (ref.kind) {\n case 'objectNumber':\n return `obj:${ref.pageObjectNumber}:${ref.annotObjectNumber}`;\n case 'nm':\n return `nm:${ref.pageObjectNumber}:${ref.nm}`;\n case 'index':\n return `idx:${ref.pageObjectNumber}:${ref.index}`;\n }\n}\n\n/**\n * Compose a flat annotation list (one page, or a whole document via\n * `listRawAll()` flattened) into {@link AnnotationThread}s in primary\n * order.\n *\n * Rules (ISO 32000 §12.5.6.2 + the spec's UI rule):\n * - Annotations with no `/IRT` become thread primaries, in input order.\n * - A `/RT /Group` child is attached to its primary's `groupedParts`.\n * - A `/RT /R` (or default) child is attached to its primary's `replies`.\n * - A child whose parent is not in the input set is treated as an\n * orphan primary (defensive — e.g. a partial/filtered page slice).\n *\n * Limitations (v1, matches the legacy stack): threading is one level deep\n * — a reply-to-a-reply is keyed to its direct parent, so it only appears\n * nested if that direct parent is itself a primary. Callers that want a\n * sidebar of \"most annotations, not widgets/popups\" should pre-filter the\n * input; this helper is intentionally unopinionated about eligibility.\n */\nexport function buildThreads(annotations: readonly AnnotationDTO[]): AnnotationThread[] {\n const byKey = new Map<string, AnnotationDTO>();\n for (const a of annotations) {\n byKey.set(refKey(a.ref), a);\n // Index under /NM too, so a child that points at the parent by name\n // still resolves when the parent's own ref is objectNumber-form.\n if (a.nm && a.nm.length > 0) {\n byKey.set(`nm:${a.ref.pageObjectNumber}:${a.nm}`, a);\n }\n }\n\n const threads: AnnotationThread[] = [];\n const threadByPrimaryKey = new Map<string, AnnotationThread>();\n\n const primaryThread = (primary: AnnotationDTO): AnnotationThread => {\n const key = refKey(primary.ref);\n let thread = threadByPrimaryKey.get(key);\n if (!thread) {\n thread = { primary, groupedParts: [], replies: [] };\n threadByPrimaryKey.set(key, thread);\n threads.push(thread);\n }\n return thread;\n };\n\n // Pass 1: every top-level annotation seeds a thread, preserving order.\n for (const a of annotations) {\n if (!a.inReplyTo) primaryThread(a);\n }\n\n // Pass 2: attach children to their primary; orphans become primaries.\n for (const a of annotations) {\n if (!a.inReplyTo) continue;\n const parent = byKey.get(refKey(a.inReplyTo));\n if (!parent || parent.inReplyTo) {\n // Parent missing from the set, or itself a child (one-level-deep\n // limitation): surface the annotation as its own primary so it is\n // never silently dropped.\n primaryThread(a);\n continue;\n }\n const thread = primaryThread(parent);\n if (a.replyType === 'group') thread.groupedParts.push(a);\n else thread.replies.push(a);\n }\n\n return threads;\n}\n","/**\n * Comment-thread composition — the conversation-plane view over the flat\n * annotation list.\n *\n * Where `buildThreads()` (relationships.ts) is the minimal, unopinionated\n * one-level composer, `buildCommentThreads()` is the opinionated one a\n * comments sidebar wants:\n *\n * - the WHOLE `/IRT` subtree of a root is walked (cycle-safe), and its\n * non-state members flatten into one chronological reply list;\n * - ISO 32000 §12.5.6.3 state annotations (review status) are extracted\n * into `review` instead of appearing as replies;\n * - widgets, links, and unsupported blobs (which includes `/Popup`\n * dictionaries) are excluded entirely;\n * - `/RT /Group` subordinates anywhere in the subtree fold into\n * `groupedParts`, never into `replies`.\n *\n * Tolerant-reader rules (foreign files are messy; none of this throws):\n * - empty-string `state` / `stateModel` count as absent — the engine\n * DTO is faithful (`''` = present-but-empty), tolerance lives here;\n * - a state annotation whose target cannot be resolved is DROPPED\n * (status metadata with no anchor has no meaning);\n * - an orphaned non-state reply is PROMOTED to a thread root (matching\n * `buildThreads`), as is the first input-order member of an `/IRT`\n * cycle — the visited set breaks the loop, nothing is lost or hangs;\n * - a `/State` with no `/StateModel` infers its model from the known\n * vocabulary; a custom model with no derivable state is skipped.\n *\n * Ordering: threads appear in the input order of their roots; the\n * composer never sorts by page (display order is a layout concern —\n * callers join `pages.list()`). Replies sort chronologically by\n * `created ?? modified`, entries without a date last, page z-order\n * (`index`) as the final deterministic tiebreak.\n */\n\nimport type { AnnotationDTO } from './kinds';\nimport type { KnownAnnotationState } from './primitives';\nimport { classifyRelation, refKey } from './relationships';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\nimport type { PageObjectNumber } from '../identity/PageObjectNumber';\n\n/** One reviewer's status, derived from an ISO §12.5.6.3 state annotation. */\nexport interface ReviewStatus {\n /** Wire-normalized when known (`'accepted'`, …); verbatim when custom. */\n state: string;\n /** `'review'`, `'marked'`, or a custom model verbatim. */\n stateModel: string;\n /** Reviewer key: `/EMBD_Metadata` userId, else `/T`, else null. */\n by: string | null;\n /** `/M` ?? `/CreationDate` of the state annotation (ISO 8601). */\n at: string | null;\n /** The state annotation itself — for auditing or deletion. */\n ref: AnnotationRef;\n}\n\n/**\n * Review state of one thread. The two ISO state models are independent\n * axes: `byReviewer` / `lastChange` cover the review axis (the standard\n * `Review` model plus custom models), while the personal-checkmark\n * `Marked` axis lives solely in `markedBy`.\n */\nexport interface CommentThreadReview {\n /** Latest review-axis status per reviewer key (unattributed skipped). */\n byReviewer: Record<string, ReviewStatus>;\n /** Latest review-axis change overall — a convenience, NOT a verdict. */\n lastChange: ReviewStatus | null;\n /** Reviewer keys whose latest Marked-model status is `'marked'`. */\n markedBy: string[];\n /**\n * Every state annotation in the thread's subtree (both axes, all\n * reviewers, chronological) — thread MEMBERSHIP, not status history:\n * deleting a whole thread must delete its state annotations too, and\n * the classified summaries above deliberately drop superseded refs.\n */\n statusRefs: AnnotationRef[];\n /** `byReviewer[currentUserId]`; only set when the option was given. */\n mine?: ReviewStatus | null;\n}\n\nexport interface CommentThread<T extends AnnotationDTO = AnnotationDTO> {\n root: T;\n pageObjectNumber: PageObjectNumber;\n /** Whole-subtree replies, flattened chronologically; states excluded. */\n replies: T[];\n /** Every `/RT /Group` subordinate found in the subtree. */\n groupedParts: T[];\n review: CommentThreadReview;\n}\n\nexport interface BuildCommentThreadsOptions {\n /** Compute `review.mine` against this reviewer key. */\n currentUserId?: string;\n}\n\n/** Subtypes that never participate in comment threads. `unsupported`\n * covers `/Popup` dictionaries (raw code 16) and unreadable foreign\n * blobs — neither makes a meaningful comment card. */\nconst EXCLUDED_SUBTYPES: ReadonlySet<string> = new Set(['widget', 'link', 'unsupported']);\n\nconst REVIEW_STATES: ReadonlySet<KnownAnnotationState> = new Set([\n 'accepted',\n 'rejected',\n 'cancelled',\n 'completed',\n 'none',\n]);\nconst MARKED_STATES: ReadonlySet<KnownAnnotationState> = new Set(['marked', 'unmarked']);\n\nconst nonEmpty = (v: string | null | undefined): v is string => typeof v === 'string' && v !== '';\n\n/**\n * An ISO 32000 §12.5.6.3 state annotation: a text annotation carrying a\n * non-empty `/State` or `/StateModel`. Classification never relies on\n * flags — producers disagree on how state annotations are flagged.\n */\nexport function isStateAnnotation(a: AnnotationDTO): boolean {\n return a.subtype === 'text' && (nonEmpty(a.state) || nonEmpty(a.stateModel));\n}\n\nexport function buildCommentThreads(\n annotations: readonly AnnotationDTO[],\n opts: BuildCommentThreadsOptions = {},\n): CommentThread[] {\n const eligible = annotations.filter((a) => !EXCLUDED_SUBTYPES.has(a.subtype));\n\n // Index by ref key, with an /NM alias so a child that addresses its\n // parent by name still resolves when the parent's own ref is\n // objectNumber-form (same dual index as buildThreads). ObjectNumber\n // entries win over nm aliases on duplicate /NM.\n const byKey = new Map<string, AnnotationDTO>();\n for (const a of eligible) {\n const key = refKey(a.ref);\n if (!byKey.has(key)) byKey.set(key, a);\n if (a.nm) {\n const aliasKey = refKey({ kind: 'nm', pageObjectNumber: a.pageObjectNumber, nm: a.nm });\n if (!byKey.has(aliasKey)) byKey.set(aliasKey, a);\n }\n }\n\n // Children adjacency over resolvable /IRT edges.\n const children = new Map<string, AnnotationDTO[]>();\n for (const a of eligible) {\n if (!a.inReplyTo) continue;\n const parent = byKey.get(refKey(a.inReplyTo));\n if (!parent) continue; // orphan — handled in the promotion pass\n const parentKey = refKey(parent.ref);\n const list = children.get(parentKey);\n if (list) list.push(a);\n else children.set(parentKey, [a]);\n }\n\n const visited = new Set<string>();\n const threads: CommentThread[] = [];\n\n const walk = (root: AnnotationDTO): void => {\n const replies: AnnotationDTO[] = [];\n const groupedParts: AnnotationDTO[] = [];\n const states: AnnotationDTO[] = [];\n\n visited.add(refKey(root.ref));\n const stack = [...(children.get(refKey(root.ref)) ?? [])];\n while (stack.length > 0) {\n const a = stack.pop()!;\n const key = refKey(a.ref);\n if (visited.has(key)) continue; // cycle back-edge — skip\n visited.add(key);\n if (isStateAnnotation(a)) states.push(a);\n else if (classifyRelation(a) === 'grouped-subordinate') groupedParts.push(a);\n else replies.push(a);\n stack.push(...(children.get(key) ?? []));\n }\n\n replies.sort(chronological);\n // Chronological order makes latest-wins deterministic for equal or\n // missing dates (the comparator's z-order tiebreak applies).\n states.sort(chronological);\n threads.push({\n root,\n pageObjectNumber: root.pageObjectNumber,\n replies,\n groupedParts,\n review: computeReview(states, opts),\n });\n };\n\n // Pass 1: real roots, in input order.\n for (const a of eligible) {\n if (!a.inReplyTo && !isStateAnnotation(a)) walk(a);\n }\n\n // Pass 2: promotion. Anything not reached from a root — an orphan whose\n // parent is missing, or a member of an /IRT cycle — promotes to its own\n // root in input order. State annotations never promote: a status with no\n // reachable target is dropped.\n for (const a of eligible) {\n if (visited.has(refKey(a.ref))) continue;\n if (isStateAnnotation(a)) continue;\n walk(a);\n }\n\n return threads;\n}\n\n/** `created ?? modified` ascending; undated last; z-order tiebreak. */\nfunction chronological(a: AnnotationDTO, b: AnnotationDTO): number {\n const at = a.created ?? a.modified;\n const bt = b.created ?? b.modified;\n if (at !== null && bt !== null && at !== bt) return at < bt ? -1 : 1;\n if (at !== null && bt === null) return -1;\n if (at === null && bt !== null) return 1;\n return a.index - b.index;\n}\n\nfunction computeReview(\n states: readonly AnnotationDTO[],\n opts: BuildCommentThreadsOptions,\n): CommentThreadReview {\n const byReviewer: Record<string, ReviewStatus> = {};\n const markedLatest: Record<string, ReviewStatus> = {};\n let lastChange: ReviewStatus | null = null;\n\n for (const a of states) {\n const status = toReviewStatus(a);\n if (!status) continue;\n if (status.stateModel === 'marked') {\n if (status.by !== null && isNewer(status, markedLatest[status.by])) {\n markedLatest[status.by] = status;\n }\n continue; // the Marked axis never feeds byReviewer / lastChange\n }\n if (status.by !== null && isNewer(status, byReviewer[status.by])) {\n byReviewer[status.by] = status;\n }\n if (isNewer(status, lastChange)) lastChange = status;\n }\n\n const markedBy = Object.keys(markedLatest)\n .filter((key) => markedLatest[key]!.state === 'marked')\n .sort();\n\n const review: CommentThreadReview = {\n byReviewer,\n lastChange,\n markedBy,\n statusRefs: states.map((a) => a.ref),\n };\n if (opts.currentUserId !== undefined) {\n review.mine = byReviewer[opts.currentUserId] ?? null;\n }\n return review;\n}\n\n/**\n * Derive a `ReviewStatus` from one state annotation, or null when nothing\n * classifiable can be derived. ISO defaulting happens HERE, not in the\n * engine reader: a known model with an absent state means `none` /\n * `unmarked`; an absent model infers from a known state; a custom model\n * with no state has no derivable status.\n */\nfunction toReviewStatus(a: AnnotationDTO): ReviewStatus | null {\n if (a.subtype !== 'text') return null;\n const rawState = nonEmpty(a.state) ? a.state : null;\n const rawModel = nonEmpty(a.stateModel) ? a.stateModel : null;\n\n let stateModel = rawModel;\n if (stateModel === null && rawState !== null) {\n if (REVIEW_STATES.has(rawState as KnownAnnotationState)) stateModel = 'review';\n else if (MARKED_STATES.has(rawState as KnownAnnotationState)) stateModel = 'marked';\n else return null; // custom state without a model: unclassifiable\n }\n let state = rawState;\n if (state === null) {\n if (stateModel === 'review') state = 'none';\n else if (stateModel === 'marked') state = 'unmarked';\n else return null; // custom model without a state: no default exists\n }\n if (stateModel === null) return null; // unreachable, kept for narrowing\n\n return {\n state,\n stateModel,\n by: a.userId ?? (nonEmpty(a.author) ? a.author : null),\n at: a.modified ?? a.created ?? null,\n ref: a.ref,\n };\n}\n\n/** `a` newer than (or supersedes) `b`. `at` decides; dated beats undated.\n * States arrive pre-sorted by `chronological` (date, then z-order), so on\n * equal or missing dates the later entry wins via `>=` / `true`. */\nfunction isNewer(a: ReviewStatus, b: ReviewStatus | null | undefined): boolean {\n if (!b) return true;\n if (a.at !== null && b.at !== null) return a.at >= b.at;\n if (a.at !== null) return true;\n if (b.at !== null) return false;\n return true; // both undated: input order — later entry wins\n}\n","import type { WeakAnnotationState } from '../revision/WeakAnnotationState';\n\nexport type AnnotationMutationKind = 'create' | 'update' | 'delete' | 'move';\n\nexport function changesAnnotationList(_kind: AnnotationMutationKind): boolean {\n return true;\n}\n\nexport function shiftsExistingAnnotationIndices(kind: AnnotationMutationKind): boolean {\n return kind === 'delete' || kind === 'move';\n}\n\nexport function invalidatesWeakIndexRefs(\n kind: AnnotationMutationKind,\n weakStateBefore: WeakAnnotationState,\n): boolean {\n if (!shiftsExistingAnnotationIndices(kind)) {\n return false;\n }\n if (weakStateBefore.kind !== 'known') {\n throw new Error(\n `invalidatesWeakIndexRefs requires a known WeakAnnotationState for ${kind}; got 'unknown'. ` +\n 'Caller must scan the page before computing mutation impact.',\n );\n }\n return weakStateBefore.hasAnyWeakAnnotations;\n}\n","import type { PdfRect } from '../geometry/primitives';\nimport type { AnnotationDTO, WireAnnotationPatch } from './kinds';\n\n/**\n * Appearance-impact classification: the shared, pure decision for whether an\n * update patch requires re-baking the `/AP` normal appearance stream.\n *\n * An `/AP` stream is CONTENT, not cache — a foreign producer's appearance\n * (Acrobat's rich `/AP`, an image-backed stamp) generally cannot be\n * recomputed, so destroying it is only acceptable as the explicit consequence\n * of a semantic edit. Per ISO 32000 §12.5.5 a form XObject's `BBox` is\n * algorithmically fitted into `/Rect`, so a same-size `/Rect` change\n * translates the painted pixels verbatim: preservation on a verified rigid\n * translation is a theorem, not a policy. The engine therefore never trusts a\n * caller's claim of \"this is just a move\" — it checks the geometric fact that\n * licenses preservation.\n *\n * The classifier compares in DTO space on both sides (the patch vocabulary IS\n * the DTO vocabulary, produced by the same readers), so value-diffing drops\n * no-op keys even from clients that send full-object patches. Unknown keys\n * and unknown subtypes classify as `regenerate` — conservative by default.\n */\nexport type AppearanceImpact =\n /** Nothing appearance-affecting changed value — never touch `/AP`. */\n | 'inert'\n /** A verified rigid translation — pixels identical up to translation. */\n | 'translation'\n /** A semantic appearance edit — the owner re-bakes `/AP`. */\n | 'regenerate';\n\n/** What actually happened to `/AP` during an update (the engine's echo). */\nexport type AppearanceAction = 'preserved' | 'regenerated' | 'generation-unavailable';\n\n/**\n * The appearance verdict every `AnnotationUpdateResult` carries. `changed`\n * (not `action`) is the raster-invalidation signal: `true` iff the document's\n * appearance definition changed — a regenerated `/AP`, or appearance-affecting\n * dictionary writes on a subtype the generic generator cannot re-bake.\n */\nexport interface AppearanceOutcome {\n action: AppearanceAction;\n changed: boolean;\n}\n\n/**\n * Coordinate tolerance in PDF user-space points. PDF numbers round-trip\n * through f32 (~7 significant digits) and client-side space conversions, so\n * exact float equality would misclassify no-op writes; 1e-3 pt is far below\n * anything visible while far above accumulated f32 drift at page magnitudes.\n */\nconst EPSILON = 1e-3;\n\n/**\n * Keys that never affect `/AP` on any kind: the discriminator, behavioral\n * flags, reply relationships, grouping, and the conversation-plane\n * entries (`/Subj` subject line, `/State` + `/StateModel` review status —\n * dictionary-only per ISO 32000 §12.5.6.3, never painted).\n */\nconst INERT_KEYS: ReadonlySet<string> = new Set([\n 'subtype',\n 'flags',\n 'inReplyTo',\n 'replyType',\n 'groupId',\n 'subject',\n 'state',\n 'stateModel',\n]);\n\n/**\n * Kinds whose `/AP` paints `/Contents`. Everywhere else `contents` is popup\n * note text — editing a comment must never re-bake (or destroy) the shape's\n * appearance.\n */\nconst CONTENTS_PAINTED: ReadonlySet<string> = new Set(['free-text', 'redact']);\n\n/**\n * The vertex family's `/EMBD_Metadata/Rotation` is an advisory scalar (the\n * vertices are already rotated); it never drives the AP generator, so patches\n * touching it are appearance-inert for these kinds.\n */\nconst ADVISORY_ROTATION: ReadonlySet<string> = new Set(['line', 'polyline', 'polygon', 'ink']);\n\n/**\n * The box kinds carry the `/EMBD_Metadata` transform pair (`rotation` +\n * `unrotatedRect`), tri-state on writes: omitted fields are PRESERVED, `null`\n * (or `0` for rotation) clears. Translation verification therefore compares\n * the after-state — `patch.rotation ?? current.rotation` — not the patch keys.\n */\nconst BOX_TRANSFORM: ReadonlySet<string> = new Set(['square', 'circle', 'free-text', 'stamp']);\n\n/**\n * Per-kind absolute-geometry fields (PDF user space) that a rigid translation\n * shifts together. A kind absent from this table never takes the translation\n * route. `rect` is required in every entry: a translation always moves `/Rect`.\n */\nconst TRANSLATABLE_GEOMETRY: Record<string, readonly string[]> = {\n square: ['rect', 'unrotatedRect'],\n circle: ['rect', 'unrotatedRect'],\n 'free-text': ['rect', 'unrotatedRect', 'calloutLine'],\n line: ['rect', 'linePoints'],\n polygon: ['rect', 'vertices'],\n polyline: ['rect', 'vertices'],\n ink: ['rect', 'inkList'],\n highlight: ['rect', 'quadPoints'],\n underline: ['rect', 'quadPoints'],\n squiggly: ['rect', 'quadPoints'],\n strikeout: ['rect', 'quadPoints'],\n redact: ['rect', 'quadPoints'],\n caret: ['rect'],\n text: ['rect'],\n stamp: ['rect', 'unrotatedRect'],\n 'file-attachment': ['rect'],\n link: ['rect'],\n};\n\nconst numEq = (a: number, b: number): boolean => Math.abs(a - b) <= EPSILON;\n\n/** Degrees normalized to [0,360); absent reads as 0 (no rotation). */\nconst normDeg = (v: unknown): number => {\n const n = typeof v === 'number' ? ((v % 360) + 360) % 360 : 0;\n return n;\n};\n\n/**\n * Semantic equality between a patch value and the current DTO value.\n * Numbers compare within {@link EPSILON}; `null` and `undefined` both mean\n * \"entry absent\" (the tri-state clear of an absent entry is a no-op); arrays\n * and objects compare structurally.\n */\nexport function semanticEqual(a: unknown, b: unknown): boolean {\n if (a == null || b == null) return a == null && b == null;\n if (typeof a === 'number' && typeof b === 'number') return numEq(a, b);\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => semanticEqual(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const keys = new Set([...Object.keys(a), ...Object.keys(b as object)]);\n for (const k of keys) {\n if (!semanticEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) {\n return false;\n }\n }\n return true;\n }\n return a === b;\n}\n\n/**\n * Is `next` exactly `cur` shifted by `(dx, dy)`? Walks the value structurally:\n * numeric leaves under x-axis keys (`left`/`right`/`x`) must shift by `dx`,\n * y-axis keys (`bottom`/`top`/`y`) by `dy`, and any other numeric leaf must be\n * unchanged. Arrays walk elementwise (same length required).\n */\nfunction shiftedBy(cur: unknown, next: unknown, dx: number, dy: number): boolean {\n if (cur == null || next == null) return cur == null && next == null;\n if (Array.isArray(cur) || Array.isArray(next)) {\n if (!Array.isArray(cur) || !Array.isArray(next) || cur.length !== next.length) return false;\n return cur.every((v, i) => shiftedBy(v, next[i], dx, dy));\n }\n if (typeof cur === 'object' && typeof next === 'object') {\n const keys = new Set([...Object.keys(cur), ...Object.keys(next as object)]);\n for (const k of keys) {\n const c = (cur as Record<string, unknown>)[k];\n const n = (next as Record<string, unknown>)[k];\n if (typeof c === 'number' && typeof n === 'number') {\n const delta =\n k === 'left' || k === 'right' || k === 'x'\n ? dx\n : k === 'bottom' || k === 'top' || k === 'y'\n ? dy\n : 0;\n if (!numEq(c + delta, n)) return false;\n } else if (!shiftedBy(c, n, dx, dy)) {\n return false;\n }\n }\n return true;\n }\n return cur === next;\n}\n\n/**\n * Verify the touched geometry is one rigid translation of the current state.\n * Requires `patch.rect` (a translation always moves `/Rect`) with width and\n * height preserved; every other geometry field present on the annotation must\n * ride along shifted by the same delta — a rect move that leaves `vertices`\n * behind is NOT a translation (the dictionary would desync from the pixels).\n * For box kinds the `/EMBD_Metadata` transform group is checked as an\n * after-state: writes are tri-state (omitted preserves, null/0 clears), so an\n * omitted rotation keeps the current one — but a preserved-yet-unshifted\n * `unrotatedRect` still fails the congruence check via the field loop.\n */\nfunction isRigidTranslation(\n cur: Record<string, unknown>,\n pat: Record<string, unknown>,\n subtype: string,\n geometryKeys: readonly string[],\n): boolean {\n const curRect = cur.rect as PdfRect | undefined;\n const patRect = pat.rect as PdfRect | undefined;\n if (!curRect || !patRect) return false;\n const dx = patRect.left - curRect.left;\n const dy = patRect.bottom - curRect.bottom;\n if (!numEq(patRect.right - patRect.left, curRect.right - curRect.left)) return false;\n if (!numEq(patRect.top - patRect.bottom, curRect.top - curRect.bottom)) return false;\n\n if (BOX_TRANSFORM.has(subtype)) {\n // Tri-state writes: an omitted rotation PRESERVES the current one; `null`\n // clears (≡ 0). Compare the resulting after-state.\n const rotAfter = pat.rotation === undefined ? cur.rotation : pat.rotation;\n if (!numEq(normDeg(cur.rotation), normDeg(rotAfter))) return false;\n }\n\n for (const key of geometryKeys) {\n if (key === 'rect') continue;\n const c = cur[key];\n const p = pat[key];\n if (c == null && p == null) continue; // absent on both — nothing to shift\n if (c == null || p == null) return false; // geometry appearing/vanishing\n if (!shiftedBy(c, p, dx, dy)) return false;\n }\n return true;\n}\n\n/**\n * Classify an update patch against the annotation's current DTO.\n *\n * 1. Value-diff: drop keys whose value semantically equals the current one,\n * plus the always-inert metadata keys (and per-kind inert keys: `contents`\n * where it isn't painted, advisory `rotation` on the vertex family).\n * Nothing left → `'inert'`.\n * 2. If every remaining key is translatable geometry for this kind AND the\n * values are one rigid translation → `'translation'`.\n * 3. Anything else — style, text, unknown keys, unknown kinds → `'regenerate'`.\n */\nexport function appearanceImpactOf(\n current: AnnotationDTO,\n patch: WireAnnotationPatch,\n): AppearanceImpact {\n if (patch.subtype !== current.subtype) return 'regenerate';\n\n const cur = current as unknown as Record<string, unknown>;\n const pat = patch as unknown as Record<string, unknown>;\n const subtype = patch.subtype;\n\n const touched: string[] = [];\n for (const [key, value] of Object.entries(pat)) {\n if (value === undefined || INERT_KEYS.has(key)) continue;\n if (key === 'contents' && !CONTENTS_PAINTED.has(subtype)) continue;\n if (key === 'rotation' && ADVISORY_ROTATION.has(subtype)) continue;\n if (!semanticEqual(value, cur[key])) touched.push(key);\n }\n if (touched.length === 0) return 'inert';\n\n const geometryKeys = TRANSLATABLE_GEOMETRY[subtype];\n if (!geometryKeys) return 'regenerate';\n if (!touched.every((k) => geometryKeys.includes(k))) return 'regenerate';\n return isRigidTranslation(cur, pat, subtype, geometryKeys) ? 'translation' : 'regenerate';\n}\n","import type { PageObjectNumber } from './PageObjectNumber';\n\n/**\n * How callers address a logical form field.\n *\n * - `objectNumber` — the indirect object number of the field dictionary.\n * ISO 32000 guarantees every real AcroForm field dictionary is an\n * indirect object, and the layer runtime never renumbers (frozen base +\n * incremental deltas), so this is the durable identity for the lifetime\n * of a document. Preferred for all engine calls.\n * - `fqn` — the fully qualified field name (\"billing.name\"). The portable,\n * semantic identity used by interchange formats (FDF/XFDF) and analytics;\n * survives document rewrites but is only as unique as the producer made\n * it. The engine resolves it against the reconciled field tree.\n */\nexport type FormFieldRef =\n | { kind: 'objectNumber'; fieldObjectNumber: number }\n | { kind: 'fqn'; name: string };\n\n/**\n * URL-safe encoding of a `FormFieldRef`, used by the cloud HTTP surface as\n * the `:fieldKey` route parameter. Decoded by the server back into a\n * `FormFieldRef` via `decodeFieldRefKey`. Mirrors the annotation plane's\n * `encodeStableIdKey` (`obj:42` / `nm:…`) so the two member-key syntaxes\n * read the same on the wire:\n *\n * `{ kind: 'objectNumber', fieldObjectNumber: 12 }` -> `'obj:12'`\n * `{ kind: 'fqn', name: 'billing.name' }` -> `'fqn:billing.name'`\n *\n * The caller is responsible for `encodeURIComponent`-ing the result before\n * splicing it into a URL path; the `wirePaths.layerFormField*` builders\n * already do that. FQNs are opaque strings and may contain anything; the\n * `fqn:` prefix keeps them unambiguous from numeric ids.\n */\nexport function encodeFieldRefKey(ref: FormFieldRef): string {\n if (ref.kind === 'objectNumber') {\n if (!Number.isInteger(ref.fieldObjectNumber) || ref.fieldObjectNumber <= 0) {\n throw new RangeError(\n `encodeFieldRefKey: fieldObjectNumber must be a positive integer, got ${ref.fieldObjectNumber}`,\n );\n }\n return `obj:${ref.fieldObjectNumber}`;\n }\n return `fqn:${ref.name}`;\n}\n\n/**\n * Inverse of `encodeFieldRefKey`. Returns `null` for malformed input so the\n * server can answer 400 InvalidArg with a useful message instead of\n * throwing. The input is the already-`decodeURIComponent`-ed segment from\n * the route path. Empty FQNs are rejected: `fqn:` with no suffix is not a\n * valid identity.\n */\nexport function decodeFieldRefKey(key: string): FormFieldRef | null {\n if (key.startsWith('obj:')) {\n const rest = key.slice('obj:'.length);\n const n = Number.parseInt(rest, 10);\n if (!Number.isInteger(n) || n <= 0 || String(n) !== rest) return null;\n return { kind: 'objectNumber', fieldObjectNumber: n };\n }\n if (key.startsWith('fqn:')) {\n const name = key.slice('fqn:'.length);\n if (name.length === 0) return null;\n return { kind: 'fqn', name };\n }\n return null;\n}\n\n/** A widget annotation of a field, as the forms subsystem sees it. */\nexport interface FormWidgetRef {\n /**\n * Indirect object number of the widget annotation — the join key to the\n * annotation subsystem's `objectNumber` refs. `0` when the widget is\n * stored as a direct object (spec-violating; cannot be addressed).\n */\n annotObjectNumber: number;\n /**\n * Object number of the page whose /Annots array references the widget.\n * `0` when the widget is not reachable from any page (\"unplaced\").\n */\n pageObjectNumber: PageObjectNumber;\n}\n","import { foldText, toOriginalRange } from './fold';\nimport type { FoldedText, FoldOptions, SearchMatchRange } from './fold';\nimport type { SearchQuery } from './types';\n\n/**\n * The fold flavor a literal query needs. Haystack and needle MUST be\n * folded with the same options; corpus caches key their pre-folded text\n * on this (the default `{}` fold is the persistable one — non-default\n * queries fold the original page text at query time).\n */\nexport function foldOptionsFor(query: SearchQuery): FoldOptions {\n return { keepCase: !!query.matchCase, keepMarks: !!query.matchDiacritics };\n}\n\n// ONE definition of \"word character\" for the whole search subsystem —\n// Unicode letters/digits, not JS \\b's ASCII set — shared by the literal\n// boundary check and the regex wholeWord post-filter, so the wholeWord\n// toggle means the same thing in both modes (\"caf\" never whole-word\n// matches inside \"café\", regex or not).\nconst WORD_UNIT = /[\\p{L}\\p{N}_]/u;\nconst MARK = /\\p{M}/u;\n\n/** Whether the code point ENDING at `index` (exclusive) is a word char. */\nexport function wordBefore(text: string, index: number): boolean {\n if (index <= 0) return false;\n // Step back over a low surrogate to test the full code point.\n const unit = text.charCodeAt(index - 1);\n const start = unit >= 0xdc00 && unit <= 0xdfff && index >= 2 ? index - 2 : index - 1;\n return WORD_UNIT.test(String.fromCodePoint(text.codePointAt(start)!));\n}\n\n/** Whether the code point starting at `index` is a word char. */\nexport function wordAt(text: string, index: number): boolean {\n if (index >= text.length) return false;\n return WORD_UNIT.test(String.fromCodePoint(text.codePointAt(index)!));\n}\n\n/**\n * All non-overlapping literal matches, in original code-unit space.\n * `haystack` must have been folded with `foldOptionsFor(query)`.\n */\nexport function matchLiteral(haystack: FoldedText, query: SearchQuery): SearchMatchRange[] {\n const needle = foldText(query.text, foldOptionsFor(query)).folded;\n // Nothing searchable: empty or whitespace-only needles would \"match\"\n // every collapsed space.\n if (needle.trim().length === 0) return [];\n\n const out: SearchMatchRange[] = [];\n let from = 0;\n while (from <= haystack.folded.length - needle.length) {\n const at = haystack.folded.indexOf(needle, from);\n if (at < 0) break;\n if (\n query.wholeWord &&\n (wordBefore(haystack.folded, at) || wordAt(haystack.folded, at + needle.length))\n ) {\n from = at + 1;\n continue;\n }\n // Diacritic-sensitive folds are decomposed (base + marks), so a bare\n // needle would otherwise match just the base letters of an accented\n // char — \"cafe\" ending right before the U+0301 of \"café\". A match may\n // not end mid-character.\n if (query.matchDiacritics && at + needle.length < haystack.folded.length) {\n const after = haystack.folded.codePointAt(at + needle.length)!;\n if (MARK.test(String.fromCodePoint(after))) {\n from = at + 1;\n continue;\n }\n }\n out.push(toOriginalRange(haystack, at, needle.length));\n from = at + needle.length;\n }\n return out;\n}\n","import type { SearchMatchRange } from './fold';\nimport { wordAt, wordBefore } from './literal';\nimport type { SearchQuery } from './types';\n\n/**\n * The portable search-regex dialect: JavaScript `u`-mode syntax MINUS the\n * features RE2 refuses (backreferences, lookaround). The local engine\n * executes patterns with JS `RegExp`; the server executes the SAME\n * pattern with RE2, whose linear-time guarantee is the ReDoS defense.\n * Restricting both sides to the common subset keeps one query string\n * valid — and equally powerful — everywhere.\n */\nexport const SEARCH_REGEX_MAX_LENGTH = 512;\n\nexport type SearchRegexIssue = 'empty' | 'too-long' | 'backreference' | 'lookaround' | 'syntax';\n\nexport type SearchRegexValidation =\n | { ok: true }\n | { ok: false; issue: SearchRegexIssue; message: string };\n\n/**\n * Validate a pattern against the dialect. Cheap and dependency-free —\n * viewers call it on keystroke for early feedback; engines re-validate\n * and reject bad patterns with `InvalidArg`.\n */\nexport function validateSearchRegex(pattern: string): SearchRegexValidation {\n if (pattern.length === 0) {\n return { ok: false, issue: 'empty', message: 'Pattern is empty.' };\n }\n if (pattern.length > SEARCH_REGEX_MAX_LENGTH) {\n return {\n ok: false,\n issue: 'too-long',\n message: `Pattern exceeds ${SEARCH_REGEX_MAX_LENGTH} characters.`,\n };\n }\n\n // One pass tracking escape/char-class state: backreferences and\n // lookaround only mean what they mean outside a character class.\n let inClass = false;\n for (let i = 0; i < pattern.length; i++) {\n const ch = pattern[i];\n if (ch === '\\\\') {\n const next = pattern[i + 1] ?? '';\n if (!inClass && next >= '1' && next <= '9') {\n return {\n ok: false,\n issue: 'backreference',\n message: `Backreference \\\\${next} is not supported.`,\n };\n }\n if (!inClass && next === 'k' && pattern[i + 2] === '<') {\n return {\n ok: false,\n issue: 'backreference',\n message: 'Named backreferences (\\\\k<…>) are not supported.',\n };\n }\n i++; // consume the escaped char\n continue;\n }\n if (inClass) {\n if (ch === ']') inClass = false;\n continue;\n }\n if (ch === '[') {\n inClass = true;\n continue;\n }\n if (ch === '(' && pattern[i + 1] === '?') {\n const tag = pattern[i + 2] ?? '';\n if (tag === '=' || tag === '!') {\n return {\n ok: false,\n issue: 'lookaround',\n message: 'Lookahead ((?=…), (?!…)) is not supported.',\n };\n }\n // \"(?<\" is lookbehind when followed by = or !, a named GROUP otherwise.\n if (tag === '<' && (pattern[i + 3] === '=' || pattern[i + 3] === '!')) {\n return {\n ok: false,\n issue: 'lookaround',\n message: 'Lookbehind ((?<=…), (?<!…)) is not supported.',\n };\n }\n }\n }\n\n try {\n // `u` is the strict common ground with RE2's syntax; `m` because ^/$\n // meaning line boundaries is what page-text search wants.\n new RegExp(pattern, 'mu');\n } catch (error) {\n return { ok: false, issue: 'syntax', message: (error as Error).message };\n }\n return { ok: true };\n}\n\n/**\n * Every flag combination has DEFINED semantics — most by behavior, one by\n * loud rejection (see the {@link SearchQuery} table). The single validator\n * a UI needs: call it on keystroke to grey out the diacritics toggle in\n * regex mode and flag bad patterns early; engines run the same check and\n * reject with `InvalidArg`. Literal queries are always valid (an empty\n * literal simply finds nothing).\n */\nexport type SearchQueryIssue = SearchRegexIssue | 'diacritics-with-regex';\n\nexport type SearchQueryValidation =\n | { ok: true }\n | { ok: false; issue: SearchQueryIssue; message: string };\n\nexport function validateSearchQuery(query: SearchQuery): SearchQueryValidation {\n if (!query.regex) return { ok: true };\n if (query.matchDiacritics) {\n return {\n ok: false,\n issue: 'diacritics-with-regex',\n message:\n 'Diacritic-sensitive matching is not available for regex patterns (regex runs on the raw text plane).',\n };\n }\n return validateSearchRegex(query.text);\n}\n\n/**\n * All matches of a dialect-valid pattern over the RAW page text (regex\n * does not run against folded text — case handling is the `i` flag, and\n * diacritic folding never applies). `wholeWord` is a boundary POST-FILTER\n * using the same Unicode word test as the literal path — never `\\b`,\n * whose ASCII word set would give the toggle different semantics in regex\n * mode (\"caf\" whole-word matching inside \"café\"). Filtering after the\n * match also survives the move to RE2 server-side. Zero-length matches\n * are skipped: search UI cannot highlight nothing, and skipping them is\n * also the infinite-loop guard for patterns like `a*`.\n */\nexport function matchRegex(text: string, query: SearchQuery): SearchMatchRange[] {\n const valid = validateSearchQuery({ ...query, regex: true });\n if (!valid.ok) throw new Error(`Invalid search query (${valid.issue}): ${valid.message}`);\n\n const re = new RegExp(query.text, query.matchCase ? 'gmu' : 'gimu');\n const out: SearchMatchRange[] = [];\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n if (m[0].length === 0) {\n // Advance one full code point past the empty match.\n const unit = text.charCodeAt(re.lastIndex);\n re.lastIndex += unit >= 0xd800 && unit <= 0xdbff ? 2 : 1;\n continue;\n }\n if (query.wholeWord && (wordBefore(text, m.index) || wordAt(text, m.index + m[0].length))) {\n continue;\n }\n out.push({ start: m.index, length: m[0].length });\n }\n return out;\n}\n","import { foldText } from './fold';\nimport type { SearchMatchRange } from './fold';\nimport { foldOptionsFor, matchLiteral } from './literal';\nimport { matchRegex } from './regex';\nimport type { SearchQuery } from './types';\n\n/**\n * The whole match stage in one pure call: page text in, original-space\n * match ranges out. Engines with a pre-folded corpus for the default fold\n * skip this and call `matchLiteral` on the cached `FoldedText` directly;\n * everything else (non-default fold options, regex, tests) comes through\n * here.\n */\nexport function matchPageText(text: string, query: SearchQuery): SearchMatchRange[] {\n if (query.regex) return matchRegex(text, query);\n return matchLiteral(foldText(text, foldOptionsFor(query)), query);\n}\n","import type { SearchMatchRange } from './fold';\nimport type { SearchSnippet } from './types';\n\n/** Default context on each side of a match, in code units. */\nexport const SEARCH_SNIPPET_CONTEXT = 48;\n\nconst WHITESPACE = /\\s/;\n// Length-preserving: every whitespace unit becomes one plain space, so\n// `matchStart`/`matchLength` stay valid offsets into the flattened text.\nconst WHITESPACE_ALL = /\\s/g;\n\nconst isLowSurrogate = (text: string, index: number): boolean => {\n const unit = text.charCodeAt(index);\n return unit >= 0xdc00 && unit <= 0xdfff;\n};\n\n/**\n * The `'full'`-mode excerpt around one match: up to `context` code units\n * of page text on each side, trimmed to a whitespace boundary when one\n * exists inside the window (so snippets start and end on whole words),\n * never splitting a surrogate pair, whitespace flattened 1:1.\n */\nexport function buildSnippet(\n text: string,\n range: SearchMatchRange,\n context: number = SEARCH_SNIPPET_CONTEXT,\n): SearchSnippet {\n const matchEnd = range.start + range.length;\n\n let start = Math.max(0, range.start - context);\n if (start > 0) {\n // Cut at the first whitespace inside the leading context, if any —\n // otherwise accept the mid-word cut (one very long token).\n for (let i = start; i < range.start; i++) {\n if (WHITESPACE.test(text[i])) {\n start = i + 1;\n break;\n }\n }\n if (isLowSurrogate(text, start)) start++;\n }\n\n let end = Math.min(text.length, matchEnd + context);\n if (end < text.length) {\n for (let i = end - 1; i >= matchEnd; i--) {\n if (WHITESPACE.test(text[i])) {\n end = i;\n break;\n }\n }\n if (isLowSurrogate(text, end)) end--;\n }\n\n return {\n text: text.slice(start, end).replace(WHITESPACE_ALL, ' '),\n matchStart: range.start - start,\n matchLength: range.length,\n };\n}\n","import {\n isRotatedGeometryRun,\n type PageGeometrySnapshot,\n type RotatedGeometryRun,\n} from '../dto/PageGeometrySnapshot';\nimport type { PdfPoint, PdfQuad, PdfRect } from '../geometry/primitives';\n\n/**\n * The canonical text-interaction layout — the ONE place glyph geometry\n * becomes hit targets, word/line ranges, and visual-line segments.\n *\n * Selection owns gestures and state; search owns matching and cursors;\n * NEITHER owns segmentation. Both consume this module, so a text range has\n * exactly one canonical segmentation regardless of how it was produced, and\n * coordinate conversion (PDF → content/view) happens strictly afterward at\n * the plugin seam.\n *\n * Everything here is PDF user space (y-up), the engine's one geometry\n * vocabulary. The line-merge is adapted from Chromium's\n * pdf/pdfium/pdfium_range.cc `MergeAdjacentRects` (BSD-licensed, Copyright\n * 2010 The Chromium Authors); hit-testing mirrors PDFium `GetIndexAtPos`\n * (exact tight box first, then a tolerance pass).\n *\n * ORIENTATION MODEL — frames. Every run belongs to a FRAME: frame 0 is page\n * space itself (all upright runs — the dominant case takes a byte-identical\n * fast path), and each rotated orientation cluster gets an orthonormal frame\n * in which its text reads upright (baseline +x, ascent +y). Frames are\n * derived from the SEMANTIC EDGES of the first classifiable glyph's quad —\n * never from advisory wire fields — and keyed by (baseline direction,\n * ascent handedness):\n *\n * - Rotated and mirrored text become upright inside their frame.\n * - Shear (fake italic) is deliberately NOT part of the frame key or the\n * basis: a sheared run shares the frame of its unsheared neighbours, so\n * a mixed roman/italic line merges into ONE segment (Acrobat parity),\n * and the shear is absorbed as a small in-frame AABB residue. This is\n * the deterministic, order-independent contract — an affine\n * (shear-preserving) basis would either fragment mixed lines or make\n * the roman body's geometry depend on whether an italic run came first.\n * - Runs of different frames never merge into one line.\n *\n * All algorithms run on frame-local boxes; every participating run of a\n * cluster is transformed through the SAME frame, so merged coordinates are\n * always commensurable. Only the output maps back to page space, as\n * oriented quads.\n */\n\nconst FLAG_SPACE = 1;\nconst FLAG_EMPTY = 2;\nconst isBoundary = (flags: number): boolean => (flags & (FLAG_SPACE | FLAG_EMPTY)) !== 0;\nconst isEmpty = (flags: number): boolean => (flags & FLAG_EMPTY) !== 0;\n\nconst CHAR_DISTANCE_FACTOR = 2.5;\nconst FONT_SIZE_RATIO_THRESHOLD = 1.5;\nconst VERTICAL_OVERLAP_THRESHOLD = 0.8;\nconst LINE_OVERLAP_THRESHOLD = 0.5;\n/** Baseline directions within ~0.5° share a frame. */\nconst FRAME_DOT_TOLERANCE = Math.cos(0.0087);\nconst EDGE_EPSILON = 1e-6;\n\n/**\n * One merged visual line of a text range, in PDF user space. `quad` is the\n * geometric authority (frame-geometric slot order: `p1..p4` = upper-start,\n * upper-end, lower-start, lower-end — visual semantics, NOT reading order);\n * `rect` is its axis-aligned bounds, produced by the same constructor.\n * `advance` is the READING direction along the baseline, derived from the\n * glyph SEQUENCE (+1 = the frame's +x), never inferred from geometry.\n */\nexport interface PdfTextSegment {\n quad: PdfQuad;\n rect: PdfRect;\n advance: 1 | -1;\n}\n\n/** One glyph in its frame's space. `loose` builds segments; `tight` hit-tests. */\nexport interface TextLayoutGlyph {\n loose: PdfRect;\n tight?: PdfRect;\n flags: number;\n}\n\n/** A contiguous run of glyphs (a text object) in one frame. */\nexport interface TextLayoutRun {\n /** First char index — identical to the flat glyph index (runs tile the page). */\n charStart: number;\n count: number;\n /** Frame-local loose box (page space itself in frame 0). */\n rect: PdfRect;\n fontSize?: number;\n /** Index into {@link PageTextLayout.frames}; 0 = page space (upright). */\n frame: number;\n}\n\n/** An orientation cluster's orthonormal basis in page space. */\nexport interface TextLayoutFrame {\n /** Unit vector along the reading baseline (+x of the frame). */\n baseline: PdfPoint;\n /** Unit vector toward the ascent side (+y of the frame), ⟂ baseline. */\n ascent: PdfPoint;\n}\n\n/**\n * A page's text laid out per-frame: a flat glyph list (index = text-page\n * char index), the run structure, and the orientation frames.\n */\nexport interface PageTextLayout {\n glyphs: TextLayoutGlyph[];\n runs: TextLayoutRun[];\n frames: TextLayoutFrame[];\n}\n\nconst IDENTITY_FRAME: TextLayoutFrame = { baseline: { x: 1, y: 0 }, ascent: { x: 0, y: 1 } };\n\nconst toFrame = (f: TextLayoutFrame, p: PdfPoint): PdfPoint => ({\n x: p.x * f.baseline.x + p.y * f.baseline.y,\n y: p.x * f.ascent.x + p.y * f.ascent.y,\n});\n\nconst fromFrame = (f: TextLayoutFrame, p: PdfPoint): PdfPoint => ({\n x: f.baseline.x * p.x + f.ascent.x * p.y,\n y: f.baseline.y * p.x + f.ascent.y * p.y,\n});\n\nconst ZERO_RECT: PdfRect = { left: 0, bottom: 0, right: 0, top: 0 };\n\n/** Frame-local AABB of a page-space cell (exact under the frame's rotation;\n * shear residue is the documented in-frame envelope). */\nfunction frameBoxOfQuad(f: TextLayoutFrame, q: PdfQuad): PdfRect {\n const pts = [q.p1, q.p2, q.p3, q.p4].map((p) => toFrame(f, p));\n const xs = pts.map((p) => p.x);\n const ys = pts.map((p) => p.y);\n return {\n left: Math.min(...xs),\n bottom: Math.min(...ys),\n right: Math.max(...xs),\n top: Math.max(...ys),\n };\n}\n\n/** Find-or-create the frame for a rotated run, keyed by the baseline\n * direction + ascent handedness of its first classifiable glyph's edges. */\nfunction frameForRun(frames: TextLayoutFrame[], run: RotatedGeometryRun): number {\n const seed = run.glyphs.find((g) => !isEmpty(g.flags));\n if (!seed) return 0;\n const q = seed.looseQuad;\n const bx = q.p2.x - q.p1.x;\n const by = q.p2.y - q.p1.y;\n const len = Math.hypot(bx, by);\n if (len <= EDGE_EPSILON) return 0;\n const baseline: PdfPoint = { x: bx / len, y: by / len };\n // Handedness from the actual ascent edge (lower-start → upper-start), so\n // mirrored text gets its own frame with \"up\" on its true ascent side.\n const ax = q.p1.x - q.p3.x;\n const ay = q.p1.y - q.p3.y;\n const sign = baseline.x * ay - baseline.y * ax >= 0 ? 1 : -1;\n const ascent: PdfPoint = { x: -baseline.y * sign, y: baseline.x * sign };\n\n for (let i = 0; i < frames.length; i++) {\n const f = frames[i];\n const dot = f.baseline.x * baseline.x + f.baseline.y * baseline.y;\n const sameHandedness = f.ascent.x * ascent.x + f.ascent.y * ascent.y > 0;\n if (dot >= FRAME_DOT_TOLERANCE && sameHandedness) return i;\n }\n frames.push({ baseline, ascent });\n return frames.length - 1;\n}\n\n/**\n * Flatten a page's geometry snapshot into the canonical layout. Upright runs\n * copy their wire boxes verbatim (frame 0 — byte-identical to the\n * pre-orientation behavior, wire run rects included); rotated runs project\n * their glyph cells into their cluster's frame.\n */\nexport function buildPageTextLayout(snapshot: PageGeometrySnapshot): PageTextLayout {\n const glyphs: TextLayoutGlyph[] = [];\n const runs: TextLayoutRun[] = [];\n const frames: TextLayoutFrame[] = [IDENTITY_FRAME];\n\n for (const run of snapshot.runs) {\n if (!isRotatedGeometryRun(run)) {\n for (const g of run.glyphs) {\n glyphs.push({ loose: g.looseBox, tight: g.tightBox, flags: g.flags });\n }\n runs.push({\n charStart: run.charStart,\n count: run.glyphs.length,\n rect: run.rect,\n fontSize: run.fontSize,\n frame: 0,\n });\n continue;\n }\n\n const frame = frameForRun(frames, run);\n const f = frames[frame];\n let runBox: PdfRect | null = null;\n for (const g of run.glyphs) {\n if (isEmpty(g.flags)) {\n glyphs.push({ loose: ZERO_RECT, flags: g.flags });\n continue;\n }\n const loose = frameBoxOfQuad(f, g.looseQuad);\n const tight = g.tightQuad ? frameBoxOfQuad(f, g.tightQuad) : undefined;\n glyphs.push({ loose, tight, flags: g.flags });\n runBox = runBox\n ? {\n left: Math.min(runBox.left, loose.left),\n bottom: Math.min(runBox.bottom, loose.bottom),\n right: Math.max(runBox.right, loose.right),\n top: Math.max(runBox.top, loose.top),\n }\n : loose;\n }\n runs.push({\n charStart: run.charStart,\n count: run.glyphs.length,\n rect: runBox ?? ZERO_RECT,\n fontSize: run.fontSize,\n frame,\n });\n }\n return { glyphs, runs, frames };\n}\n\nconst inRect = (r: PdfRect, p: PdfPoint): boolean =>\n p.x >= r.left && p.x <= r.right && p.y >= r.bottom && p.y <= r.top;\n\nfunction avgGlyphHeight(layout: PageTextLayout): number {\n let total = 0;\n let count = 0;\n for (const g of layout.glyphs) {\n if (isEmpty(g.flags)) continue;\n total += g.loose.top - g.loose.bottom;\n count++;\n }\n return count === 0 ? 0 : total / count;\n}\n\n/** The point expressed in every frame (index-aligned with `layout.frames`).\n * Frame 0 returns the point itself — no float round-trip on the fast path. */\nfunction pointPerFrame(layout: PageTextLayout, p: PdfPoint): PdfPoint[] {\n return layout.frames.map((f, i) => (i === 0 ? p : toFrame(f, p)));\n}\n\n/**\n * The glyph (char) index at a page-space point, or null when nothing is near\n * (so callers can show the pointer cursor off-text). PDFium `GetIndexAtPos`:\n * exact tight-box containment first, then a tolerance pass (closest by\n * Manhattan distance within `toleranceFactor × average glyph height`). Each\n * run tests the point in ITS OWN frame, so rotated text hit-tests exactly.\n */\nexport function textGlyphAt(\n layout: PageTextLayout,\n point: PdfPoint,\n toleranceFactor = 1.5,\n): number | null {\n const pts = pointPerFrame(layout, point);\n for (const run of layout.runs) {\n const q = pts[run.frame];\n if (!inRect(run.rect, q)) continue;\n for (let i = 0; i < run.count; i++) {\n const g = layout.glyphs[run.charStart + i];\n if (inRect(g.tight ?? g.loose, q)) return run.charStart + i;\n }\n }\n if (toleranceFactor <= 0) return null;\n\n const half = (avgGlyphHeight(layout) * toleranceFactor) / 2;\n let best = -1;\n let bestDist = Infinity;\n for (const run of layout.runs) {\n const q = pts[run.frame];\n const r = run.rect;\n if (\n q.x < r.left - half ||\n q.x > r.right + half ||\n q.y < r.bottom - half ||\n q.y > r.top + half\n ) {\n continue;\n }\n for (let i = 0; i < run.count; i++) {\n const g = layout.glyphs[run.charStart + i];\n if (isEmpty(g.flags)) continue;\n const b = g.tight ?? g.loose;\n if (\n q.x < b.left - half ||\n q.x > b.right + half ||\n q.y < b.bottom - half ||\n q.y > b.top + half\n ) {\n continue;\n }\n const dx = Math.min(Math.abs(q.x - b.left), Math.abs(q.x - b.right));\n const dy = Math.min(Math.abs(q.y - b.bottom), Math.abs(q.y - b.top));\n if (dx + dy < bestDist) {\n bestDist = dx + dy;\n best = run.charStart + i;\n }\n }\n }\n return best >= 0 ? best : null;\n}\n\n/** Double-click: the word around `glyph` (walk to space/empty glyphs both ways). */\nexport function expandTextRangeToWord(layout: PageTextLayout, glyph: number): [number, number] {\n const n = layout.glyphs.length;\n if (glyph < 0 || glyph >= n) return [glyph, glyph];\n let from = glyph;\n while (from > 0 && !isBoundary(layout.glyphs[from - 1].flags)) from--;\n let to = glyph;\n while (to < n - 1 && !isBoundary(layout.glyphs[to + 1].flags)) to++;\n return [from, to];\n}\n\n/** Triple-click: the full visual line — SAME-FRAME runs whose vertical extent\n * overlaps the anchor run's. A differently-oriented run is a line boundary. */\nexport function expandTextRangeToLine(layout: PageTextLayout, glyph: number): [number, number] {\n const ri = layout.runs.findIndex((r) => glyph >= r.charStart && glyph < r.charStart + r.count);\n if (ri < 0) return [glyph, glyph];\n const anchor = layout.runs[ri];\n const bottom = anchor.rect.bottom;\n const top = anchor.rect.top;\n let from = anchor.charStart;\n let to = anchor.charStart + anchor.count - 1;\n for (let r = ri - 1; r >= 0; r--) {\n const run = layout.runs[r];\n if (isZero(run.rect)) continue;\n if (run.frame !== anchor.frame) break;\n if (!overlapV(run.rect.bottom, run.rect.top, bottom, top)) break;\n from = run.charStart;\n }\n for (let r = ri + 1; r < layout.runs.length; r++) {\n const run = layout.runs[r];\n if (isZero(run.rect)) continue;\n if (run.frame !== anchor.frame) break;\n if (!overlapV(run.rect.bottom, run.rect.top, bottom, top)) break;\n to = run.charStart + run.count - 1;\n }\n return [from, to];\n}\n\n/**\n * A single glyph's oriented cell in page space, or null for degenerate\n * glyphs — the anchor for caret placement at a selection boundary.\n */\nexport function textGlyphQuad(layout: PageTextLayout, glyph: number): PdfQuad | null {\n const g = layout.glyphs[glyph];\n if (!g || isEmpty(g.flags)) return null;\n const b = g.loose;\n if (b.right <= b.left || b.top <= b.bottom) return null;\n const run = layout.runs.find((r) => glyph >= r.charStart && glyph < r.charStart + r.count);\n const f = layout.frames[run?.frame ?? 0];\n return quadOfFrameRect(f, run?.frame ?? 0, b);\n}\n\ninterface SubRun {\n rect: PdfRect;\n charCount: number;\n fontSize?: number;\n frame: number;\n /** Baseline x of the FIRST/LAST glyph in sequence order (frame space) —\n * the reading-direction signal. */\n firstX: number;\n lastX: number;\n}\n\n/**\n * Merged visual-line segments for the half-open char range\n * `[charStart, charStart + charCount)` — THE canonical segmentation. Chars\n * outside the layout are ignored.\n */\nexport function textSegmentsForRange(\n layout: PageTextLayout,\n charStart: number,\n charCount: number,\n): PdfTextSegment[] {\n if (charCount <= 0 || layout.glyphs.length === 0) return [];\n const lo = Math.max(0, charStart);\n const hi = Math.min(layout.glyphs.length - 1, charStart + charCount - 1);\n if (hi < lo) return [];\n const subRuns: SubRun[] = [];\n\n for (const run of layout.runs) {\n const runEnd = run.charStart + run.count - 1;\n if (runEnd < lo || run.charStart > hi) continue;\n const s = Math.max(lo, run.charStart);\n const e = Math.min(hi, runEnd);\n\n let left = Infinity;\n let right = -Infinity;\n let bottom = Infinity;\n let top = -Infinity;\n let charCountAcc = 0;\n let widthSum = 0;\n let prevRight = -Infinity;\n let firstX = 0;\n let lastX = 0;\n const flush = () => {\n if (charCountAcc > 0 && left !== Infinity) {\n subRuns.push({\n rect: { left, bottom, right, top },\n charCount: charCountAcc,\n fontSize: run.fontSize,\n frame: run.frame,\n firstX,\n lastX,\n });\n }\n left = Infinity;\n right = -Infinity;\n bottom = Infinity;\n top = -Infinity;\n charCountAcc = 0;\n widthSum = 0;\n prevRight = -Infinity;\n };\n\n for (let ci = s; ci <= e; ci++) {\n const g = layout.glyphs[ci];\n if (isEmpty(g.flags)) continue;\n const b = g.loose;\n if (charCountAcc > 0 && prevRight > -Infinity) {\n const avg = widthSum / charCountAcc;\n if (avg > 0 && Math.abs(b.left - prevRight) > CHAR_DISTANCE_FACTOR * avg) flush();\n }\n const centerX = (b.left + b.right) / 2;\n if (charCountAcc === 0) firstX = centerX;\n lastX = centerX;\n left = Math.min(left, b.left);\n right = Math.max(right, b.right);\n bottom = Math.min(bottom, b.bottom);\n top = Math.max(top, b.top);\n charCountAcc++;\n widthSum += b.right - b.left;\n prevRight = b.right;\n }\n flush();\n }\n\n return mergeAdjacentSubRuns(subRuns).map((m) => materializeSegment(layout, m));\n}\n\ninterface MergedSubRun {\n rect: PdfRect;\n frame: number;\n firstX: number;\n lastX: number;\n}\n\nfunction mergeAdjacentSubRuns(runs: SubRun[]): MergedSubRun[] {\n const out: MergedSubRun[] = [];\n let prev: SubRun | null = null;\n let cur: MergedSubRun | null = null;\n for (const run of runs) {\n // Frames are canonical per cluster, so index equality IS the \"same\n // orientation\" test — every participant was projected through the SAME\n // frame, keeping merged coordinates commensurable.\n if (prev && cur && prev.frame === run.frame && shouldMerge(prev, run)) {\n cur = {\n rect: {\n left: Math.min(cur.rect.left, run.rect.left),\n bottom: Math.min(cur.rect.bottom, run.rect.bottom),\n right: Math.max(cur.rect.right, run.rect.right),\n top: Math.max(cur.rect.top, run.rect.top),\n },\n frame: cur.frame,\n firstX: cur.firstX,\n lastX: run.lastX,\n };\n } else {\n if (cur) out.push(cur);\n cur = { rect: run.rect, frame: run.frame, firstX: run.firstX, lastX: run.lastX };\n }\n prev = run;\n }\n if (cur && cur.rect.right > cur.rect.left && cur.rect.top > cur.rect.bottom) out.push(cur);\n return out;\n}\n\n/** Segment quad for a frame-local rect (frame 0: the rect's own corners,\n * no float round-trip). Slot order US, UE, LS, LE; frame is y-up, so the\n * upper corners sit at the frame TOP. */\nfunction quadOfFrameRect(f: TextLayoutFrame, frameIndex: number, r: PdfRect): PdfQuad {\n if (frameIndex === 0) {\n return {\n p1: { x: r.left, y: r.top },\n p2: { x: r.right, y: r.top },\n p3: { x: r.left, y: r.bottom },\n p4: { x: r.right, y: r.bottom },\n };\n }\n return {\n p1: fromFrame(f, { x: r.left, y: r.top }),\n p2: fromFrame(f, { x: r.right, y: r.top }),\n p3: fromFrame(f, { x: r.left, y: r.bottom }),\n p4: fromFrame(f, { x: r.right, y: r.bottom }),\n };\n}\n\nfunction materializeSegment(layout: PageTextLayout, m: MergedSubRun): PdfTextSegment {\n const frame = layout.frames[m.frame];\n const quad = quadOfFrameRect(frame, m.frame, m.rect);\n const rect =\n m.frame === 0\n ? m.rect\n : {\n left: Math.min(quad.p1.x, quad.p2.x, quad.p3.x, quad.p4.x),\n bottom: Math.min(quad.p1.y, quad.p2.y, quad.p3.y, quad.p4.y),\n right: Math.max(quad.p1.x, quad.p2.x, quad.p3.x, quad.p4.x),\n top: Math.max(quad.p1.y, quad.p2.y, quad.p3.y, quad.p4.y),\n };\n return { quad, rect, advance: m.lastX >= m.firstX ? 1 : -1 };\n}\n\nfunction shouldMerge(a: SubRun, b: SubRun): boolean {\n if (a.fontSize != null && b.fontSize != null && a.fontSize > 0 && b.fontSize > 0) {\n const ratio = Math.max(a.fontSize, b.fontSize) / Math.min(a.fontSize, b.fontSize);\n if (ratio > FONT_SIZE_RATIO_THRESHOLD) return false;\n }\n if (verticalOverlap(a.rect, b.rect) < VERTICAL_OVERLAP_THRESHOLD) return false;\n const aw = (a.rect.right - a.rect.left) / a.charCount;\n const bw = (b.rect.right - b.rect.left) / b.charCount;\n const aL = a.rect.left - aw;\n const aR = a.rect.right + aw;\n const bL = b.rect.left - bw;\n const bR = b.rect.right + bw;\n return aL < bR && aR > bL;\n}\n\nfunction verticalOverlap(a: PdfRect, b: PdfRect): number {\n const ah = a.top - a.bottom;\n const bh = b.top - b.bottom;\n if (ah <= 0 || bh <= 0) return 0;\n const u = Math.max(a.top, b.top) - Math.min(a.bottom, b.bottom);\n if (u === ah || u === bh) return 1;\n const i = Math.max(0, Math.min(a.top, b.top) - Math.max(a.bottom, b.bottom));\n return i / u;\n}\n\nconst isZero = (r: PdfRect): boolean => r.right === r.left && r.top === r.bottom;\n\nfunction overlapV(bottom1: number, top1: number, bottom2: number, top2: number): boolean {\n const u = Math.max(top1, top2) - Math.min(bottom1, bottom2);\n if (u === 0) return false;\n const i = Math.max(0, Math.min(top1, top2) - Math.max(bottom1, bottom2));\n return i / u >= LINE_OVERLAP_THRESHOLD;\n}\n","import type { PageGeometrySnapshot } from '../dto/PageGeometrySnapshot';\nimport type { PdfRect } from '../geometry/primitives';\nimport { buildPageTextLayout, textSegmentsForRange, type PdfTextSegment } from '../text/layout';\n\n/**\n * Match-range → canonical visual-line segments. Thin wrappers over the ONE\n * text layout (`src/text/layout.ts`) — search owns matching and cursors,\n * never segmentation, so a match highlights exactly like a selection of the\n * same characters. No frame or merge logic lives here.\n */\n\n/** Canonical segments for `[charStart, charStart + charCount)`. */\nexport function searchSegmentsForRange(\n snapshot: PageGeometrySnapshot,\n charStart: number,\n charCount: number,\n): PdfTextSegment[] {\n return textSegmentsForRange(buildPageTextLayout(snapshot), charStart, charCount);\n}\n\n/** The segments' AABBs — for consumers that genuinely want boxes. */\nexport function searchRectsForRange(\n snapshot: PageGeometrySnapshot,\n charStart: number,\n charCount: number,\n): PdfRect[] {\n return searchSegmentsForRange(snapshot, charStart, charCount).map((s) => s.rect);\n}\n","import type { DocumentManifest } from '../dto/DocumentManifest';\nimport { foldText } from './fold';\nimport type { SearchQuery } from './types';\n\n/**\n * The search CONTENT EPOCH: a deterministic fingerprint of everything a\n * search result depends on — page order/structure (`layoutVersion`) and\n * each page's text content (`contentVersion`), nothing else. Annotation\n * and metadata churn deliberately do NOT move it, so cached search\n * responses in a collaborative document survive comment storms.\n *\n * Both sides compute it from the manifest they already hold: the client\n * to mint versioned search URLs, the server to validate them (mismatch →\n * NotFound, the standard stale-versioned-read signal). FNV-1a 64-bit —\n * dependency-free and stable; not cryptographic, and doesn't need to be:\n * an adversary can only vary his OWN authorized query results.\n */\nexport function searchContentEpoch(manifest: DocumentManifest): string {\n let input = `${manifest.layoutVersion}`;\n for (const page of manifest.pages) {\n input += `|${page.state.pageObjectNumber}:${page.cache.contentVersion}`;\n }\n return fnv1a64(input);\n}\n\nconst FNV_OFFSET = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst MASK_64 = 0xffffffffffffffffn;\n\nfunction fnv1a64(input: string): string {\n let hash = FNV_OFFSET;\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i));\n hash = (hash * FNV_PRIME) & MASK_64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\n/**\n * Canonicalize a query for CACHE KEYING: default-fold literal queries are\n * pre-folded (\"Café\", \"café\" and \"CAFE\" are the same search, so they\n * should be the same cache entry). Semantics are unchanged — the fold is\n * idempotent and exactly what the matcher applies to the needle anyway.\n * Case- or diacritic-sensitive literals and regex patterns pass through\n * untouched (their raw form IS the query).\n */\nexport function canonicalSearchQuery(query: SearchQuery): SearchQuery {\n if (query.regex || query.matchCase || query.matchDiacritics) return query;\n const canonical: SearchQuery = { text: foldText(query.text).folded };\n if (query.wholeWord) canonical.wholeWord = true;\n return canonical;\n}\n","import type { PdfBits } from './types';\n\n/**\n * ISO 32000 user-access permission bit positions, expressed as integer\n * masks. Bit numbers in the spec are 1-indexed, so bit 3 = `1 << 2`.\n *\n * Bits 1, 2, 7, 8, and 13+ are reserved and not surfaced here.\n */\nexport const PDF_BITS = {\n /** Bit 3 — print the document. */\n PRINT: 1 << 2,\n /** Bit 4 — modify content streams. */\n MODIFY: 1 << 3,\n /** Bit 5 — copy/extract text and graphics. */\n COPY: 1 << 4,\n /** Bit 6 — annotate + fill forms (+ modify form fields with bit 4). */\n ANNOTATE_FILL: 1 << 5,\n /** Bit 9 — fill existing forms (even if bit 6 is clear). */\n FILL_FORMS: 1 << 8,\n /** Bit 10 — accessibility extraction (deprecated in PDF 2.0). */\n ACCESSIBILITY: 1 << 9,\n /** Bit 11 — assemble document (insert/rotate/delete pages, outline). */\n ASSEMBLE: 1 << 10,\n /** Bit 12 — high-quality print (refines bit 3). */\n PRINT_HIGH: 1 << 11,\n} as const;\n\n/**\n * Decode a raw PDFium permission integer into a typed boolean view.\n *\n * `null` input (the documents row column is nullable until probed)\n * yields all-false bits — i.e., a maximally restrictive interpretation.\n * That keeps `pdf.permissions` expansion safe on unprobed documents.\n */\nexport function decodePdfBits(raw: number | null): PdfBits {\n if (raw === null) {\n return {\n bit3: false,\n bit4: false,\n bit5: false,\n bit6: false,\n bit9: false,\n bit10: false,\n bit11: false,\n bit12: false,\n };\n }\n return {\n bit3: (raw & PDF_BITS.PRINT) !== 0,\n bit4: (raw & PDF_BITS.MODIFY) !== 0,\n bit5: (raw & PDF_BITS.COPY) !== 0,\n bit6: (raw & PDF_BITS.ANNOTATE_FILL) !== 0,\n bit9: (raw & PDF_BITS.FILL_FORMS) !== 0,\n bit10: (raw & PDF_BITS.ACCESSIBILITY) !== 0,\n bit11: (raw & PDF_BITS.ASSEMBLE) !== 0,\n bit12: (raw & PDF_BITS.PRINT_HIGH) !== 0,\n };\n}\n","import type { DocCapability, PdfBits } from './types';\n\n/**\n * Typed capability constants for customer-side JWT minting.\n *\n * The shape mirrors the dotted capability name so it reads naturally:\n * caps.doc.text.copy() // \"doc.text.copy\"\n * caps.doc.download() // \"doc.download\"\n * caps.doc.download.flattened() // \"doc.download.flattened\"\n * caps.doc.print.high() // \"doc.print.high\"\n *\n * Each leaf is a function returning the literal string (as `const`) so\n * TypeScript catches typos at the call site. Wrappers like `download`\n * and `print` are `Object.assign`'d to be callable AND carry child\n * properties for the refinement capabilities.\n */\nexport const caps = {\n doc: {\n open: () => 'doc.open' as const,\n render: () => 'doc.render' as const,\n text: {\n select: () => 'doc.text.select' as const,\n copy: () => 'doc.text.copy' as const,\n search: () => 'doc.text.search' as const,\n },\n content: {\n copy: () => 'doc.content.copy' as const,\n },\n download: Object.assign(() => 'doc.download' as const, {\n flattened: () => 'doc.download.flattened' as const,\n }),\n print: Object.assign(() => 'doc.print' as const, {\n high: () => 'doc.print.high' as const,\n }),\n pages: {\n modify: () => 'doc.pages.modify' as const,\n assemble: () => 'doc.pages.assemble' as const,\n },\n forms: {\n read: () => 'doc.forms.read' as const,\n fill: () => 'doc.forms.fill' as const,\n modify: () => 'doc.forms.modify' as const,\n },\n annotate: {\n read: () => 'doc.annotate.read' as const,\n modify: () => 'doc.annotate.modify' as const,\n },\n metadata: {\n modify: () => 'doc.metadata.modify' as const,\n },\n attachments: {\n modify: () => 'doc.attachments.modify' as const,\n },\n redact: () => 'doc.redact' as const,\n },\n} as const;\n\n/**\n * Builder factory for collab scope filters. Each entity:action pair\n * gets a sub-object with the four filter constructors.\n *\n * collab.annotations.create.self() → \"annotations:create:self\"\n * collab.annotations.create.group(\"legal\") → \"annotations:create:group=legal\"\n * collab.annotations.update.group(\"4\") → \"annotations:update:group=4\"\n * collab.annotations.delete.createdBy(\"u-7\") → \"annotations:delete:createdBy=u-7\"\n * collab.annotations.setGroup.group(\"legal\") → \"annotations:set-group:group=legal\"\n * collab.annotations.all.all() → \"annotations:*:all\" (action wildcard)\n *\n * On create, the filter is evaluated against the caller's own identity\n * (no impersonation), so `:self` and `:all` trivially pass; `:group=X`\n * is the meaningful filter — it constrains creation to callers whose\n * default group is X.\n */\nexport const collab = {\n annotations: {\n create: makeFilterBuilder('annotations', 'create'),\n update: makeFilterBuilder('annotations', 'update'),\n delete: makeFilterBuilder('annotations', 'delete'),\n setGroup: makeSetGroupBuilder(),\n /** Action wildcard — matches create, update, delete, AND set-group with the given filter. */\n all: makeFilterBuilder('annotations', '*'),\n },\n} as const;\n\ninterface FilterBuilder {\n all(): string;\n self(): string;\n createdBy(userId: string): string;\n group(groupId: string): string;\n}\n\nfunction makeFilterBuilder(entity: string, action: string): FilterBuilder {\n return {\n all: () => `${entity}:${action}:all`,\n self: () => `${entity}:${action}:self`,\n createdBy: (userId: string) => `${entity}:${action}:createdBy=${userId}`,\n group: (groupId: string) => `${entity}:${action}:group=${groupId}`,\n };\n}\n\n/**\n * `set-group` is an authority filter, not a per-record collab filter:\n * only `:all` and `:group=X` are meaningful (assign-to-any vs\n * assign-to-X). The builder exposes exactly those two — a typo at JWT\n * mint time is caught by the compiler instead of producing a JWT that\n * fails at verify.\n */\ninterface SetGroupBuilder {\n all(): string;\n group(groupId: string): string;\n}\n\nfunction makeSetGroupBuilder(): SetGroupBuilder {\n return {\n all: () => 'annotations:set-group:all',\n group: (groupId: string) => `annotations:set-group:group=${groupId}`,\n };\n}\n\n/**\n * Builder for the `pdf.permissions` virtual scope. Returns the literal\n * string; provided as a helper for parity with caps/collab in JWT\n * construction code.\n */\nexport const pdfPermissions = (): 'pdf.permissions' => 'pdf.permissions';\n\n/**\n * Materialise `pdf.permissions` into the concrete capability list it\n * would expand to under the given PDF bit configuration.\n *\n * Useful when the customer wants to start from PDF defaults and then\n * subtract specific capabilities — easier to build the JWT scope array\n * by filtering an explicit list than by composing virtual + denials.\n *\n * const defaults = materializePdfPermissions(pdfBits);\n * const scope = [\n * ...defaults.filter(s => s !== 'doc.text.copy'),\n * 'doc.download',\n * ];\n *\n * IMPORTANT: this MUST stay in sync with `addPdfPermissions` inside\n * resolver.ts. A test pins them together.\n */\nexport function materializePdfPermissions(b: PdfBits): DocCapability[] {\n const out = new Set<DocCapability>();\n\n // Always — pdf.permissions means \"give me a working session\"\n out.add('doc.open');\n out.add('doc.render');\n // Reading existing annotations and form values is unconditional —\n // PDF bit 6 governs writes, not visibility.\n out.add('doc.annotate.read');\n out.add('doc.forms.read');\n\n if (b.bit5) {\n out.add('doc.text.select');\n out.add('doc.text.copy');\n out.add('doc.text.search');\n out.add('doc.content.copy');\n }\n if (b.bit3) out.add('doc.print');\n if (b.bit12 && b.bit3) out.add('doc.print.high');\n if (b.bit4) {\n out.add('doc.pages.modify');\n out.add('doc.redact');\n out.add('doc.metadata.modify');\n out.add('doc.attachments.modify');\n }\n if (b.bit11) out.add('doc.pages.assemble');\n if (b.bit6) out.add('doc.annotate.modify');\n if (b.bit6 || b.bit9) out.add('doc.forms.fill');\n if (b.bit6 && b.bit4) out.add('doc.forms.modify');\n\n return [...out];\n}\n"],"mappings":";;;;;;;AA0DA,MAAa,yBAAyB,QAAiC;CACrE,MAAM,OAAO,OAAwB,MAAO,KAAM,IAAI,OAAS;CAC/D,MAAM,SAAS,IAAI,CAAC,IAAI,QAAQ,IAAI,CAAC,IAAI,SAAS,IAAI,CAAC,IAAI,SAAS;CACpE,OAAO;EACL;EACA,SAAS,IAAI,CAAC;EACd,sBAAsB,IAAI,CAAC;EAC3B;EACA,QAAQ,IAAI,CAAC,MAAM,WAAW,UAAU,WAAW,SAAS,QAAQ;EACpE,mBAAmB,IAAI,CAAC;EACxB,oBAAoB,IAAI,CAAC;EACzB,oBAAoB,IAAI,CAAC;EACzB,iBAAiB,IAAI,EAAE;EACvB,mBAAmB,IAAI,EAAE;EACzB,UAAU,IAAI,EAAE;EAChB,WAAW,IAAI,EAAE;CACnB;AACF;;;ACsCA,SAAgB,sBACd,QACA,YACiB;CACjB,OAAO;EACL,GAAG;EACH,MAAM,UAAU,QAAsB;GACpC,IAAI,OAAO,SAAS,eAAe,OAAO,QAAQ,eAAe,CAAC,IAAI,i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