@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
@@ -1 +0,0 @@
1
- {"version":3,"file":"builders-DOjcKDWQ.js","names":[],"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,CA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EACL,WAAW,GAAG,OAAO,GAAG,OAAO;EAC/B,YAAY,GAAG,OAAO,GAAG,OAAO;EAChC,YAAY,WAAmB,GAAG,OAAO,GAAG,OAAO,aAAa;EAChE,QAAQ,YAAoB,GAAG,OAAO,GAAG,OAAO,SAAS;CAC3D;AACF;AAcA,SAAS,sBAAuC;CAC9C,OAAO;EACL,WAAW;EACX,QAAQ,YAAoB,+BAA+B;CAC7D;AACF;;;;;;AAOA,MAAa,uBAA0C;;;;;;;;;;;;;;;;;;AAmBvD,SAAgB,0BAA0B,GAA6B;CACrE,MAAM,sBAAM,IAAI,IAAmB;CAGnC,IAAI,IAAI,UAAU;CAClB,IAAI,IAAI,YAAY;CAGpB,IAAI,IAAI,mBAAmB;CAC3B,IAAI,IAAI,gBAAgB;CAExB,IAAI,EAAE,MAAM;EACV,IAAI,IAAI,iBAAiB;EACzB,IAAI,IAAI,eAAe;EACvB,IAAI,IAAI,iBAAiB;EACzB,IAAI,IAAI,kBAAkB;CAC5B;CACA,IAAI,EAAE,MAAM,IAAI,IAAI,WAAW;CAC/B,IAAI,EAAE,SAAS,EAAE,MAAM,IAAI,IAAI,gBAAgB;CAC/C,IAAI,EAAE,MAAM;EACV,IAAI,IAAI,kBAAkB;EAC1B,IAAI,IAAI,YAAY;EACpB,IAAI,IAAI,qBAAqB;EAC7B,IAAI,IAAI,wBAAwB;CAClC;CACA,IAAI,EAAE,OAAO,IAAI,IAAI,oBAAoB;CACzC,IAAI,EAAE,MAAM,IAAI,IAAI,qBAAqB;CACzC,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,IAAI,gBAAgB;CAC9C,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,IAAI,kBAAkB;CAEhD,OAAO,CAAC,GAAG,GAAG;AAChB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolver-CHG4waXL.js","names":[],"sources":["../src/auth/scope/errors.ts","../src/auth/scope/parser.ts","../src/auth/scope/resolver.ts"],"sourcesContent":["/**\n * Thrown by {@link parseScope} / {@link validateScopeArray} when a scope\n * string does not match any known grammar (capability, collab, virtual,\n * or wildcard).\n *\n * Carries the offending scope verbatim so route/JWT-layer error\n * handlers can echo it to the customer.\n */\nexport class InvalidScope extends Error {\n constructor(\n public readonly scope: string,\n reason: string,\n ) {\n super(`invalid scope \"${scope}\": ${reason}`);\n this.name = 'InvalidScope';\n }\n}\n\n/**\n * Thrown by route guards and engine-local enforcement when a capability\n * or collab action is denied for the current request/handle.\n *\n * `required` names what the caller needed (e.g., \"doc.render\" or\n * \"annotations:update\"). `context` is an optional label such as \"local\"\n * or \"/v1/docs/.../pages/2/render\".\n */\nexport class PermissionDenied extends Error {\n constructor(\n public readonly required: string,\n public readonly context?: string,\n ) {\n super(`permission denied${context ? ` (${context})` : ''}: ${required}`);\n this.name = 'PermissionDenied';\n }\n}\n\n/**\n * Thrown at engine-local open time when the supplied scope includes\n * collab filters (`:self`, `:group=...`) but the identity claims needed\n * to resolve them are missing. Fails loudly at open so the configuration\n * mistake is visible immediately instead of producing silent denies at\n * every annotation mutation.\n */\nexport class MissingIdentity extends Error {\n constructor(scope: string) {\n super(`scope \"${scope}\" requires identity claims (user_id and/or groups)`);\n this.name = 'MissingIdentity';\n }\n}\n","import { InvalidScope } from './errors';\nimport type { CollabAction, CollabFilter, DocCapability, ParsedScope } from './types';\n\n/**\n * Closed set of recognized capability strings. Membership is the\n * authoritative source of truth — adding a new capability requires\n * extending the `DocCapability` union AND adding it here. The parser\n * rejects anything outside this set.\n *\n * Removed legacy names (e.g., `doc.read`, `doc.edit-pages`, `doc.save`)\n * are deliberately absent so any JWT carrying them fails at verify\n * time with a clear error.\n */\nconst KNOWN_CAPABILITIES: ReadonlySet<DocCapability> = new Set([\n 'doc.open',\n 'doc.render',\n 'doc.text.select',\n 'doc.text.copy',\n 'doc.text.search',\n 'doc.content.copy',\n 'doc.download',\n 'doc.download.flattened',\n 'doc.print',\n 'doc.print.high',\n 'doc.pages.modify',\n 'doc.pages.assemble',\n 'doc.forms.read',\n 'doc.forms.fill',\n 'doc.forms.modify',\n 'doc.forms.submit',\n 'doc.annotate.read',\n 'doc.annotate.modify',\n 'doc.metadata.modify',\n 'doc.attachments.modify',\n 'doc.redact',\n]);\n\n/**\n * Parse a single scope string into a structured `ParsedScope`.\n *\n * Recognised shapes:\n * - `\"*\"` → wildcard\n * - `\"pdf.permissions\"` → virtual (expands at resolve time)\n * - `\"a.b.c...\"` (dotted) → capability\n * - `\"entity:action:filter\"` (colons) → collab\n *\n * Throws {@link InvalidScope} for any string that fails to match one of\n * those shapes, or whose capability/entity/action/filter is not in the\n * closed enum.\n */\nexport function parseScope(raw: string): ParsedScope {\n if (raw === '*') return { kind: 'wildcard' };\n if (raw === 'pdf.permissions') return { kind: 'virtual', name: 'pdf.permissions' };\n if (raw.includes(':')) return parseCollab(raw);\n return parseCapability(raw);\n}\n\n/**\n * Validate every entry in a scope array by attempting to parse it.\n * Throws on the first invalid string. Discards the parse output —\n * callers re-parse at resolution time to keep the array as the\n * authoritative payload.\n */\nexport function validateScopeArray(raw: ReadonlyArray<string>): void {\n for (const s of raw) parseScope(s);\n}\n\nfunction parseCollab(raw: string): ParsedScope {\n // Split on the FIRST two colons only. Filter values may contain\n // colons (UUIDs with `urn:uuid:...`, subject ids like `auth0|user:1`).\n const idx1 = raw.indexOf(':');\n const idx2 = raw.indexOf(':', idx1 + 1);\n if (idx1 === -1 || idx2 === -1) {\n throw new InvalidScope(raw, 'collab scope requires entity:action:filter');\n }\n const entity = raw.slice(0, idx1);\n const action = raw.slice(idx1 + 1, idx2);\n const filterStr = raw.slice(idx2 + 1);\n\n if (entity !== 'annotations') {\n throw new InvalidScope(raw, `unknown collab entity: ${entity}`);\n }\n if (\n action !== 'create' &&\n action !== 'update' &&\n action !== 'delete' &&\n action !== 'set-group' &&\n action !== '*'\n ) {\n throw new InvalidScope(raw, `unknown collab action: ${action}`);\n }\n const filter = parseFilter(filterStr, raw);\n\n // `set-group` is a group-assignment authority, not a per-record collab\n // filter. The only meaningful filter values are `all` (assign to any\n // group) and `group=X` (assign to group X). `:self` and `:createdBy=Y`\n // can't be sensibly applied to \"what group is this annotation in\", so\n // we reject them at parse time rather than silently always-denying.\n if (action === 'set-group' && (filter.kind === 'self' || filter.kind === 'createdBy')) {\n throw new InvalidScope(\n raw,\n `set-group only supports :all or :group=<id> filters (got :${filter.kind})`,\n );\n }\n\n return {\n kind: 'collab',\n entity,\n action: action as CollabAction | '*',\n filter,\n };\n}\n\nfunction parseFilter(s: string, raw: string): CollabFilter {\n if (s === 'all') return { kind: 'all' };\n if (s === 'self') return { kind: 'self' };\n if (s.startsWith('createdBy=')) {\n const v = s.slice('createdBy='.length);\n if (!v) throw new InvalidScope(raw, 'createdBy= requires a value');\n return { kind: 'createdBy', userId: v };\n }\n if (s.startsWith('group=')) {\n const v = s.slice('group='.length);\n if (!v) throw new InvalidScope(raw, 'group= requires a value');\n return { kind: 'group', groupId: v };\n }\n throw new InvalidScope(raw, `unknown filter: ${s}`);\n}\n\n// Capability shape: lowercase dotted segments, e.g. \"doc.text.copy\".\n// Validates shape first, then membership in the closed set.\nconst CAPABILITY_SHAPE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$/;\n\nfunction parseCapability(raw: string): ParsedScope {\n if (!CAPABILITY_SHAPE.test(raw)) {\n throw new InvalidScope(raw, 'invalid capability name shape');\n }\n if (!KNOWN_CAPABILITIES.has(raw as DocCapability)) {\n throw new InvalidScope(raw, `unknown capability: ${raw}`);\n }\n return { kind: 'capability', name: raw as DocCapability };\n}\n","import { parseScope } from './parser';\nimport type {\n CollabAction,\n CollabFilter,\n DocCapability,\n IdentityClaims,\n ParsedScope,\n PdfBits,\n} from './types';\n\n/**\n * Resolved collab subject — the per-record identity bits used to test\n * collab filters against. Sourced from the target record's stored\n * `/EMBD_Metadata/UserID` and `/GroupID` at mutation time.\n */\nexport interface CollabTarget {\n userId?: string;\n groupId?: string;\n}\n\n/**\n * True iff the given capability is granted by the scope array plus the\n * PDF bits visible via `pdf.permissions` expansion.\n *\n * Wildcard `*` short-circuits to true. Anything not explicitly granted\n * (or expanded from `pdf.permissions`) is denied.\n */\nexport function checkCapability(\n capability: DocCapability,\n rawScope: ReadonlyArray<string>,\n pdfBits: PdfBits,\n): boolean {\n const parsed = rawScope.map(parseScope);\n if (parsed.some((s) => s.kind === 'wildcard')) return true;\n return expandedCapabilities(parsed, pdfBits).has(capability);\n}\n\n/**\n * True iff the scope grants AT LEAST ONE of `capabilities`. Convenience\n * for routes like `/text` (`doc.text.copy` OR `doc.text.search`) and\n * `/geometry` (`doc.text.select` OR `doc.text.search`).\n */\nexport function checkAnyCapability(\n capabilities: ReadonlyArray<DocCapability>,\n rawScope: ReadonlyArray<string>,\n pdfBits: PdfBits,\n): boolean {\n return capabilities.some((c) => checkCapability(c, rawScope, pdfBits));\n}\n\n/**\n * True iff the scope grants the collab action against the target record.\n *\n * Narrowing model. For each action independently:\n * 1. wildcard `*` → allow (global escape hatch)\n * 2. if any collab scope applies to this action → NARROW: only those\n * collab filters decide. If none match the target, deny — even if\n * `doc.annotate.modify` is also present. This is what makes\n * `[modify, update:self]` correctly mean \"edit own only\" rather\n * than \"edit anyone via modify-bypass.\"\n * 3. otherwise, if `doc.annotate.modify` is present → allow. This is\n * the broad PDF-bit-derived default for create/update/delete when\n * no per-action collab filter has been written.\n * 4. otherwise → deny.\n *\n * For create: `target` should be built by the caller from JWT identity\n * (`{ userId: caller.user_id, groupId: caller.group_id }`). `:self` and\n * `:all` then trivially pass; `:group=X` is the meaningful filter (only\n * matches when the caller's default group is X).\n *\n * For update / delete: `target` is the existing row's owner.\n */\nexport function checkCollab(\n action: CollabAction,\n target: CollabTarget,\n rawScope: ReadonlyArray<string>,\n identity: IdentityClaims,\n pdfBits: PdfBits,\n): boolean {\n const parsed = rawScope.map(parseScope);\n if (parsed.some((s) => s.kind === 'wildcard')) return true;\n\n const applicableCollab = parsed.filter(\n (s): s is Extract<ParsedScope, { kind: 'collab' }> =>\n s.kind === 'collab' &&\n s.entity === 'annotations' &&\n (s.action === action || s.action === '*'),\n );\n\n if (applicableCollab.length > 0) {\n // Narrow: presence of any applicable collab scope shadows\n // `modify`-as-default for this action.\n return applicableCollab.some((s) => filterMatches(s.filter, target, identity));\n }\n\n // No collab scope for this action — fall back to the broad default.\n return expandedCapabilities(parsed, pdfBits).has('doc.annotate.modify');\n}\n\n/**\n * Compute the full set of granted capabilities after expanding\n * `pdf.permissions` and applying implication rules.\n *\n * Implications applied:\n * - `doc.annotate.modify` implies `doc.annotate.read` (you can't\n * sensibly modify what you can't see).\n * - `doc.forms.modify` implies `doc.forms.fill` and `doc.forms.read`.\n * - `doc.forms.fill` implies `doc.forms.read`.\n * - any annotation collab scope implies `doc.annotate.read`, because\n * mutation routes need to see the target row to evaluate the\n * collab filter against its current owner.\n *\n * Does NOT short-circuit on wildcard — callers do that themselves\n * before calling this. Returning the expanded set is useful for the\n * `/access` response's `effectiveScope` and for advisory UI surfacing.\n */\nexport function expandedCapabilities(\n parsed: ReadonlyArray<ParsedScope>,\n pdfBits: PdfBits,\n): Set<DocCapability> {\n const out = new Set<DocCapability>();\n let hasAnnotationCollab = false;\n\n for (const s of parsed) {\n if (s.kind === 'capability') {\n out.add(s.name);\n } else if (s.kind === 'virtual' && s.name === 'pdf.permissions') {\n addPdfPermissions(out, pdfBits);\n } else if (s.kind === 'collab' && s.entity === 'annotations') {\n hasAnnotationCollab = true;\n }\n }\n\n // Implications (apply after the explicit additions above)\n if (out.has('doc.annotate.modify')) out.add('doc.annotate.read');\n if (out.has('doc.forms.modify')) {\n out.add('doc.forms.fill');\n out.add('doc.forms.read');\n }\n if (out.has('doc.forms.fill')) out.add('doc.forms.read');\n if (hasAnnotationCollab) out.add('doc.annotate.read');\n\n return out;\n}\n\n/**\n * Convenience wrapper: takes the raw scope array, parses each entry,\n * returns the expanded capability set. Exposed for the `/access`\n * endpoint and for the SDK helper that surfaces `effectiveScope`.\n */\nexport function expandRawScope(\n rawScope: ReadonlyArray<string>,\n pdfBits: PdfBits,\n): Set<DocCapability> {\n return expandedCapabilities(rawScope.map(parseScope), pdfBits);\n}\n\n/**\n * Test a single collab filter against a target record + the caller's\n * identity. Pure function — no side effects, no implicit rules.\n *\n * all → always matches\n * self → matches if identity.user_id === target.userId\n * createdBy=<X> → matches if target.userId === X\n * group=<X> → matches if target.groupId === X\n * AND identity.groups includes X\n *\n * The group-membership check on `group=X` prevents a token from\n * matching annotations in a group it doesn't belong to, even if the\n * target row carries that groupId.\n */\n/**\n * Authority to assign a specific groupId to an annotation.\n *\n * Set-group is decoupled from `doc.annotate.modify`. The reasoning:\n * capabilities like `modify` describe row access — what kind of write\n * you can do to which existing rows — and map to PDF permission bits.\n * Set-group is a cloud-only *assignment authority*: which destination\n * group can you put an annotation into? There is no PDF-bit\n * counterpart, so it doesn't inherit from `modify`.\n *\n * Resolution order:\n * 1. newGroupId === callerDefaultGroupId → true (no real reassignment\n * is happening; the annotation gets the caller's default group)\n * 2. wildcard `*` → true (global escape hatch)\n * 3. `annotations:set-group:all` → true\n * 4. `annotations:set-group:group=<newGroupId>` → true\n * 5. `annotations:*:all` or `annotations:*:group=<newGroupId>` → true\n * (action wildcard includes set-group)\n * 6. otherwise → false\n *\n * Note: independent from membership. A user with\n * `set-group:group=legal` can assign annotations to the legal group\n * even if they're not a member — that's the whole point.\n */\nexport function checkSetGroup(\n newGroupId: string,\n callerDefaultGroupId: string | undefined,\n rawScope: ReadonlyArray<string>,\n _pdfBits: PdfBits,\n): boolean {\n // No authority needed when the caller is assigning their default group.\n if (newGroupId === callerDefaultGroupId) return true;\n\n const parsed = rawScope.map(parseScope);\n if (parsed.some((s) => s.kind === 'wildcard')) return true;\n\n for (const s of parsed) {\n if (s.kind !== 'collab') continue;\n if (s.entity !== 'annotations') continue;\n if (s.action !== 'set-group' && s.action !== '*') continue;\n if (s.filter.kind === 'all') return true;\n if (s.filter.kind === 'group' && s.filter.groupId === newGroupId) return true;\n // :self and :createdBy are rejected at parse time for set-group, so\n // they never appear here. The action-wildcard path could carry those\n // filters legitimately for other actions — silently skip those, they\n // can't satisfy a set-group check.\n }\n return false;\n}\n\nexport function filterMatches(\n filter: CollabFilter,\n target: CollabTarget,\n id: IdentityClaims,\n): boolean {\n switch (filter.kind) {\n case 'all':\n return true;\n case 'self':\n return !!id.user_id && target.userId === id.user_id;\n case 'createdBy':\n return target.userId === filter.userId;\n case 'group':\n return target.groupId === filter.groupId && (id.groups?.includes(filter.groupId) ?? false);\n }\n}\n\n/**\n * Translate `pdf.permissions` (virtual scope) into the concrete\n * capabilities it represents under the current PDF bit configuration.\n *\n * Always adds `doc.open` and `doc.render` — these are cloud-only\n * capabilities with no PDF bit, but `pdf.permissions` is meant to be\n * the \"give the user a working session\" shorthand. Without them, a\n * token with just `['pdf.permissions']` would be useless.\n *\n * Reads are unconditional: ISO 32000 / Acrobat let any reader see\n * existing annotations and form values regardless of permission bits.\n * Bit 6 governs *writing*, not visibility.\n *\n * Bit-derived expansions follow ISO 32000:\n * bit 5 → doc.text.{select, copy, search}, doc.content.copy\n * bit 3 → doc.print\n * bit 12 → doc.print.high (requires bit 3 also set)\n * bit 4 → doc.pages.modify, doc.redact, doc.metadata.modify, doc.attachments.modify\n * bit 11 → doc.pages.assemble\n * bit 6 → doc.annotate.modify\n * bit 6/9 → doc.forms.fill\n * bit 6+4 → doc.forms.modify\n *\n * Note: this same expansion lives in builders.ts as\n * `materializePdfPermissions` for SDK-side use. The two MUST stay in\n * sync; a test in resolver.test.ts pins them together.\n */\nfunction addPdfPermissions(out: Set<DocCapability>, b: PdfBits): void {\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) {\n out.add('doc.annotate.modify');\n }\n if (b.bit6 || b.bit9) out.add('doc.forms.fill');\n if (b.bit6 && b.bit4) out.add('doc.forms.modify');\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,eAAb,cAAkC,MAAM;CACtC,YACE,OACA,QACA;EACA,MAAM,kBAAkB,MAAM,KAAK,QAAQ;EAH3B,KAAA,QAAA;EAIhB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YACE,UACA,SACA;EACA,MAAM,oBAAoB,UAAU,KAAK,QAAQ,KAAK,GAAG,IAAI,UAAU;EAHvD,KAAA,WAAA;EACA,KAAA,UAAA;EAGhB,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,OAAe;EACzB,MAAM,UAAU,MAAM,mDAAmD;EACzE,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;ACnCA,MAAM,qCAAiD,IAAI,IAAI;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;AAeD,SAAgB,WAAW,KAA0B;CACnD,IAAI,QAAQ,KAAK,OAAO,EAAE,MAAM,WAAW;CAC3C,IAAI,QAAQ,mBAAmB,OAAO;EAAE,MAAM;EAAW,MAAM;CAAkB;CACjF,IAAI,IAAI,SAAS,GAAG,GAAG,OAAO,YAAY,GAAG;CAC7C,OAAO,gBAAgB,GAAG;AAC5B;;;;;;;AAQA,SAAgB,mBAAmB,KAAkC;CACnE,KAAK,MAAM,KAAK,KAAK,WAAW,CAAC;AACnC;AAEA,SAAS,YA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;;;;;;;;;;;AA6BA,SAAS,kBAAkB,KAAyB,GAAkB;CAEpE,IAAI,IAAI,UAAU;CAClB,IAAI,IAAI,YAAY;CAGpB,IAAI,IAAI,mBAAmB;CAC3B,IAAI,IAAI,gBAAgB;CAExB,IAAI,EAAE,MAAM;EACV,IAAI,IAAI,iBAAiB;EACzB,IAAI,IAAI,eAAe;EACvB,IAAI,IAAI,iBAAiB;EACzB,IAAI,IAAI,kBAAkB;CAC5B;CACA,IAAI,EAAE,MAAM,IAAI,IAAI,WAAW;CAC/B,IAAI,EAAE,SAAS,EAAE,MAAM,IAAI,IAAI,gBAAgB;CAC/C,IAAI,EAAE,MAAM;EACV,IAAI,IAAI,kBAAkB;EAC1B,IAAI,IAAI,YAAY;EACpB,IAAI,IAAI,qBAAqB;EAC7B,IAAI,IAAI,wBAAwB;CAClC;CACA,IAAI,EAAE,OAAO,IAAI,IAAI,oBAAoB;CACzC,IAAI,EAAE,MACJ,IAAI,IAAI,qBAAqB;CAE/B,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,IAAI,gBAAgB;CAC9C,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,IAAI,kBAAkB;AAClD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolver-D-jumvgM.cjs","names":[],"sources":["../src/auth/scope/errors.ts","../src/auth/scope/parser.ts","../src/auth/scope/resolver.ts"],"sourcesContent":["/**\n * Thrown by {@link parseScope} / {@link validateScopeArray} when a scope\n * string does not match any known grammar (capability, collab, virtual,\n * or wildcard).\n *\n * Carries the offending scope verbatim so route/JWT-layer error\n * handlers can echo it to the customer.\n */\nexport class InvalidScope extends Error {\n constructor(\n public readonly scope: string,\n reason: string,\n ) {\n super(`invalid scope \"${scope}\": ${reason}`);\n this.name = 'InvalidScope';\n }\n}\n\n/**\n * Thrown by route guards and engine-local enforcement when a capability\n * or collab action is denied for the current request/handle.\n *\n * `required` names what the caller needed (e.g., \"doc.render\" or\n * \"annotations:update\"). `context` is an optional label such as \"local\"\n * or \"/v1/docs/.../pages/2/render\".\n */\nexport class PermissionDenied extends Error {\n constructor(\n public readonly required: string,\n public readonly context?: string,\n ) {\n super(`permission denied${context ? ` (${context})` : ''}: ${required}`);\n this.name = 'PermissionDenied';\n }\n}\n\n/**\n * Thrown at engine-local open time when the supplied scope includes\n * collab filters (`:self`, `:group=...`) but the identity claims needed\n * to resolve them are missing. Fails loudly at open so the configuration\n * mistake is visible immediately instead of producing silent denies at\n * every annotation mutation.\n */\nexport class MissingIdentity extends Error {\n constructor(scope: string) {\n super(`scope \"${scope}\" requires identity claims (user_id and/or groups)`);\n this.name = 'MissingIdentity';\n }\n}\n","import { InvalidScope } from './errors';\nimport type { CollabAction, CollabFilter, DocCapability, ParsedScope } from './types';\n\n/**\n * Closed set of recognized capability strings. Membership is the\n * authoritative source of truth — adding a new capability requires\n * extending the `DocCapability` union AND adding it here. The parser\n * rejects anything outside this set.\n *\n * Removed legacy names (e.g., `doc.read`, `doc.edit-pages`, `doc.save`)\n * are deliberately absent so any JWT carrying them fails at verify\n * time with a clear error.\n */\nconst KNOWN_CAPABILITIES: ReadonlySet<DocCapability> = new Set([\n 'doc.open',\n 'doc.render',\n 'doc.text.select',\n 'doc.text.copy',\n 'doc.text.search',\n 'doc.content.copy',\n 'doc.download',\n 'doc.download.flattened',\n 'doc.print',\n 'doc.print.high',\n 'doc.pages.modify',\n 'doc.pages.assemble',\n 'doc.forms.read',\n 'doc.forms.fill',\n 'doc.forms.modify',\n 'doc.forms.submit',\n 'doc.annotate.read',\n 'doc.annotate.modify',\n 'doc.metadata.modify',\n 'doc.attachments.modify',\n 'doc.redact',\n]);\n\n/**\n * Parse a single scope string into a structured `ParsedScope`.\n *\n * Recognised shapes:\n * - `\"*\"` → wildcard\n * - `\"pdf.permissions\"` → virtual (expands at resolve time)\n * - `\"a.b.c...\"` (dotted) → capability\n * - `\"entity:action:filter\"` (colons) → collab\n *\n * Throws {@link InvalidScope} for any string that fails to match one of\n * those shapes, or whose capability/entity/action/filter is not in the\n * closed enum.\n */\nexport function parseScope(raw: string): ParsedScope {\n if (raw === '*') return { kind: 'wildcard' };\n if (raw === 'pdf.permissions') return { kind: 'virtual', name: 'pdf.permissions' };\n if (raw.includes(':')) return parseCollab(raw);\n return parseCapability(raw);\n}\n\n/**\n * Validate every entry in a scope array by attempting to parse it.\n * Throws on the first invalid string. Discards the parse output —\n * callers re-parse at resolution time to keep the array as the\n * authoritative payload.\n */\nexport function validateScopeArray(raw: ReadonlyArray<string>): void {\n for (const s of raw) parseScope(s);\n}\n\nfunction parseCollab(raw: string): ParsedScope {\n // Split on the FIRST two colons only. Filter values may contain\n // colons (UUIDs with `urn:uuid:...`, subject ids like `auth0|user:1`).\n const idx1 = raw.indexOf(':');\n const idx2 = raw.indexOf(':', idx1 + 1);\n if (idx1 === -1 || idx2 === -1) {\n throw new InvalidScope(raw, 'collab scope requires entity:action:filter');\n }\n const entity = raw.slice(0, idx1);\n const action = raw.slice(idx1 + 1, idx2);\n const filterStr = raw.slice(idx2 + 1);\n\n if (entity !== 'annotations') {\n throw new InvalidScope(raw, `unknown collab entity: ${entity}`);\n }\n if (\n action !== 'create' &&\n action !== 'update' &&\n action !== 'delete' &&\n action !== 'set-group' &&\n action !== '*'\n ) {\n throw new InvalidScope(raw, `unknown collab action: ${action}`);\n }\n const filter = parseFilter(filterStr, raw);\n\n // `set-group` is a group-assignment authority, not a per-record collab\n // filter. The only meaningful filter values are `all` (assign to any\n // group) and `group=X` (assign to group X). `:self` and `:createdBy=Y`\n // can't be sensibly applied to \"what group is this annotation in\", so\n // we reject them at parse time rather than silently always-denying.\n if (action === 'set-group' && (filter.kind === 'self' || filter.kind === 'createdBy')) {\n throw new InvalidScope(\n raw,\n `set-group only supports :all or :group=<id> filters (got :${filter.kind})`,\n );\n }\n\n return {\n kind: 'collab',\n entity,\n action: action as CollabAction | '*',\n filter,\n };\n}\n\nfunction parseFilter(s: string, raw: string): CollabFilter {\n if (s === 'all') return { kind: 'all' };\n if (s === 'self') return { kind: 'self' };\n if (s.startsWith('createdBy=')) {\n const v = s.slice('createdBy='.length);\n if (!v) throw new InvalidScope(raw, 'createdBy= requires a value');\n return { kind: 'createdBy', userId: v };\n }\n if (s.startsWith('group=')) {\n const v = s.slice('group='.length);\n if (!v) throw new InvalidScope(raw, 'group= requires a value');\n return { kind: 'group', groupId: v };\n }\n throw new InvalidScope(raw, `unknown filter: ${s}`);\n}\n\n// Capability shape: lowercase dotted segments, e.g. \"doc.text.copy\".\n// Validates shape first, then membership in the closed set.\nconst CAPABILITY_SHAPE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$/;\n\nfunction parseCapability(raw: string): ParsedScope {\n if (!CAPABILITY_SHAPE.test(raw)) {\n throw new InvalidScope(raw, 'invalid capability name shape');\n }\n if (!KNOWN_CAPABILITIES.has(raw as DocCapability)) {\n throw new InvalidScope(raw, `unknown capability: ${raw}`);\n }\n return { kind: 'capability', name: raw as DocCapability };\n}\n","import { parseScope } from './parser';\nimport type {\n CollabAction,\n CollabFilter,\n DocCapability,\n IdentityClaims,\n ParsedScope,\n PdfBits,\n} from './types';\n\n/**\n * Resolved collab subject — the per-record identity bits used to test\n * collab filters against. Sourced from the target record's stored\n * `/EMBD_Metadata/UserID` and `/GroupID` at mutation time.\n */\nexport interface CollabTarget {\n userId?: string;\n groupId?: string;\n}\n\n/**\n * True iff the given capability is granted by the scope array plus the\n * PDF bits visible via `pdf.permissions` expansion.\n *\n * Wildcard `*` short-circuits to true. Anything not explicitly granted\n * (or expanded from `pdf.permissions`) is denied.\n */\nexport function checkCapability(\n capability: DocCapability,\n rawScope: ReadonlyArray<string>,\n pdfBits: PdfBits,\n): boolean {\n const parsed = rawScope.map(parseScope);\n if (parsed.some((s) => s.kind === 'wildcard')) return true;\n return expandedCapabilities(parsed, pdfBits).has(capability);\n}\n\n/**\n * True iff the scope grants AT LEAST ONE of `capabilities`. Convenience\n * for routes like `/text` (`doc.text.copy` OR `doc.text.search`) and\n * `/geometry` (`doc.text.select` OR `doc.text.search`).\n */\nexport function checkAnyCapability(\n capabilities: ReadonlyArray<DocCapability>,\n rawScope: ReadonlyArray<string>,\n pdfBits: PdfBits,\n): boolean {\n return capabilities.some((c) => checkCapability(c, rawScope, pdfBits));\n}\n\n/**\n * True iff the scope grants the collab action against the target record.\n *\n * Narrowing model. For each action independently:\n * 1. wildcard `*` → allow (global escape hatch)\n * 2. if any collab scope applies to this action → NARROW: only those\n * collab filters decide. If none match the target, deny — even if\n * `doc.annotate.modify` is also present. This is what makes\n * `[modify, update:self]` correctly mean \"edit own only\" rather\n * than \"edit anyone via modify-bypass.\"\n * 3. otherwise, if `doc.annotate.modify` is present → allow. This is\n * the broad PDF-bit-derived default for create/update/delete when\n * no per-action collab filter has been written.\n * 4. otherwise → deny.\n *\n * For create: `target` should be built by the caller from JWT identity\n * (`{ userId: caller.user_id, groupId: caller.group_id }`). `:self` and\n * `:all` then trivially pass; `:group=X` is the meaningful filter (only\n * matches when the caller's default group is X).\n *\n * For update / delete: `target` is the existing row's owner.\n */\nexport function checkCollab(\n action: CollabAction,\n target: CollabTarget,\n rawScope: ReadonlyArray<string>,\n identity: IdentityClaims,\n pdfBits: PdfBits,\n): boolean {\n const parsed = rawScope.map(parseScope);\n if (parsed.some((s) => s.kind === 'wildcard')) return true;\n\n const applicableCollab = parsed.filter(\n (s): s is Extract<ParsedScope, { kind: 'collab' }> =>\n s.kind === 'collab' &&\n s.entity === 'annotations' &&\n (s.action === action || s.action === '*'),\n );\n\n if (applicableCollab.length > 0) {\n // Narrow: presence of any applicable collab scope shadows\n // `modify`-as-default for this action.\n return applicableCollab.some((s) => filterMatches(s.filter, target, identity));\n }\n\n // No collab scope for this action — fall back to the broad default.\n return expandedCapabilities(parsed, pdfBits).has('doc.annotate.modify');\n}\n\n/**\n * Compute the full set of granted capabilities after expanding\n * `pdf.permissions` and applying implication rules.\n *\n * Implications applied:\n * - `doc.annotate.modify` implies `doc.annotate.read` (you can't\n * sensibly modify what you can't see).\n * - `doc.forms.modify` implies `doc.forms.fill` and `doc.forms.read`.\n * - `doc.forms.fill` implies `doc.forms.read`.\n * - any annotation collab scope implies `doc.annotate.read`, because\n * mutation routes need to see the target row to evaluate the\n * collab filter against its current owner.\n *\n * Does NOT short-circuit on wildcard — callers do that themselves\n * before calling this. Returning the expanded set is useful for the\n * `/access` response's `effectiveScope` and for advisory UI surfacing.\n */\nexport function expandedCapabilities(\n parsed: ReadonlyArray<ParsedScope>,\n pdfBits: PdfBits,\n): Set<DocCapability> {\n const out = new Set<DocCapability>();\n let hasAnnotationCollab = false;\n\n for (const s of parsed) {\n if (s.kind === 'capability') {\n out.add(s.name);\n } else if (s.kind === 'virtual' && s.name === 'pdf.permissions') {\n addPdfPermissions(out, pdfBits);\n } else if (s.kind === 'collab' && s.entity === 'annotations') {\n hasAnnotationCollab = true;\n }\n }\n\n // Implications (apply after the explicit additions above)\n if (out.has('doc.annotate.modify')) out.add('doc.annotate.read');\n if (out.has('doc.forms.modify')) {\n out.add('doc.forms.fill');\n out.add('doc.forms.read');\n }\n if (out.has('doc.forms.fill')) out.add('doc.forms.read');\n if (hasAnnotationCollab) out.add('doc.annotate.read');\n\n return out;\n}\n\n/**\n * Convenience wrapper: takes the raw scope array, parses each entry,\n * returns the expanded capability set. Exposed for the `/access`\n * endpoint and for the SDK helper that surfaces `effectiveScope`.\n */\nexport function expandRawScope(\n rawScope: ReadonlyArray<string>,\n pdfBits: PdfBits,\n): Set<DocCapability> {\n return expandedCapabilities(rawScope.map(parseScope), pdfBits);\n}\n\n/**\n * Test a single collab filter against a target record + the caller's\n * identity. Pure function — no side effects, no implicit rules.\n *\n * all → always matches\n * self → matches if identity.user_id === target.userId\n * createdBy=<X> → matches if target.userId === X\n * group=<X> → matches if target.groupId === X\n * AND identity.groups includes X\n *\n * The group-membership check on `group=X` prevents a token from\n * matching annotations in a group it doesn't belong to, even if the\n * target row carries that groupId.\n */\n/**\n * Authority to assign a specific groupId to an annotation.\n *\n * Set-group is decoupled from `doc.annotate.modify`. The reasoning:\n * capabilities like `modify` describe row access — what kind of write\n * you can do to which existing rows — and map to PDF permission bits.\n * Set-group is a cloud-only *assignment authority*: which destination\n * group can you put an annotation into? There is no PDF-bit\n * counterpart, so it doesn't inherit from `modify`.\n *\n * Resolution order:\n * 1. newGroupId === callerDefaultGroupId → true (no real reassignment\n * is happening; the annotation gets the caller's default group)\n * 2. wildcard `*` → true (global escape hatch)\n * 3. `annotations:set-group:all` → true\n * 4. `annotations:set-group:group=<newGroupId>` → true\n * 5. `annotations:*:all` or `annotations:*:group=<newGroupId>` → true\n * (action wildcard includes set-group)\n * 6. otherwise → false\n *\n * Note: independent from membership. A user with\n * `set-group:group=legal` can assign annotations to the legal group\n * even if they're not a member — that's the whole point.\n */\nexport function checkSetGroup(\n newGroupId: string,\n callerDefaultGroupId: string | undefined,\n rawScope: ReadonlyArray<string>,\n _pdfBits: PdfBits,\n): boolean {\n // No authority needed when the caller is assigning their default group.\n if (newGroupId === callerDefaultGroupId) return true;\n\n const parsed = rawScope.map(parseScope);\n if (parsed.some((s) => s.kind === 'wildcard')) return true;\n\n for (const s of parsed) {\n if (s.kind !== 'collab') continue;\n if (s.entity !== 'annotations') continue;\n if (s.action !== 'set-group' && s.action !== '*') continue;\n if (s.filter.kind === 'all') return true;\n if (s.filter.kind === 'group' && s.filter.groupId === newGroupId) return true;\n // :self and :createdBy are rejected at parse time for set-group, so\n // they never appear here. The action-wildcard path could carry those\n // filters legitimately for other actions — silently skip those, they\n // can't satisfy a set-group check.\n }\n return false;\n}\n\nexport function filterMatches(\n filter: CollabFilter,\n target: CollabTarget,\n id: IdentityClaims,\n): boolean {\n switch (filter.kind) {\n case 'all':\n return true;\n case 'self':\n return !!id.user_id && target.userId === id.user_id;\n case 'createdBy':\n return target.userId === filter.userId;\n case 'group':\n return target.groupId === filter.groupId && (id.groups?.includes(filter.groupId) ?? false);\n }\n}\n\n/**\n * Translate `pdf.permissions` (virtual scope) into the concrete\n * capabilities it represents under the current PDF bit configuration.\n *\n * Always adds `doc.open` and `doc.render` — these are cloud-only\n * capabilities with no PDF bit, but `pdf.permissions` is meant to be\n * the \"give the user a working session\" shorthand. Without them, a\n * token with just `['pdf.permissions']` would be useless.\n *\n * Reads are unconditional: ISO 32000 / Acrobat let any reader see\n * existing annotations and form values regardless of permission bits.\n * Bit 6 governs *writing*, not visibility.\n *\n * Bit-derived expansions follow ISO 32000:\n * bit 5 → doc.text.{select, copy, search}, doc.content.copy\n * bit 3 → doc.print\n * bit 12 → doc.print.high (requires bit 3 also set)\n * bit 4 → doc.pages.modify, doc.redact, doc.metadata.modify, doc.attachments.modify\n * bit 11 → doc.pages.assemble\n * bit 6 → doc.annotate.modify\n * bit 6/9 → doc.forms.fill\n * bit 6+4 → doc.forms.modify\n *\n * Note: this same expansion lives in builders.ts as\n * `materializePdfPermissions` for SDK-side use. The two MUST stay in\n * sync; a test in resolver.test.ts pins them together.\n */\nfunction addPdfPermissions(out: Set<DocCapability>, b: PdfBits): void {\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) {\n out.add('doc.annotate.modify');\n }\n if (b.bit6 || b.bit9) out.add('doc.forms.fill');\n if (b.bit6 && b.bit4) out.add('doc.forms.modify');\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,eAAb,cAAkC,MAAM;CACtC,YACE,OACA,QACA;EACA,MAAM,kBAAkB,MAAM,KAA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