import type { PageDestination } from './PdfDestination'; /** Normalized values of an action dictionary's `/S` name. */ export type PdfActionType = PdfActionNode['type']; /** * One Hide `/T` or ResetForm `/Fields` entry. Deliberately unscoped: a * dictionary reference carries no page, so resolution (a name to widgets, an * object number to an annotation or field) is the interpreter's job — never * the extractor's. */ export type PdfActionTargetRef = | { kind: 'name'; name: string } | { kind: 'objectNumber'; objectNumber: number }; /** * SubmitForm's `/Flags` word (ISO 32000-2:2020 Table 240), named. The engine * reads and writes the bits; the API only names them. Note the two * easily-missed positions verified against the spec: bit 12 is `ExclFKey` * (not "ExclFDFTemplate") and bit 13 is reserved/undefined, so `EmbedForm` * is bit 14. */ export interface SubmitFormFlags { /** Bit 1: set → `fields` lists excluded fields. */ exclude: boolean; /** Bit 2: submit designated valueless fields too, as name-only entries. */ includeNoValueFields: boolean; /** Bits 3/6/9 folded into one verdict: bit 9 SubmitPDF dominates ("all * other flags shall be ignored except GetMethod"), else bit 6 XFDF, else * bit 3 HTML Form format, else FDF (the Table 240 default). */ format: 'fdf' | 'html' | 'xfdf' | 'pdf'; /** Bit 4. ISO makes GetMethod meaningful only with ExportFormat set, and * the bit-9 rule keeps it alive for SubmitPDF — so `'get'` only for * `'html'` and `'pdf'`; everything else posts. */ method: 'post' | 'get'; /** Bit 5 (meaningful only with ExportFormat; passed through — this stack * does not capture click coordinates). */ submitCoordinates: boolean; /** Bit 7 (FDF only): include incremental updates via FDF `Differences`. */ includeAppendSaves: boolean; /** Bit 8 (FDF only): include markup annotations. */ includeAnnotations: boolean; /** Bit 10: convert date-like values to the standard date format. */ canonicalFormat: boolean; /** Bit 11 (FDF, with IncludeAnnotations): only the current user's * annotations. */ exclNonUserAnnots: boolean; /** Bit 12: the submitted FDF excludes its `F` entry. */ exclFKey: boolean; /** Bit 14 (bit 13 is reserved): the FDF `F` entry embeds the source PDF. */ embedForm: boolean; } /** * The one Table-240 decode, shared by the reader, the schema's producers, * and tests — so bit semantics cannot fork. */ export const decodeSubmitFormFlags = (raw: number): SubmitFormFlags => { const bit = (n: number): boolean => (raw & (1 << (n - 1))) !== 0; const format = bit(9) ? 'pdf' : bit(6) ? 'xfdf' : bit(3) ? 'html' : 'fdf'; return { exclude: bit(1), includeNoValueFields: bit(2), format, method: bit(4) && (format === 'html' || format === 'pdf') ? 'get' : 'post', submitCoordinates: bit(5), includeAppendSaves: bit(7), includeAnnotations: bit(8), canonicalFormat: bit(10), exclNonUserAnnots: bit(11), exclFKey: bit(12), embedForm: bit(14), }; }; /** * The `/Flags` word for named flags, the inverse of * {@link decodeSubmitFormFlags}: a flag left out is off, `format` is `'fdf'` * and `method` is `'post'`. */ export const encodeSubmitFormFlags = (flags: Partial): number => { const bits: Array<[number, boolean | undefined]> = [ [1, flags.exclude], [2, flags.includeNoValueFields], [3, flags.format === 'html'], [4, flags.method === 'get'], [5, flags.submitCoordinates], [6, flags.format === 'xfdf'], [7, flags.includeAppendSaves], [8, flags.includeAnnotations], [9, flags.format === 'pdf'], [10, flags.canonicalFormat], [11, flags.exclNonUserAnnots], [12, flags.exclFKey], [14, flags.embedForm], ]; return bits.reduce((word, [bit, on]) => (on ? word | (1 << (bit - 1)) : word), 0); }; /** The named flags of a payload, without its URL, fields or charset. */ function submitFormFlagsOf(payload: SubmitFormPayload): SubmitFormFlags { const { url: _url, fields: _fields, charSet: _charSet, ...flags } = payload; return flags; } /** * SubmitForm's extracted intent. Atomic on purpose: either every required * component resolved (a complete, executable payload) or the node carries no * payload at all — partial states are unrepresentable. An unreadable * required component (`/F`) degrades the whole node to `unknown` + * `payload-dropped` at read time instead. */ export interface SubmitFormPayload extends SubmitFormFlags { /** Resolved `/F` URL — a `<< /FS /URL >>` file specification (7.11.5, * `/UF` preferred over `/F` per 7.11.2); a bare string `/F` is accepted * as a producer-compat extension. */ url: string; /** * `null` = `/Fields` absent → Include/Exclude is ignored and every field * except NoExport-flagged ones is submitted (Table 239). `[]` = * present-but-empty: include mode submits nothing, exclude mode submits * everything eligible — presence and emptiness are different states. */ fields: PdfActionTargetRef[] | null; /** `/CharSet` (PDF 2.0), extracted but not encoded by this stack. */ charSet?: string; } interface PdfActionNodeCommon { /** Raw `/S` name, retained for unknown and future action types. */ subtype: string; /** Normalized `/Next` children in PDF order. */ next: PdfActionNode[]; } /** * One detached node in a normalized PDF action tree, discriminated on the * interpreter that would execute it. Every executable arm carries its full * payload — a `goto` without a destination or a `uri` without a URI is * unrepresentable. A payload the reader cannot materialize degrades the node * to `unknown` (original `/S` kept on `subtype`) and appends the tree-level * `'payload-dropped'` warning. A `goto` goes to a {@link PageDestination}; * the engine's own readers, which work in the file's coordinates, use * `PdfActionNode`. */ export type PdfActionNode = PdfActionNodeCommon & ( | { type: 'javascript'; script: string } | { type: 'goto'; destination: Destination } | { type: 'uri'; uri: string; isMap: boolean } | { type: 'named'; name: string } | { type: 'hide'; targets: PdfActionTargetRef[]; hide: boolean } | { type: 'reset-form'; /** * `null` = `/Fields` absent → reset every field (`exclude` is * meaningless). `[]` = present-but-empty: with `exclude` false reset * nothing, with `exclude` true reset everything — PDFium's executor * branches on presence first. */ fields: PdfActionTargetRef[] | null; exclude: boolean; } /** Reported, never executed. */ | { type: 'goto-remote'; filePath: string } | { type: 'goto-embedded'; filePath: string } | { type: 'launch'; filePath: string } /** ISO allows `/Rendition` to carry `/JS`; preserved, not collected. */ | { type: 'rendition'; script?: string } /** Recognized; executable only when `payload` is present. Absent payload * = extracted by a runtime without the SubmitForm getters (version * skew) — the node stays recognized-inert. */ | { type: 'submit-form'; payload?: SubmitFormPayload } | { type: 'thread' } | { type: 'sound' } | { type: 'movie' } | { type: 'import-data' } | { type: 'set-ocg-state' } | { type: 'transition' } | { type: 'goto-3d-view' } | { type: 'unknown' } ); export type PdfActionWarning = | 'cycle-dropped' | 'malformed-next' | 'incomplete' /** A node's payload could not be read; that node degraded to `unknown`. */ | 'payload-dropped'; /** * One extracted action root plus the native reader's safety verdict. * Consumers must never execute a tree whose `incomplete` flag is true. */ export interface PdfActionTree { /** Null when the model was valid but its root exceeded a safety bound. */ root: PdfActionNode | null; incomplete: boolean; /** What the reader dropped or couldn't read, by name. */ warnings: PdfActionWarning[]; } export interface PdfFieldActions { keystroke?: PdfActionTree; format?: PdfActionTree; validate?: PdfActionTree; calculate?: PdfActionTree; } export interface PdfPageActions { open?: PdfActionTree; close?: PdfActionTree; } export interface PdfAnnotationActions { activate?: PdfActionTree; cursorEnter?: PdfActionTree; cursorExit?: PdfActionTree; mouseDown?: PdfActionTree; mouseUp?: PdfActionTree; focus?: PdfActionTree; blur?: PdfActionTree; pageOpen?: PdfActionTree; pageClose?: PdfActionTree; pageVisible?: PdfActionTree; pageInvisible?: PdfActionTree; } export interface NamedJavaScriptAction { /** Name-tree key. Array order is the PDF boot order. */ name: string; action: PdfActionTree; } /** Catalog-owned actions. Page actions stay on their owning PageLayout. */ export interface DocumentActionsSnapshot { nameTreeScripts: NamedJavaScriptAction[]; /** Action-form `/OpenAction`. Mutually exclusive with `openDestination` — * `/OpenAction` is one entry, a dictionary or an array. */ openAction: PdfActionTree | null; /** Destination-form `/OpenAction` — the initial view, not an action. */ openDestination: Destination | null; willClose?: PdfActionTree; willSave?: PdfActionTree; didSave?: PdfActionTree; willPrint?: PdfActionTree; didPrint?: PdfActionTree; } /** * Aggregate guard applied across every action model read by one job. Native * limits are per model; this prevents a document containing many models from * creating an unbounded detached snapshot. */ export interface ActionReadBudget { maxModels: number; maxNodes: number; maxScriptCodeUnits: number; /** Hide `/T` + ResetForm/SubmitForm `/Fields` entries, aggregate across * the job. */ maxTargetEntries: number; /** Payload string code units (URIs, submit URLs/CharSets, names, file * paths, name-tree script names), aggregate across the job. Reserved * before allocation. */ maxPayloadCodeUnits: number; } // ── writing actions ── /** * An action to write: the read shape ({@link PdfActionNode}) of a type a * write can make, without what only a read reports (`subtype`, a tree's * warnings). `next` runs after it, in order. A write makes JavaScript, * go-to, URI, named, hide, reset-form and submit-form actions; a `uri`'s * `isMap` and a submit's `charSet` are read, never written. */ export type PdfActionWrite = { next?: PdfActionWrite[]; } & ( | { type: 'javascript'; script: string } | { type: 'goto'; destination: Destination } | { type: 'uri'; uri: string } | { type: 'named'; name: string } | { type: 'hide'; targets: PdfActionTargetRef[]; hide: boolean } | { type: 'reset-form'; /** As read: `null` resets every field, `[]` with `exclude` false resets none. */ fields: PdfActionTargetRef[] | null; exclude: boolean; } | ({ type: 'submit-form'; url: string; /** As read: `null` submits every field the form exports. */ fields: PdfActionTargetRef[] | null; } & Partial) ); /** * A field event's script: JavaScript, with more scripts to run after it. * A field's events (keystroke, format, validate, calculate) take JavaScript * only: every viewer runs them as script hooks. */ export interface FieldScriptWrite { type: 'javascript'; script: string; next?: FieldScriptWrite[]; } /** The events a field's scripts run on. */ export type FieldScriptEvent = keyof PdfFieldActions; /** The events a widget's actions run on: `activate` (`/A`, a click) and its `/AA` events. */ export type WidgetActionEvent = keyof PdfAnnotationActions; /** * A widget's actions to write, by event: an action sets the event's, `null` * removes it, and an event left out keeps what it has. Any type a write * makes; a JavaScript, submit-form or URI action anywhere in a tree takes * `doc.forms.script` too. */ export type WidgetActionsPatch = { [Event in WidgetActionEvent]?: PdfActionWrite | null; }; /** * A field's scripts to write, by event: a script sets the event's, `null` * removes it, and an event left out keeps what it has. A `calculate` script * puts the field in the form's calculation order (at the end, when it isn't * there yet); removing it takes the field out. */ export type FieldActionsPatch = { [Event in FieldScriptEvent]?: FieldScriptWrite | null }; /** * Whether writing `action` puts code or a way out of the viewer into the * document, which takes `doc.forms.script`: a JavaScript, submit-form or URI * action anywhere in its tree. */ export function needsScriptRight(action: PdfActionWrite): boolean { return ( action.type === 'javascript' || action.type === 'submit-form' || action.type === 'uri' || (action.next ?? []).some(needsScriptRight) ); } /** * Whether writing actions, a field's or a widget's, takes `doc.forms.script`: * an event gets a tree holding a JavaScript, submit-form or URI action. * Removing actions (`null`) never does, and neither does a widget's read sent * back: its trees are kept unchanged or refused, never written. */ export function writesScripts( actions: | FieldActionsPatch | WidgetActionsPatch | PdfAnnotationActions | null | undefined, ): boolean { return Object.values(actions ?? {}).some( (action: PdfActionWrite | PdfActionTree | null | undefined) => action != null && !('root' in action) && needsScriptRight(action), ); } /** * The write of a read action tree: what a copy writes. `null` when the tree * is incomplete, or holds a type a write can't make (a submit-form whose * payload the read dropped included). */ export function actionWriteOf( tree: PdfActionTree, ): PdfActionWrite | null { if (tree.incomplete || !tree.root) return null; return nodeWriteOf(tree.root); } /** * A widget's read actions as a patch writes them: `null` for an event * without one. An event whose actions a write can't make is left out, so * writing the patch back never removes it. */ export function widgetActionsOf( actions: PdfAnnotationActions | null, ): WidgetActionsPatch { const patch: WidgetActionsPatch = {}; for (const event of WIDGET_ACTION_EVENTS) { const tree = actions?.[event]; if (!tree) { patch[event] = null; continue; } const write = actionWriteOf(tree); if (write) patch[event] = write; } return patch; } /** Every event a widget's actions run on, in `EPDF_ANNOT_ACTION_*` order. */ export const WIDGET_ACTION_EVENTS = [ 'activate', 'cursorEnter', 'cursorExit', 'mouseDown', 'mouseUp', 'focus', 'blur', 'pageOpen', 'pageClose', 'pageVisible', 'pageInvisible', ] as const satisfies readonly WidgetActionEvent[]; /** The field script of a read tree: `null` unless it is JavaScript all through. */ export function fieldScriptOf(tree: PdfActionTree): FieldScriptWrite | null { const write = actionWriteOf(tree); return write && isFieldScript(write) ? write : null; } /** Whether `action` is JavaScript all through: what a field event takes. */ export function isFieldScript(action: PdfActionWrite): action is FieldScriptWrite { return action.type === 'javascript' && (action.next ?? []).every(isFieldScript); } function nodeWriteOf( node: PdfActionNode, ): PdfActionWrite | null { const next: PdfActionWrite[] = []; for (const child of node.next) { const write = nodeWriteOf(child); if (!write) return null; next.push(write); } const tail = next.length > 0 ? { next } : {}; switch (node.type) { case 'javascript': return { type: 'javascript', script: node.script, ...tail }; case 'goto': return { type: 'goto', destination: node.destination, ...tail }; case 'uri': return { type: 'uri', uri: node.uri, ...tail }; case 'named': return { type: 'named', name: node.name, ...tail }; case 'hide': return { type: 'hide', targets: node.targets, hide: node.hide, ...tail }; case 'reset-form': return { type: 'reset-form', fields: node.fields, exclude: node.exclude, ...tail }; case 'submit-form': return node.payload ? { ...submitFormFlagsOf(node.payload), type: 'submit-form', url: node.payload.url, fields: node.payload.fields, ...tail, } : null; default: return null; } }