@embedpdf/plugin-actions 3.0.0-next.15 → 3.0.0-next.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contract/host.d.cts +2 -2
- package/dist/contract/host.d.ts +2 -2
- package/dist/{contract-DSQysTqU.d.cts → contract-BTPW8b4L.d.cts} +12 -2
- package/dist/{contract-CNKZHb6w.d.ts → contract-Cn-7mBY8.d.ts} +12 -2
- package/dist/contract-CwN3NAXU.js.map +1 -1
- package/dist/contract-_HB_UliT.cjs.map +1 -1
- package/dist/contract.d.cts +1 -1
- package/dist/contract.d.ts +1 -1
- package/dist/{host-contract-CRNO2oZN.d.ts → host-contract-BbODswDs.d.ts} +2 -2
- package/dist/{host-contract-DJ8TqDr3.d.cts → host-contract-D22Gz-qt.d.cts} +2 -2
- package/dist/index.cjs +78 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +79 -11
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["PluginError","triggerOriginOf","eventOf","PluginError","DEFAULT_SCRIPT_BUDGET","ActionsToken","ACTIONS_DEFAULTS"],"sources":["../src/services/annotation-rows.ts","../src/dispatch/fold.ts","../src/dispatch/dispatcher.ts","../src/services/policy.ts","../src/submit/intent.ts","../src/dispatch/run.ts","../src/dispatch/triggers.ts","../src/lifecycle/document-events.ts","../src/lifecycle/open-sequence.ts","../src/lifecycle/page-lifecycle.ts","../src/scripting/world.ts","../src/scripting/executor.ts","../src/scripting/environment.ts","../src/scripting/realm.ts","../src/scripting/surface.ts","../src/services/authority.ts","../src/services/catalog.ts","../src/services/events.ts","../src/services/form.ts","../src/services/ports.ts","../src/services/print-latch.ts","../src/services/queue.ts","../src/services/index.ts","../src/submit/perform.ts","../src/controller.ts","../src/settings.ts","../src/actions.plugin.ts"],"sourcesContent":["/**\n * The annotations an action can live on, of both read families: a page's\n * annotations (`doc.annotations`, `doc.annotate.read`) and its widgets, which\n * come with the form (`ActionsForm`, `doc.forms.read`). Each family is read\n * only when the session may read it, so a fill-only session still finds its\n * widgets' actions.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type PageRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\nimport type { ActionsForm } from './form';\n\n/** Every annotation of a page the session may read: its annotations, then its widgets. */\nexport async function readPageAnnotations(\n ctx: ActionsContext,\n form: ActionsForm,\n page: PageRef,\n read: <T>(task: Promise<T>) => Promise<T> = (task) => task,\n): Promise<Annotation[]> {\n const [annotations, widgets] = await Promise.all([\n ctx.allows('doc.annotate.read')\n ? read(ctx.doc.page(page).annotations.list()).then((list) => list.annotations)\n : Promise.resolve([]),\n ctx.allows('doc.forms.read')\n ? form\n .read(read)\n .then((snapshot) =>\n snapshot.widgets.filter((widget) => widget.page.objectNumber === page.objectNumber),\n )\n : Promise.resolve([]),\n ]);\n return [...annotations, ...widgets];\n}\n\n/**\n * The annotation `ref` names, of either family, or `null` when the session\n * can't see it: the form's widgets first (most actions a viewer runs are a\n * field's), then the page's annotations.\n */\nexport async function readAnnotation(\n ctx: ActionsContext,\n form: ActionsForm,\n ref: AnnotationRef,\n read: <T>(task: Promise<T>) => Promise<T> = (task) => task,\n): Promise<Annotation | null> {\n const key = annotationKey(ref);\n const matches = (candidate: Annotation) => annotationKey(candidate.ref) === key;\n if (ctx.allows('doc.forms.read')) {\n const widget = (await form.read(read)).widgets.find(matches);\n if (widget) return widget;\n }\n if (!ctx.allows('doc.annotate.read')) return null;\n return (await read(ctx.doc.page(ref.page).annotations.list())).annotations.find(matches) ?? null;\n}\n","/** Aggregate step statuses. A step failure never skips its siblings; this\n * only folds what each step reported. Pure. */\nimport type { ActionDiagnostic, ActionStepResult, ActionTriggerResult } from '../contract';\n\nexport const foldSteps = (\n steps: ActionStepResult[],\n diagnostics: ActionDiagnostic[],\n): ActionTriggerResult => {\n const statuses = steps.map((step) => step.result.status);\n const status: ActionTriggerResult['status'] =\n steps.length === 0\n ? 'inert'\n : statuses.every((stepStatus) => stepStatus === 'refused')\n ? 'refused'\n : statuses.every((stepStatus) => stepStatus === 'inert')\n ? 'inert'\n : statuses.every((stepStatus) => stepStatus === 'executed')\n ? 'executed'\n : 'partial';\n return { status, steps, diagnostics };\n};\n","/**\n * The dispatcher: the one serialized queue every tree rides. `execute` runs\n * a resolved tree; `dispatch` resolves a trigger inside the queued operation\n * (submission order is execution order) and fans out through the lifecycle\n * areas. `runAndEmit` is the shared per-tree unit: run, then `onExecuted`.\n *\n * A caller's signal skips an operation that hasn't started, stops a\n * trigger's reads, and stops a tree before its next node. `execute` then\n * rejects `operation-cancelled`; `dispatch` never rejects, so it resolves\n * `cancelled`.\n */\nimport { isPluginError, PluginError, type OperationOptions } from '@embedpdf/core';\nimport { annotationKey, type PdfActionTree } from '@embedpdf/engine-core/runtime';\n\nimport { eventOf, triggerOriginOf } from '../contract';\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionOrigin,\n ActionsCapability,\n ActionSource,\n ActionStepResult,\n ActionTreeSource,\n ActionTrigger,\n ActionTriggerEvent,\n ActionTriggerResult,\n PdfNamedAction,\n} from '../contract';\nimport type { ActionsDocumentEvents } from '../lifecycle/document-events';\nimport type { ActionsOpenSequence } from '../lifecycle/open-sequence';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { readAnnotation } from '../services/annotation-rows';\nimport { foldSteps } from './fold';\nimport type { ActionsRunner } from './run';\nimport type { ActionsTriggers } from './triggers';\n\n/** The source a trigger reports for: what its diagnostics carry before a tree is found. */\nconst sourceOfTrigger = (trigger: ActionTrigger): ActionSource => {\n switch (trigger.scope) {\n case 'activate':\n case 'annotation':\n return trigger.source ?? { kind: 'annotation', annotation: trigger.ref, page: trigger.page };\n case 'page':\n return { kind: 'page', page: trigger.page };\n case 'document':\n return { kind: 'document' };\n }\n};\n\nconst cancelled = (operation: string, signal: AbortSignal | undefined) =>\n new PluginError('operation-cancelled', 'actions', `${operation} was cancelled`, {\n cause: signal?.reason,\n });\n\nexport function createDispatcher(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'events' | 'policy' | 'queue' | 'catalog' | 'authority' | 'form'>,\n { run }: ActionsRunner,\n { triggerEnabled, lifecycleAnnotationsOf, planPageSteps }: ActionsTriggers,\n openSequence: Pick<ActionsOpenSequence, 'noteUserActivity' | 'claim' | 'run'>,\n { runDocumentEventOp }: Pick<ActionsDocumentEvents, 'runDocumentEventOp'>,\n) {\n const { executed, reportDiagnostic } = services.events;\n const { decisionFor } = services.policy;\n const { allowsPrint } = services.authority;\n const { enqueue, budget } = services.queue;\n const { readDocumentActions, DOC_EVENT_TREES } = services.catalog;\n const { form } = services;\n const { noteUserActivity } = openSequence;\n\n /** Run one tree and announce it: the shared per-tree unit (queued by\n * `execute`; called inline per step by the queued trigger resolver). */\n const runAndEmit = async (\n tree: PdfActionTree,\n actionContext: ActionContext,\n signal?: AbortSignal,\n ): Promise<ActionDispatchResult> => {\n const result = await run(tree, actionContext, signal);\n executed.emit({ tree, result, source: actionContext.source });\n return result;\n };\n\n const execute = (\n tree: PdfActionTree,\n actionContext: ActionContext,\n options?: OperationOptions,\n ): Promise<ActionDispatchResult> => {\n const signal = options?.signal;\n // Before enqueueing: a real user gesture arms the open sequence (its\n // operation then lands ahead of this action in the queue) and resets the\n // cascade budget.\n if (actionContext.origin === 'user') noteUserActivity();\n return enqueue(async () => {\n budget.scriptNodes = 0; // one script budget per dispatch\n const result = await runAndEmit(tree, actionContext, signal);\n if (result.status === 'cancelled') throw cancelled('actions.execute', signal);\n return result;\n }, options);\n };\n\n const canExecute = (tree: PdfActionTree, actionContext: ActionContext): boolean => {\n if (tree.incomplete || !tree.root) return false;\n const decision = decisionFor(tree.root, actionContext.origin);\n return decision === 'allow' || decision === 'adapter';\n };\n\n const runSteps = async (\n steps: Array<{ source: ActionSource; tree: PdfActionTree }>,\n origin: ActionOrigin,\n event: ActionTriggerEvent,\n diagnostics: ActionDiagnostic[],\n signal: AbortSignal | undefined,\n ): Promise<ActionTriggerResult> => {\n const results: ActionStepResult[] = [];\n for (const step of steps) {\n if (signal?.aborted) break;\n const result = await runAndEmit(step.tree, { origin, source: step.source, event }, signal);\n results.push({ source: step.source, tree: step.tree, result });\n }\n if (signal?.aborted) return { status: 'cancelled', steps: results, diagnostics };\n return foldSteps(results, diagnostics);\n };\n\n /** Everything a trigger needs, reads included, inside the queued operation:\n * submission order is execution order. Never throws. */\n const resolveAndRun = async (\n trigger: ActionTrigger,\n signal: AbortSignal | undefined,\n ): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const diagnose = (diagnostic: ActionDiagnostic): void => {\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { source: sourceOfTrigger(trigger) });\n };\n /** A read the caller's signal can stop. */\n const read = <T>(task: Promise<T>): Promise<T> => ctx.cancellable(signal, task);\n try {\n if (!triggerEnabled(trigger)) {\n diagnose({\n code: 'trigger-disabled',\n message: `${trigger.scope}: trigger family disabled by config`,\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n const origin = triggerOriginOf(trigger);\n switch (trigger.scope) {\n case 'activate':\n case 'annotation': {\n const event = trigger.scope === 'activate' ? 'activate' : trigger.event;\n const annotation = await readAnnotation(ctx, form, trigger.ref, read);\n // ISO 32000-2 Table 197: \"the A entry, if present, takes precedence\n // over [the /AA U entry]\"; a shadowed U tree is silently inert,\n // exactly like an absent one.\n if (event === 'mouseUp' && annotation?.actions?.activate) {\n return { status: 'inert', steps: [], diagnostics };\n }\n const tree = annotation?.actions?.[event];\n if (!tree?.root && !tree?.incomplete) return { status: 'inert', steps: [], diagnostics };\n const source = sourceOfTrigger(trigger);\n return await runSteps([{ source, tree }], origin, eventOf(trigger), diagnostics, signal);\n }\n case 'page': {\n // A shared read other triggers may wait on too: never aborted, only not awaited further.\n const lifecycle = await lifecycleAnnotationsOf(trigger.page);\n const pageActions = ctx.getPage(trigger.page)?.actions;\n const steps = planPageSteps(trigger.event, trigger.page, pageActions, lifecycle);\n return await runSteps(steps, origin, eventOf(trigger), diagnostics, signal);\n }\n case 'document': {\n if (trigger.event !== 'open') {\n return await runDocumentEventOp(trigger.event, diagnostics, diagnose);\n }\n if (!openSequence.claim()) {\n diagnose({\n code: 'open-sequence-replayed',\n message: 'document open sequence already fired for this document',\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n return await openSequence.run();\n }\n }\n } catch (error) {\n if (isPluginError(error, 'operation-cancelled') && signal?.aborted) {\n return { status: 'cancelled', steps: [], diagnostics };\n }\n diagnose({\n code: 'trigger-failed',\n message: `trigger resolution failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n return { status: 'refused', steps: [], diagnostics };\n }\n };\n\n const dispatch = (\n trigger: ActionTrigger,\n options?: OperationOptions,\n ): Promise<ActionTriggerResult> => {\n const signal = options?.signal;\n // A user-origin trigger is user activity (it arms the open sequence and\n // resets the cascade budget), noted before taking the queue slot, so an\n // armed open sequence runs first.\n if (triggerOriginOf(trigger) === 'user') noteUserActivity();\n return enqueue(() => {\n budget.scriptNodes = 0; // one script budget per dispatch\n return resolveAndRun(trigger, signal);\n }, options).catch(\n // Only a signal that fired while the trigger waited for its turn gets\n // here: resolveAndRun itself never throws.\n (): ActionTriggerResult => ({ status: 'cancelled', steps: [], diagnostics: [] }),\n );\n };\n\n /** The tree `executeNamed` runs, and its context: a click from your code unless `context` says otherwise. */\n const namedTree = (name: PdfNamedAction): PdfActionTree => ({\n root: { type: 'named', subtype: 'Named', name, next: [] },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n });\n const namedContext = (context?: Partial<ActionContext>): ActionContext => ({\n origin: 'user',\n source: { kind: 'api' },\n event: { scope: 'activate' },\n ...context,\n });\n\n const executeNamed = (\n name: PdfNamedAction,\n context?: Partial<ActionContext>,\n options?: OperationOptions,\n ): Promise<ActionDispatchResult> => execute(namedTree(name), namedContext(context), options);\n\n const canExecuteNamed = (name: PdfNamedAction, context?: Partial<ActionContext>): boolean =>\n canExecute(namedTree(name), namedContext(context)) && (name !== 'Print' || allowsPrint());\n\n /** The raw tree behind a source, read from the document, with no dispatch\n * rules applied (the /A-shadows-U rule lives in `resolveAndRun`). */\n const readActionTree = async (source: ActionTreeSource): Promise<PdfActionTree | null> => {\n switch (source.kind) {\n case 'annotation': {\n const annotation = await readAnnotation(ctx, form, source.annotation);\n const tree = annotation?.actions?.[source.event ?? 'activate'];\n return tree ?? null;\n }\n case 'field': {\n const { fields } = await form.read();\n const target = source.field;\n const field = fields.find((candidate) =>\n target.kind === 'objectNumber'\n ? candidate.ref.kind === 'objectNumber' &&\n candidate.ref.objectNumber === target.objectNumber\n : candidate.name === target.name,\n );\n return field?.actions?.[source.event] ?? null;\n }\n case 'page':\n return ctx.getPage(source.page)?.actions?.[source.event ?? 'open'] ?? null;\n case 'document': {\n const snapshot = await readDocumentActions();\n if (!snapshot) return null;\n const event = source.event ?? 'open';\n return (event === 'open' ? snapshot.openAction : snapshot[DOC_EVENT_TREES[event]]) ?? null;\n }\n }\n };\n\n return {\n runAndEmit,\n dispatch,\n api: {\n execute,\n canExecute,\n executeNamed,\n canExecuteNamed,\n getActionTree: (source, options) => ctx.cancellable(options?.signal, readActionTree(source)),\n dispatch,\n // The synchronous twin: the trigger family is enabled. Per-tree truth\n // stays per step in the results; resolution is async and never\n // previewed here.\n canDispatch: (trigger) => triggerEnabled(trigger),\n prepareClose: (options): Promise<ActionTriggerResult> =>\n dispatch({ scope: 'document', event: 'will-close' }, options),\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsDispatcher = ReturnType<typeof createDispatcher>;\n","/**\n * The policy matrix (type × origin → decision): the fixed `never` and\n * unsupported sets, and the one decision function over the `policy` setting.\n * The setting itself (its defaults and its merge) is the plugin's settings.\n */\nimport type { PdfActionNode, PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionOrigin,\n ActionPolicy,\n ActionPolicyDecision,\n ActionPolicyRow,\n} from '../contract';\nimport type { ActionsContext } from './context';\n\n/** Never executable, not configurable — diagnostics only. */\nconst NEVER_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'launch',\n 'goto-remote',\n 'goto-embedded',\n 'sound',\n 'movie',\n 'import-data',\n]);\n\n/** Recognized types with no interpreter: reported, never executed. */\nconst UNSUPPORTED_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'rendition',\n 'thread',\n 'set-ocg-state',\n 'transition',\n 'goto-3d-view',\n 'unknown',\n]);\n\n/** Document-lifetime node types: engine mutations, committed in walk order. */\nexport const DOCUMENT_TYPES: ReadonlySet<PdfActionType> = new Set(['reset-form', 'javascript']);\n\nexport const isPrintVerb = (node: PdfActionNode): boolean =>\n node.type === 'named' && node.name === 'Print';\n\nexport function createPolicy(ctx: ActionsContext) {\n const settings = ctx.settings();\n /** The live policy: read at decision time, never captured. */\n const current = (): ActionPolicy => settings.get().policy;\n\n /** The decision for one node and origin; `'never'` and `'unsupported'` are fixed, not configurable. */\n const decisionFor = (\n node: PdfActionNode,\n origin: ActionOrigin,\n ): ActionPolicyDecision | 'never' | 'unsupported' => {\n if (NEVER_TYPES.has(node.type)) return 'never';\n if (UNSUPPORTED_TYPES.has(node.type)) return 'unsupported';\n const policy = current();\n if (isPrintVerb(node)) return policy.print[origin];\n const row = policy[node.type as keyof ActionPolicy] as ActionPolicyRow | undefined;\n return row ? row[origin] : 'unsupported';\n };\n\n return { decisionFor, current };\n}\nexport type ActionsPolicy = ReturnType<typeof createPolicy>;\n","/** The one normalized submit intent, from either source (an action node's\n * payload or a script `doc.submitForm()` effect), and the engine request\n * shape the document's home receives. Pure. */\nimport type { ScriptUiEffect } from '@embedpdf/core-acrojs';\nimport type {\n FormSubmissionRequest,\n IsoDateTime,\n SubmitFormPayload,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionSubmitRequest, SubmitIntent } from '../contract';\n\nexport const intentOfPayload = (payload: SubmitFormPayload): SubmitIntent => ({\n url: payload.url,\n fields: payload.fields,\n exclude: payload.flags.exclude,\n includeNoValueFields: payload.flags.includeNoValueFields,\n format: payload.flags.format,\n method: payload.flags.method,\n flagsRaw: payload.flags.raw,\n ...(payload.charSet === undefined ? {} : { charSet: payload.charSet }),\n});\n\nexport const toFormSubmissionRequest = (\n request: ActionSubmitRequest,\n sentAt: IsoDateTime,\n): FormSubmissionRequest => ({\n entries: request.entries,\n intent: {\n url: request.url,\n format: request.format,\n method: request.method,\n flagsRaw: request.flagsRaw,\n ...(request.charSet === undefined ? {} : { charSet: request.charSet }),\n },\n origin: request.origin,\n sentAt,\n});\n\n/** Script `doc.submitForm(...)` → the one normalized intent. Script field\n * names are include-mode by definition (Acrobat's aFields). */\nexport const intentOfSubmitEffect = (\n effect: Extract<ScriptUiEffect, { kind: 'submitForm' }>,\n): SubmitIntent => {\n const format = effect.format ?? 'fdf';\n return {\n url: effect.url,\n fields: effect.fieldNames?.map((name) => ({ kind: 'name' as const, name })) ?? null,\n exclude: false,\n includeNoValueFields: effect.includeEmpty,\n format,\n method: effect.method ?? 'post',\n flagsRaw: 0,\n };\n};\n","/**\n * The tree walker: policy per node, document-lifetime work in walk order\n * (Hide through the owner sinks, executors for the rest), and navigation and\n * external effects deferred until every document node succeeded. A caller's\n * signal that fires stops the walk before its next node, and nothing\n * deferred fires.\n */\nimport type {\n FormFieldRef,\n PdfActionNode,\n PdfActionTree,\n PdfActionType,\n} from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionExecutorResult,\n ActionNodeResult,\n ActionNodeStatus,\n} from '../contract';\nimport type { AnnotCommitEntry } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { DOCUMENT_TYPES, isPrintVerb } from '../services/policy';\nimport { intentOfPayload } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\nimport type { ActionsDocumentEvents } from '../lifecycle/document-events';\n\nexport function createRunner(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'policy' | 'ports' | 'events' | 'form'>,\n { performSubmit }: ActionsSubmit,\n { firePrintThroughAdapter }: Pick<ActionsDocumentEvents, 'firePrintThroughAdapter'>,\n) {\n const { decisionFor } = services.policy;\n const ports = services.ports.slots;\n const { reportDiagnostic } = services.events;\n const { form } = services;\n\n async function run(\n tree: PdfActionTree,\n actionContext: ActionContext,\n signal?: AbortSignal,\n ): Promise<ActionDispatchResult> {\n const diagnostics: ActionDiagnostic[] = [];\n /** Record a diagnostic in the result and report it, with the action it concerns. */\n const diagnose = (diagnostic: ActionDiagnostic, action: PdfActionType | null): void => {\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { action, source: actionContext.source });\n };\n\n // The law: never execute an incomplete tree — not even its root.\n if (tree.incomplete) {\n diagnose(\n { code: 'incomplete-tree', message: 'refused: the action tree is incomplete' },\n tree.root?.type ?? null,\n );\n return { status: 'refused', nodes: [], diagnostics };\n }\n if (!tree.root) return { status: 'inert', nodes: [], diagnostics };\n\n const nodes: ActionNodeResult[] = [];\n // Navigation and external effects are deferred thunks, fired only after\n // every document-lifetime node succeeded, in node order, so navigation\n // never yanks the user away from a failed write.\n const deferred: Array<{ result: ActionNodeResult; fire: () => Promise<void> | void }> = [];\n let documentFailed = false;\n let cancelled = false;\n\n const settle = (result: ActionNodeResult, outcome: ActionExecutorResult): void => {\n if (outcome.status === 'executed') result.status = 'executed';\n else if (outcome.status === 'inert') {\n result.status = 'inert';\n result.detail = outcome.reason;\n diagnose(\n { code: 'executor-inert', message: `${result.type}: ${outcome.reason}` },\n result.type,\n );\n } else {\n result.status = 'failed';\n result.detail = outcome.error;\n diagnose(\n { code: 'executor-failed', message: `${result.type}: ${outcome.error}` },\n result.type,\n );\n }\n };\n\n // A Hide action sets or clears the Hidden state (ISO 32000-2 §12.6.4.11):\n // a real mutation through the owning plane's commit sink, authority-gated\n // by the engine like every other write. Widgets are the forms plane's\n // visibility (the engine's field-level `setDisplay`, like Acrobat's\n // `field.display`; there is no per-widget annotation patch); plain\n // annotations are flag patches through the annotation sink.\n const interpretHide = async (\n node: Extract<PdfActionNode, { type: 'hide' }>,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const display = node.hide ? ('hidden' as const) : ('visible' as const);\n const diagnoseHide = (diagnostic: ActionDiagnostic): void => diagnose(diagnostic, 'hide');\n const fieldRefs: FormFieldRef[] = [];\n const annotEntries: AnnotCommitEntry[] = [];\n const names: string[] = [];\n const bareObjectNumbers: number[] = [];\n for (const target of node.targets) {\n if (target.kind === 'objectNumber') bareObjectNumbers.push(target.objectNumber);\n else names.push(target.name);\n }\n if (names.length || bareObjectNumbers.length) {\n const snapshot = await form.read();\n for (const name of names) {\n const field = snapshot.fields.find((candidate) => candidate.name === name);\n if (!field) {\n diagnoseHide({ code: 'unresolved-target', message: `hide: no field named '${name}'` });\n continue;\n }\n fieldRefs.push(field.ref);\n }\n for (const objectNumber of bareObjectNumbers) {\n // A bare object number may be a widget (its field's display) or a\n // plain annotation (its own flags): the forms snapshot decides.\n const owner = snapshot.fields.find((field) =>\n field.widgets.some((widget) => widget.objectNumber === objectNumber),\n );\n if (owner) {\n fieldRefs.push(owner.ref);\n } else {\n annotEntries.push({\n annotObjectNumber: objectNumber,\n patch: { flags: { hidden: node.hide } },\n });\n }\n }\n }\n let failedDetail: string | undefined;\n if (fieldRefs.length) {\n if (!ports.formCommitSink) {\n diagnoseHide({\n code: 'no-commit-sink',\n message: 'hide: no form commit sink registered (form plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const result = await ports.formCommitSink(\n fieldRefs.map((ref) => ({ kind: 'setDisplay', ref, display })),\n );\n if (result.status === 'failed') {\n failedDetail = result.error ?? 'failed';\n diagnoseHide({ code: 'executor-failed', message: `hide: ${failedDetail}` });\n }\n }\n if (annotEntries.length && !failedDetail) {\n if (!ports.annotCommitSink) {\n diagnoseHide({\n code: 'no-commit-sink',\n message: 'hide: no annotation commit sink registered (annotation plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const committed = await ports.annotCommitSink(annotEntries);\n const failed = committed.results.filter((entry) => entry.status === 'failed');\n for (const failure of failed) {\n diagnoseHide({\n code: 'executor-failed',\n message: `hide: annotation ${failure.annotObjectNumber}: ${failure.error ?? 'failed'}`,\n });\n }\n if (failed.length === committed.results.length && failed.length > 0) {\n failedDetail = failed[0]?.error;\n }\n }\n if (failedDetail) return { status: 'failed', detail: failedDetail };\n return { status: 'executed' };\n };\n\n const interpret = async (node: PdfActionNode, path: number[]): Promise<void> => {\n const result: ActionNodeResult = { path, type: node.type, status: 'blocked' };\n nodes.push(result);\n const decision = decisionFor(node, actionContext.origin);\n const diagnoseNode = (diagnostic: ActionDiagnostic): void => diagnose(diagnostic, node.type);\n\n if (decision === 'never' || decision === 'block' || decision === 'report') {\n result.status = 'blocked';\n // `block` refuses quietly; `report`, and a type that never runs, say so.\n if (decision !== 'block') {\n diagnoseNode({\n code: 'blocked',\n message: `${node.type}: ${decision === 'never' ? 'never executable' : `policy 'report' for origin '${actionContext.origin}'`}`,\n });\n }\n return;\n }\n if (decision === 'unsupported') {\n result.status = 'no-executor';\n return;\n }\n\n if (node.type === 'hide') {\n // A document mutation: an earlier document failure skips it, and its\n // own failure stops later document work and drops deferred effects.\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const outcome = await interpretHide(node);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n if (outcome.status === 'failed') documentFailed = true;\n return;\n }\n\n if (DOCUMENT_TYPES.has(node.type)) {\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const executor = ports.executors.get(node.type);\n if (!executor) {\n result.status = node.type === 'javascript' ? 'inert' : 'no-executor';\n diagnoseNode({\n code: 'no-executor',\n message: `${node.type}: no executor registered${node.type === 'javascript' ? ' (scripting unavailable)' : ''}`,\n });\n return;\n }\n try {\n settle(result, await executor(node, actionContext));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (result.status === 'failed') documentFailed = true;\n return;\n }\n\n if (node.type === 'submit-form') {\n if (!node.payload) {\n // A runtime that does not extract the submit payload: the node is\n // recognized but inert, and diagnosed.\n result.status = 'inert';\n result.detail = 'submit payload unavailable (older runtime extraction)';\n diagnoseNode({\n code: 'submit-payload-unavailable',\n message: 'submit-form: payload unavailable (older runtime extraction) — node inert',\n });\n return;\n }\n const payload = node.payload;\n // External like print and uri: deferred until every document-lifetime\n // node succeeded, so a submission never carries a half-failed form\n // state.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const outcome = await performSubmit(\n intentOfPayload(payload),\n actionContext,\n diagnoseNode,\n );\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n if (isPrintVerb(node) || node.type === 'uri') {\n // External: adapter-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n if (node.type === 'uri') {\n if (!ports.uiAdapter) {\n result.status = 'no-executor';\n diagnoseNode({\n code: 'no-adapter',\n message: `${node.type}: no UI adapter installed`,\n });\n return;\n }\n ports.uiAdapter.openUri(node.uri, {\n isMap: node.isMap,\n origin: actionContext.origin,\n });\n result.status = 'executed';\n return;\n }\n // The Print verb: /WP → the adapter (exactly once) → /DP, under\n // the print latch. Authority, adapter and reentrancy verdicts come\n // back as the node's status.\n const outcome = await firePrintThroughAdapter(undefined, diagnoseNode);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n // goto + named page verbs: navigation, executor-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const executor = ports.executors.get(node.type);\n if (!executor) {\n result.status = 'no-executor';\n diagnoseNode({ code: 'no-executor', message: `${node.type}: no executor registered` });\n return;\n }\n try {\n settle(result, await executor(node, actionContext));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n });\n };\n\n const walk = async (node: PdfActionNode, path: number[]): Promise<void> => {\n if (signal?.aborted) {\n cancelled = true;\n return;\n }\n await interpret(node, path);\n for (let index = 0; index < node.next.length && !cancelled; index++) {\n await walk(node.next[index], [...path, index]);\n }\n };\n await walk(tree.root, []);\n\n if (!documentFailed && !cancelled) {\n for (const entry of deferred) await entry.fire();\n }\n if (cancelled) return { status: 'cancelled', nodes, diagnostics };\n\n const anyExecuted = nodes.some((node) => node.status === 'executed');\n const anyFailedOrSkipped = nodes.some(\n (node) => node.status === 'failed' || node.status === 'skipped',\n );\n const status: ActionDispatchResult['status'] = anyExecuted\n ? anyFailedOrSkipped\n ? 'partial'\n : 'executed'\n : anyFailedOrSkipped\n ? 'partial'\n : 'inert';\n return { status, nodes, diagnostics };\n }\n\n return { run };\n}\nexport type ActionsRunner = ReturnType<typeof createRunner>;\n","/**\n * Trigger resolution helpers: the `triggers` setting, the per-page cache of annotations bearing page-lifecycle trees (the fan-out's\n * read amplifier) and ISO 32000-2 Table 197's page-step order.\n */\nimport type {\n AnnotationRef,\n DocumentEvent,\n PageObjectNumber,\n PageRef,\n PdfActionTree,\n PdfAnnotationActions,\n PdfPageActions,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionSource, ActionTrigger } from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { readPageAnnotations } from '../services/annotation-rows';\n\n/** An annotation that carries at least one page-lifecycle tree (/PO, /PC, /PV, /PI), as read. */\ninterface LifecycleAnnotation {\n readonly ref: AnnotationRef;\n readonly actions: PdfAnnotationActions;\n}\n\n/**\n * The pages whose annotations an event changes: those pages, every page\n * (`'all'`: a redaction, a skipped stretch of the stream, new document\n * bytes), or none.\n */\nconst annotationPagesOf = (event: DocumentEvent): readonly PageRef[] | 'all' | null => {\n switch (event.type) {\n case 'annotations.created':\n case 'annotations.updated':\n case 'annotations.deleted':\n case 'annotations.reordered':\n case 'annotations.flattened':\n case 'forms.widgetsReordered':\n return [event.page];\n // A form write can add, move or remove widgets, which carry page actions too.\n case 'forms.created':\n case 'forms.deleted':\n case 'forms.widgetAdded':\n case 'forms.widgetRemoved':\n case 'forms.widgetDeleted':\n case 'forms.widgetRestored':\n case 'forms.widgetUpdated':\n case 'forms.restored':\n case 'forms.repaired':\n return 'all';\n case 'pages.flattened':\n return event.pages;\n case 'redaction.applied':\n case 'stream.desynced':\n case 'document.versioned':\n return 'all';\n default:\n return null;\n }\n};\n\nexport function createTriggers(\n ctx: ActionsContext,\n { settings, form }: Pick<ActionsServices, 'settings' | 'form'>,\n) {\n const triggerEnabled = (trigger: ActionTrigger): boolean => {\n const { triggers } = settings.get();\n switch (trigger.scope) {\n case 'activate':\n return true; // the click door is never gated\n case 'annotation':\n return triggers.annotation;\n case 'page':\n return triggers.page;\n case 'document':\n return triggers.document;\n }\n };\n\n // Per page, the pending or settled read of its lifecycle-bearing\n // annotations. Reads start only inside the queued operation that needs\n // them, so a trigger sees every change made by the operations queued\n // before it. Holding the promise lets concurrent readers share one read,\n // and dropping it on invalidation means a read that was in flight when its\n // page changed is never reused afterwards.\n const lifecycleReads = new Map<PageObjectNumber, Promise<readonly LifecycleAnnotation[]>>();\n\n const lifecycleAnnotationsOf = (page: PageRef): Promise<readonly LifecycleAnnotation[]> => {\n const key = page.objectNumber;\n const cached = lifecycleReads.get(key);\n if (cached) return cached;\n const read = readPageAnnotations(ctx, form, page).then((annotations) =>\n annotations\n .filter(\n (annotation) =>\n annotation.actions &&\n (annotation.actions.pageOpen?.root ||\n annotation.actions.pageClose?.root ||\n annotation.actions.pageVisible?.root ||\n annotation.actions.pageInvisible?.root),\n )\n .map((annotation) => ({ ref: annotation.ref, actions: annotation.actions! })),\n );\n lifecycleReads.set(key, read);\n // A failed read is not kept: the next trigger for the page reads again.\n read.catch(() => {\n if (lifecycleReads.get(key) === read) lifecycleReads.delete(key);\n });\n return read;\n };\n\n /** Forget the pages a confirmed document event changed. */\n const invalidate = (event: DocumentEvent): void => {\n const pages = annotationPagesOf(event);\n if (pages === 'all') lifecycleReads.clear();\n else if (pages) for (const page of pages) lifecycleReads.delete(page.objectNumber);\n };\n\n /**\n * ISO 32000-2 Table 197 order: /PO \"shall be executed after the O action …\n * and the OpenAction entry\"; /PC \"shall be executed before the C action\".\n * Rootless trees are skipped (a budget-degraded tree with no root has\n * nothing to walk).\n */\n const planPageSteps = (\n event: 'open' | 'close' | 'visible' | 'invisible',\n page: PageRef,\n pageActions: PdfPageActions | undefined,\n lifecycle: readonly LifecycleAnnotation[],\n ): Array<{ source: ActionSource; tree: PdfActionTree }> => {\n const pageSource: ActionSource = { kind: 'page', page };\n const annotationSteps = (key: 'pageOpen' | 'pageClose' | 'pageVisible' | 'pageInvisible') =>\n lifecycle\n .filter((annotation) => annotation.actions[key]?.root)\n .map((annotation) => ({\n source: { kind: 'annotation', annotation: annotation.ref, page } as ActionSource,\n tree: annotation.actions[key]!,\n }));\n switch (event) {\n case 'open':\n return [\n ...(pageActions?.open?.root ? [{ source: pageSource, tree: pageActions.open }] : []),\n ...annotationSteps('pageOpen'),\n ];\n case 'close':\n return [\n ...annotationSteps('pageClose'),\n ...(pageActions?.close?.root ? [{ source: pageSource, tree: pageActions.close }] : []),\n ];\n case 'visible':\n return annotationSteps('pageVisible');\n case 'invisible':\n return annotationSteps('pageInvisible');\n }\n };\n\n return { triggerEnabled, lifecycleAnnotationsOf, invalidate, planPageSteps };\n}\nexport type ActionsTriggers = ReturnType<typeof createTriggers>;\n","/**\n * The verb-shaped document events (/WC, /WS, /DS, /WP, /DP) and the print\n * door: one catalog lifecycle tree per event, run inside the current queue\n * operation and never throwing (a broken script must not cancel the user's\n * save or print), and the adapter print wrapped /WP → print → /DP under the\n * print latch.\n */\nimport { PluginError, type OperationOptions } from '@embedpdf/core';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionNodeStatus,\n ActionOrigin,\n ActionsCapability,\n ActionStepResult,\n ActionTriggerResult,\n DocumentTriggerEvent,\n} from '../contract';\nimport type { DispatchCore } from '../dispatch/core';\nimport { foldSteps } from '../dispatch/fold';\nimport type { ActionsServices } from '../services';\nimport type { ActionsOpenSequence } from './open-sequence';\n\nexport function createDocumentEvents(\n services: Pick<\n ActionsServices,\n 'events' | 'catalog' | 'queue' | 'ports' | 'authority' | 'printLatch' | 'settings'\n >,\n {\n ensureOpenSequenceBeforeDocEvent,\n }: Pick<ActionsOpenSequence, 'ensureOpenSequenceBeforeDocEvent'>,\n { runAndEmit }: DispatchCore,\n) {\n const { reportDiagnostic } = services.events;\n const { readDocumentActions, DOC_EVENT_TREES } = services.catalog;\n const { enqueue, budget } = services.queue;\n const ports = services.ports.slots;\n const { allowsPrint } = services.authority;\n const printLatch = services.printLatch;\n\n /**\n * Run one catalog lifecycle tree inside the current queue operation, shared\n * by the dispatch path, `runDocumentVerb` and the print wrapper. Never\n * throws: a read or resolution failure degrades to a diagnostic, because a\n * broken script must not cancel the user's save or print.\n */\n const runDocEventTreeSafe = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionStepResult | null> => {\n if (!services.settings.get().triggers.document) return null;\n try {\n await ensureOpenSequenceBeforeDocEvent();\n const snapshot = await readDocumentActions();\n const tree = snapshot?.[DOC_EVENT_TREES[event]];\n if (!tree?.root && !tree?.incomplete) return null;\n const actionContext: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: event },\n };\n return { source: { kind: 'document' }, tree, result: await runAndEmit(tree, actionContext) };\n } catch (error) {\n diagnose({\n code: 'trigger-failed',\n message: `${event}: ${error instanceof Error ? error.message : String(error)}`,\n });\n return null;\n }\n };\n\n /** The dispatch-path body for a verb-shaped document event. */\n const runDocumentEventOp = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnostics: ActionDiagnostic[],\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionTriggerResult> => {\n const step = await runDocEventTreeSafe(event, diagnose);\n return foldSteps(step ? [step] : [], diagnostics);\n };\n\n /**\n * Both adapter print paths (the Named Print verb, and script `doc.print()`\n * effects from the actions plane) go through here: /WP →\n * `ports.uiAdapter.print` exactly once → /DP, with the latch reset in\n * `finally`. While the latch is held (including `runDocumentVerb('print')`'s\n * body) a nested request is suppressed with `reentrant-print`. An adapter\n * throw skips /DP (the latch still resets). /DP fires when the adapter call\n * returns, since a browser cannot observe dialog completion.\n */\n const firePrintThroughAdapter = async (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n if (printLatch.active) {\n diagnose({\n code: 'reentrant-print',\n message:\n 'print request during a document print event — suppressed (one dialog per request)',\n });\n return { status: 'blocked', detail: 'reentrant print suppressed' };\n }\n if (!allowsPrint()) {\n diagnose({ code: 'blocked', message: 'print: doc.print is not allowed' });\n return { status: 'blocked', detail: 'doc.print is not allowed' };\n }\n if (!ports.uiAdapter) {\n diagnose({ code: 'no-adapter', message: 'print: no UI adapter installed' });\n return { status: 'no-executor', detail: 'no UI adapter installed' };\n }\n printLatch.active = true;\n try {\n await runDocEventTreeSafe('will-print', diagnose);\n const adapter = ports.uiAdapter;\n if (!adapter) return { status: 'no-executor', detail: 'UI adapter uninstalled mid-print' };\n if (uiContext) adapter.print(uiContext);\n else adapter.print();\n await runDocEventTreeSafe('did-print', diagnose);\n return { status: 'executed' };\n } finally {\n printLatch.active = false;\n }\n };\n\n return {\n runDocumentEventOp,\n firePrintThroughAdapter,\n api: {\n runDocumentVerb: <T>(\n verb: 'save' | 'print',\n operation: () => Promise<T> | T,\n options?: OperationOptions,\n ): Promise<T> =>\n enqueue(async () => {\n budget.scriptNodes = 0; // one script budget for the whole verb operation\n const diagnose = (diagnostic: ActionDiagnostic): void =>\n reportDiagnostic(diagnostic, { source: { kind: 'document' } });\n const before = verb === 'save' ? ('will-save' as const) : ('will-print' as const);\n const after = verb === 'save' ? ('did-save' as const) : ('did-print' as const);\n const body = async (): Promise<T> => {\n // A before-event failure never cancels the user's verb;\n // runDocEventTreeSafe already degrades to diagnostics.\n await runDocEventTreeSafe(before, diagnose);\n // The caller can still cancel here; once the operation started,\n // it finishes, and so does its after-event.\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'actions', `${verb} was cancelled`, {\n cause: options.signal.reason,\n });\n }\n // `operation()` throwing skips the after-event and rethrows: no\n // /DS for a failed save.\n const value = await operation();\n await runDocEventTreeSafe(after, diagnose);\n return value;\n };\n if (verb !== 'print') return body();\n // The print verb holds the print latch for its whole body, so a /WP\n // or /DP script calling doc.print() is suppressed instead of\n // opening a second dialog.\n printLatch.active = true;\n try {\n return await body();\n } finally {\n printLatch.active = false;\n }\n }, options),\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsDocumentEvents = ReturnType<typeof createDocumentEvents>;\n","/**\n * The document-open sequence and its latch. The sequence runs the open\n * destination (as a lifecycle GoTo), then the catalog /OpenAction, and only\n * then releases the page-lifecycle barrier, so the first page /O fires after\n * both. It fires once: at the earliest of a UI adapter installing or the\n * first user-origin dispatch (`'auto'`), at bringup (`'headless'`), or never\n * (`'off'`, which still releases the barrier). Unless it is off, it runs\n * before the first verb-shaped document event (/WS, /WP, /WC, …).\n */\nimport type { Unsubscribe } from '@embedpdf/core';\nimport type { PdfActionTree } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionsCapability,\n ActionStepResult,\n ActionTriggerResult,\n} from '../contract';\nimport type { DispatchCore } from '../dispatch/core';\nimport { foldSteps } from '../dispatch/fold';\nimport type { ActionsServices } from '../services';\nimport type { ActionsPageLifecycle } from './page-lifecycle';\n\nexport function createOpenSequence(\n services: Pick<ActionsServices, 'events' | 'catalog' | 'queue' | 'ports' | 'settings'>,\n { releaseBarrier, resetCascade }: Pick<ActionsPageLifecycle, 'releaseBarrier' | 'resetCascade'>,\n { runAndEmit }: DispatchCore,\n) {\n const { reportDiagnostic, openSequenceCompleted } = services.events;\n /** The `openSequence` setting, read when it decides: it applies until the sequence has run. */\n const mode = () => services.settings.get().openSequence;\n const { readDocumentActions } = services.catalog;\n const { enqueue } = services.queue;\n const ports = services.ports.slots;\n let openFired = false;\n let sawUserActivity = false;\n\n /** The sequence body. Runs inside the queue (through dispatch or the\n * latch's own enqueue); callers guarantee `openFired` was set. */\n const runOpenSequenceOp = async (): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const steps: ActionStepResult[] = [];\n const openContext: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: 'open' },\n };\n try {\n const snapshot = await readDocumentActions();\n if (snapshot?.openDestination) {\n // The initial view reuses the whole spine (stage's goto executor,\n // policy included) as a synthesized lifecycle goto.\n const tree: PdfActionTree = {\n root: {\n type: 'goto',\n subtype: 'GoTo',\n destination: snapshot.openDestination,\n next: [],\n },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n };\n steps.push({\n source: { kind: 'document' },\n tree,\n result: await runAndEmit(tree, openContext),\n });\n }\n if (snapshot?.openAction?.root || snapshot?.openAction?.incomplete) {\n steps.push({\n source: { kind: 'document' },\n tree: snapshot.openAction,\n result: await runAndEmit(snapshot.openAction, openContext),\n });\n }\n } catch (error) {\n const diagnostic: ActionDiagnostic = {\n code: 'trigger-failed',\n message: `open sequence failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { source: { kind: 'document' } });\n } finally {\n // Release after the document steps, on every path; page-open emission\n // enqueues behind this operation (never awaited here: awaiting our own\n // queue would deadlock).\n releaseBarrier(true);\n }\n const result = foldSteps(steps, diagnostics);\n openSequenceCompleted.emit({ result });\n return result;\n };\n\n /**\n * The catalog /OpenAction never runs after a /WS, /WP or /WC script: before\n * the first verb-shaped document event, an armed but unfired open sequence\n * runs inline (the caller is already inside the queue; `runOpenSequenceOp`\n * never enqueues). It does not wait for the initial page /O: the guarantee\n * is catalog-level.\n */\n const ensureOpenSequenceBeforeDocEvent = async (): Promise<void> => {\n if (openFired || mode() === 'off') return;\n openFired = true;\n await runOpenSequenceOp();\n };\n\n const maybeFireOpenSequence = (): void => {\n if (openFired) return;\n if (mode() === 'off') {\n // The sequence never runs, but feeds must not buffer forever.\n openFired = true;\n releaseBarrier(false);\n return;\n }\n if (!ports.uiAdapter && mode() !== 'headless' && !sawUserActivity) return;\n openFired = true;\n void enqueue(() => runOpenSequenceOp());\n };\n\n const noteUserActivity = (): void => {\n resetCascade();\n if (!sawUserActivity) {\n sawUserActivity = true;\n maybeFireOpenSequence();\n }\n };\n\n /** Claim the one-shot open for a dispatched document-open trigger: false\n * when it already fired (the caller reports a replay). */\n const claim = (): boolean => {\n if (openFired) return false;\n openFired = true;\n return true;\n };\n\n return {\n run: runOpenSequenceOp,\n ensureOpenSequenceBeforeDocEvent,\n noteUserActivity,\n claim,\n /** Arm the latch at bringup: fires immediately for 'headless', releases\n * the barrier for 'off', waits for an adapter or user activity for 'auto'. */\n arm: maybeFireOpenSequence,\n api: {\n setUiAdapter: (adapter): Unsubscribe => {\n ports.uiAdapter = adapter;\n // An adapter arriving is the usual trigger of the open sequence.\n if (adapter) maybeFireOpenSequence();\n return () => {\n // Identity-safe: never wipe a successor installed after us.\n if (ports.uiAdapter === adapter) ports.uiAdapter = null;\n };\n },\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsOpenSequence = ReturnType<typeof createOpenSequence>;\n","/**\n * The lifecycle coordinator's page half: the document-open barrier and the\n * cascade budget. The stage owns page truth (it reports through\n * `reportPageState`); this owns when page-lifecycle triggers fire: nothing\n * emits before the document-open sequence has run (or was declared off or\n * headless), and emission is a diff against the last-emitted state, so\n * pre-open motion collapses to one open with no phantom close.\n */\nimport { toPageRef } from '@embedpdf/core';\nimport type { PageObjectNumber } from '@embedpdf/engine-core/runtime';\n\nimport type { DispatchCore } from '../dispatch/core';\nimport type { ActionsHostCapability, PageStateReport } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\n\n/** Consecutive programmatic rounds after which page-lifecycle emission is suppressed. */\nconst CASCADE_LIMIT = 8;\n\nexport function createPageLifecycle(\n ctx: ActionsContext,\n { events, settings }: Pick<ActionsServices, 'events' | 'settings'>,\n { dispatch }: DispatchCore,\n) {\n const { reportDiagnostic } = events;\n let barrierOpen = false;\n let bufferedReport: PageStateReport | null = null;\n let lastEmitted: {\n current: PageObjectNumber | null;\n visible: Set<PageObjectNumber>;\n } = {\n current: null,\n visible: new Set(),\n };\n let cascadeRounds = 0;\n\n const emitForReport = (report: PageStateReport): void => {\n if (report.cause === 'user') cascadeRounds = 0;\n const current = report.currentPage === null ? null : report.currentPage.objectNumber;\n const nextVisible = new Set(report.visiblePages.map((page) => page.objectNumber));\n const changedCurrent = current !== lastEmitted.current;\n const leaving = [...lastEmitted.visible].filter(\n (pageObjectNumber) => !nextVisible.has(pageObjectNumber),\n );\n const entering = [...nextVisible].filter(\n (pageObjectNumber) => !lastEmitted.visible.has(pageObjectNumber),\n );\n if (!changedCurrent && leaving.length === 0 && entering.length === 0) return;\n const previousCurrent = lastEmitted.current;\n // Track truth even when suppressed: the budget bounds emission, not state.\n lastEmitted = { current, visible: nextVisible };\n if (report.cause === 'programmatic') {\n cascadeRounds += 1;\n if (cascadeRounds > CASCADE_LIMIT) {\n reportDiagnostic({\n code: 'cascade-budget',\n message: `page-lifecycle emission suppressed: ${cascadeRounds} consecutive programmatic rounds (cap ${CASCADE_LIMIT})`,\n });\n return;\n }\n }\n // Canonical order (ISO leaves the cross-page order unspecified; within a\n // page, planPageSteps holds Table 197's /PO-after-/O and /PC-before-/C):\n // close(previous) → invisible set → visible set → open(current).\n if (changedCurrent && previousCurrent !== null) {\n void dispatch({ scope: 'page', event: 'close', page: toPageRef(previousCurrent) });\n }\n for (const pageObjectNumber of leaving) {\n void dispatch({ scope: 'page', event: 'invisible', page: toPageRef(pageObjectNumber) });\n }\n for (const pageObjectNumber of entering) {\n void dispatch({ scope: 'page', event: 'visible', page: toPageRef(pageObjectNumber) });\n }\n if (changedCurrent && current !== null) {\n void dispatch({ scope: 'page', event: 'open', page: toPageRef(current) });\n }\n };\n\n const reportPageState = (report: PageStateReport): void => {\n if (!report.placed) return;\n if (report.cause === 'user') cascadeRounds = 0;\n if (!barrierOpen) {\n bufferedReport = report; // coalesce: only the latest pre-open state matters\n return;\n }\n emitForReport(report);\n };\n\n const releaseBarrier = (fireFallback: boolean): void => {\n barrierOpen = true;\n const report = bufferedReport;\n bufferedReport = null;\n try {\n if (report) {\n emitForReport(report);\n } else if (fireFallback && settings.get().openSequence === 'headless') {\n // The initial page open falls back to the document's first page only\n // in declared-headless mode (no stage will ever report). In 'auto',\n // the stage report owns the initial open: firing a first-page /O\n // before a restored view reports would be exactly the phantom open\n // the coordinator exists to prevent; a stage-less 'auto' embedder\n // drives page triggers itself or declares headless.\n const first = ctx.document()?.pages[0]?.ref.objectNumber;\n if (first !== undefined) {\n lastEmitted = { current: first, visible: lastEmitted.visible };\n void dispatch({ scope: 'page', event: 'open', page: toPageRef(first) });\n }\n }\n } catch (error) {\n // The barrier is open either way: feeds must never stay buffered.\n reportDiagnostic({\n code: 'trigger-failed',\n message: `barrier release failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n };\n\n return {\n releaseBarrier,\n /** A user gesture resets the programmatic-cascade counter. */\n resetCascade: (): void => {\n cascadeRounds = 0;\n },\n api: { reportPageState } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsPageLifecycle = ReturnType<typeof createPageLifecycle>;\n","/**\n * Script world building (a page-scoped prefetch: the form as the user sees it\n * plus the annotations of the page the action runs on) and the event bridge between\n * two standards: the /AA keys are ISO 32000-2 Table 200; the event names\n * live in the JavaScript API layer (ISO 21757-1, Acrobat).\n */\nimport { scriptFieldsFromSnapshot } from '@embedpdf/core-acrojs';\nimport type {\n ScriptAnnotInput,\n ScriptColorArray,\n ScriptEventInput,\n ScriptWorldInput,\n} from '@embedpdf/core-acrojs';\nimport { pdfRectOf, rgbOf, toPageRef } from '@embedpdf/engine-core/runtime';\nimport type { FormSnapshot, PageObjectNumber } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionContext } from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\n\nexport function createScriptWorld(ctx: ActionsContext, { form }: Pick<ActionsServices, 'form'>) {\n // Acrobat's JavaScript keeps colors as color arrays, so they convert here, at its edge.\n const engineColorToArray = (color: string | null | undefined): ScriptColorArray => {\n if (!color) return ['T'];\n const { r, g, b } = rgbOf(color);\n return ['RGB', r / 255, g / 255, b / 255];\n };\n\n const scriptWorldFor = async (\n pageObjectNumber: PageObjectNumber,\n ): Promise<{ snapshot: FormSnapshot; world: Omit<ScriptWorldInput, 'event'> }> => {\n const page = toPageRef(pageObjectNumber);\n const snapshot = await form.read();\n const layout = ctx.getPage(page);\n const pageIndex = Math.max(0, layout?.index ?? -1);\n const { annotations } = await ctx.doc.page(page).annotations.list();\n const annots: ScriptAnnotInput[] = annotations\n // Script-addressable = everything except links and widgets (they are\n // Link and Field objects in Acrobat and separate planes here).\n .filter(\n (annotation) => annotation.subtype !== 'link' && !annotation.subtype.startsWith('widget'),\n )\n .map((annotation) => {\n // Acrobat's JavaScript keeps an annotation's rect in the file's\n // numbers, [x_ll, y_ll, x_ur, y_ur], so it converts here, at its edge.\n const inFile = layout ? pdfRectOf(annotation.rect, layout.pdfCropBox) : null;\n const styled = annotation as unknown as {\n color?: string;\n interiorColor?: string | null;\n opacity?: number;\n strokeWidth?: number;\n borderStyle?: string;\n dashArray?: number[];\n };\n return {\n ref: annotation.ref,\n name: annotation.nm ?? '',\n subtype: annotation.subtype,\n page: pageIndex,\n rect: (inFile\n ? [inFile.left, inFile.bottom, inFile.right, inFile.top]\n : [0, 0, 0, 0]) as [number, number, number, number],\n contents: annotation.contents ?? '',\n author: annotation.author ?? '',\n subject: annotation.subject ?? '',\n strokeColor: engineColorToArray(styled.color),\n fillColor: engineColorToArray(styled.interiorColor),\n opacity: styled.opacity ?? 1,\n width: styled.strokeWidth ?? 1,\n borderStyle: styled.borderStyle === 'dashed' ? ('D' as const) : ('S' as const),\n dash: styled.dashArray ?? [],\n hidden: annotation.hidden,\n print: annotation.print,\n readOnly: annotation.readOnly,\n locked: annotation.locked,\n noView: annotation.noView,\n toggleNoView: annotation.toggleNoView,\n opaqueBody: annotation.subtype === 'stamp',\n };\n });\n return {\n snapshot,\n world: {\n fields: scriptFieldsFromSnapshot(snapshot),\n annots,\n annotPages: [pageIndex],\n annotsCoverDocument: (ctx.document()?.pageCount ?? 0) <= 1,\n },\n };\n };\n\n const ANNOTATION_EVENT_NAMES: Record<string, string> = {\n cursorEnter: 'Mouse Enter',\n cursorExit: 'Mouse Exit',\n mouseDown: 'Mouse Down',\n mouseUp: 'Mouse Up',\n focus: 'Focus',\n blur: 'Blur',\n };\n const PAGE_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n close: 'Close',\n // /PV and /PI have no Acrobat event name: these two are an EmbedPDF extension.\n visible: 'Visible',\n invisible: 'Invisible',\n };\n // The /AA keys are ISO 32000-2 Table 200; the event names live in the\n // JavaScript API layer (ISO 21757-1, Acrobat).\n const DOC_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n 'will-save': 'WillSave',\n 'did-save': 'DidSave',\n 'will-print': 'WillPrint',\n 'did-print': 'DidPrint',\n 'will-close': 'WillClose',\n };\n\n const scriptEventFor = (\n actionContext: ActionContext,\n snapshot: FormSnapshot,\n ): ScriptEventInput => {\n const provenance = actionContext.event;\n const type =\n provenance.scope === 'page'\n ? 'Page'\n : provenance.scope === 'document'\n ? 'Doc'\n : actionContext.source.kind === 'widget'\n ? 'Field'\n : actionContext.source.kind === 'link'\n ? 'Link'\n : 'Annot'; // EmbedPDF extension — Acrobat has no plain-annot type\n const name =\n provenance.scope === 'activate'\n ? 'Mouse Up'\n : provenance.scope === 'annotation'\n ? (ANNOTATION_EVENT_NAMES[provenance.name] ?? 'Mouse Up')\n : provenance.scope === 'page'\n ? (PAGE_EVENT_NAMES[provenance.name] ?? 'Open')\n : (DOC_EVENT_NAMES[provenance.name] ?? 'Open');\n const targetRef =\n actionContext.source.kind === 'widget' ? actionContext.source.field : undefined;\n const targetField = targetRef\n ? snapshot.fields.find((field) =>\n targetRef.kind === 'objectNumber' && field.ref.kind === 'objectNumber'\n ? field.ref.objectNumber === targetRef.objectNumber\n : targetRef.kind === 'fqn' && field.name === targetRef.name,\n )\n : undefined;\n return {\n kind: 'widget-activate',\n type,\n name,\n ...(targetRef ? { target: targetRef, source: targetRef } : {}),\n ...(targetField && targetField.valueEntry.kind === 'scalar'\n ? { value: targetField.valueEntry.value }\n : {}),\n };\n };\n\n return { scriptWorldFor, scriptEventFor };\n}\n","/**\n * The `javascript` executor: one node is one host transaction with prefetch →\n * boot (once) → run → commit → surface inside the boundary. Print and submit\n * effects are external: replayed after the transaction releases, still inside\n * the queued dispatch operation.\n */\nimport type { ScriptOutput, ScriptUiEffect } from '@embedpdf/core-acrojs';\n\nimport type {\n ActionDiagnostic,\n ActionNodeStatus,\n ActionOrigin,\n ActionsScriptEnvironment,\n} from '../contract';\nimport type { AnnotCommitEntry } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { intentOfSubmitEffect } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\nimport type { ActionsRealm } from './realm';\nimport type { ActionsScriptSurface } from './surface';\nimport { createScriptWorld } from './world';\n\ntype FirePrint = (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n) => Promise<{ status: ActionNodeStatus; detail?: string }>;\n\n/** The default cap on JavaScript nodes one dispatch may run. */\nconst DEFAULT_SCRIPT_NODES_PER_DISPATCH = 16;\n\nexport function registerScriptExecutor(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'events' | 'ports' | 'queue' | 'form'>,\n environment: ActionsScriptEnvironment,\n { scriptHost }: Pick<ActionsRealm, 'scriptHost'>,\n { performSubmit }: ActionsSubmit,\n { surfaceScriptResult }: Pick<ActionsScriptSurface, 'surfaceScriptResult'>,\n documentEvents: { firePrintThroughAdapter: FirePrint },\n): void {\n const { reportDiagnostic } = services.events;\n const ports = services.ports.slots;\n const { budget } = services.queue;\n const { firePrintThroughAdapter } = documentEvents;\n const { scriptWorldFor, scriptEventFor } = createScriptWorld(ctx, services);\n\n /** Commit one run's document effects through the owner sinks in the\n * declared order (form first, then annotations); the first failure skips\n * the rest across both streams. Returns the failure summary, if any. */\n const commitScriptOutput = async (\n output: ScriptOutput,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<string | null> => {\n let failure: string | null = null;\n if (output.formEffects.length > 0) {\n if (!ports.formCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script form effects dropped: no form commit sink registered (${output.formEffects.length})`,\n });\n } else {\n const result = await ports.formCommitSink(output.formEffects);\n if (result.status === 'failed') failure = `form effects: ${result.error ?? 'failed'}`;\n }\n }\n if (output.annotEffects.length > 0) {\n if (failure) {\n diagnose({\n code: 'executor-failed',\n message: `script annot effects skipped after form failure (${output.annotEffects.length})`,\n });\n } else if (!ports.annotCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script annot effects dropped: no annotation commit sink registered (${output.annotEffects.length})`,\n });\n } else {\n const entries: AnnotCommitEntry[] = output.annotEffects.map((effect) => ({\n annotObjectNumber: effect.ref.kind === 'objectNumber' ? effect.ref.objectNumber : -1,\n ...(effect.ref.kind === 'objectNumber' ? { page: effect.ref.page } : {}),\n patch: effect.patch,\n }));\n const result = await ports.annotCommitSink(entries);\n const firstFailure = result.results.find((entry) => entry.status === 'failed');\n if (firstFailure)\n failure = `annotation ${firstFailure.annotObjectNumber}: ${firstFailure.error ?? 'failed'}`;\n }\n }\n if (failure) diagnose({ code: 'executor-failed', message: `script commit: ${failure}` });\n return failure;\n };\n\n if (!scriptHost) return;\n const nodeLimit = environment.maxScriptNodesPerDispatch ?? DEFAULT_SCRIPT_NODES_PER_DISPATCH;\n ports.executors.set('javascript', async (node, actionContext) => {\n if (node.type !== 'javascript') return { status: 'inert', reason: 'not a JS node' };\n if (budget.scriptNodes >= nodeLimit) {\n return {\n status: 'inert',\n reason: `dispatch script budget exhausted (${nodeLimit} JS nodes)`,\n };\n }\n budget.scriptNodes += 1;\n const source = actionContext.source;\n const firstPage = ctx.document()?.pages[0]?.ref.objectNumber;\n const pageObjectNumber =\n source.kind === 'widget' || source.kind === 'page'\n ? source.page.objectNumber\n : source.kind === 'link' || source.kind === 'annotation'\n ? (source.page?.objectNumber ?? firstPage)\n : firstPage;\n if (pageObjectNumber === undefined) {\n return { status: 'inert', reason: 'no page to anchor the world on' };\n }\n const diagnose = (diagnostic: ActionDiagnostic): void =>\n reportDiagnostic(diagnostic, { action: 'javascript', source });\n // Print and submit effects are external: the /WP and /DP wrap runs\n // action trees (which may need their own host transactions) and the\n // submit dataset must be resolved from post-commit truth, so both run\n // after the transaction releases, still inside this queued operation.\n const pendingExternal: Array<{\n effect: Extract<ScriptUiEffect, { kind: 'print' | 'submitForm' }>;\n phase: 'boot' | 'user';\n }> = [];\n const splitExternal = (output: ScriptOutput, phase: 'boot' | 'user'): ScriptUiEffect[] =>\n output.uiEffects.filter((effect) => {\n if (effect.kind === 'print' || effect.kind === 'submitForm') {\n pendingExternal.push({ effect, phase });\n return false;\n }\n return true;\n });\n const outcome = await scriptHost.transaction<\n { status: 'executed' } | { status: 'failed'; error: string }\n >(async (transaction) => {\n let built = await scriptWorldFor(pageObjectNumber);\n const boot = await transaction.boot({\n ...built.world,\n event: { kind: 'name-tree-boot', type: 'Doc', name: 'Open' },\n });\n if (boot) {\n // Boot effects belong to this first transaction; a boot fault only\n // degrades, never blocks. Refetch the world afterwards so the run\n // sees post-boot truth.\n await commitScriptOutput(boot, diagnose);\n surfaceScriptResult({\n uiEffects: splitExternal(boot, 'boot'),\n diagnostics: boot.diagnostics,\n ...(boot.error ? { error: boot.error } : {}),\n origin: actionContext.origin,\n phase: 'boot',\n realm: 'document',\n source,\n });\n if (boot.formEffects.length || boot.annotEffects.length) {\n built = await scriptWorldFor(pageObjectNumber);\n }\n }\n const output = await transaction.run(node.script, {\n ...built.world,\n event: scriptEventFor(actionContext, built.snapshot),\n });\n surfaceScriptResult({\n uiEffects: splitExternal(output, 'user'),\n diagnostics: output.diagnostics,\n ...(output.error ? { error: output.error } : {}),\n origin: actionContext.origin,\n phase: 'user',\n realm: 'document',\n source,\n });\n if (output.error) return { status: 'failed', error: output.error.message };\n const failure = await commitScriptOutput(output, diagnose);\n return failure ? { status: 'failed', error: failure } : { status: 'executed' };\n });\n for (const entry of pendingExternal) {\n if (entry.effect.kind === 'print') {\n await firePrintThroughAdapter(\n { origin: actionContext.origin, phase: entry.phase },\n diagnose,\n );\n } else {\n await performSubmit(intentOfSubmitEffect(entry.effect), actionContext, diagnose);\n }\n }\n return outcome;\n });\n}\n","import {\n createScriptHost,\n DEFAULT_SCRIPT_BUDGET,\n resolveScriptIdentity,\n seedFrom,\n type ScriptBudget,\n type ScriptHost,\n} from '@embedpdf/core-acrojs';\nimport type { DocumentHandle } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsScriptEnvironment, ActionsScriptIdentity } from '../contract';\nimport type { ScriptRealmTarget } from '../host-contract';\n\n/**\n * The scripting environment, the session-level half of the JavaScript\n * switch: sandbox factory, identity, clock, timezone, seed and budget. Policy\n * (`enabled`) decides whether one exists; realms are minted from it.\n *\n * One environment mints any number of realms: the owning document's own\n * host, and detached realms for documents that are not the viewer document\n * (a stamp asset, a template). Every realm gets a fresh sandbox from the\n * factory: the same policy and environment, isolated globals.\n *\n * Identity closes over the owning document: who the user is, is a session\n * fact resolved from the owner's claims plus the `javascript.identity`\n * setting as it is at each run, never from a detached document's\n * (authority-less) handle.\n */\nexport interface ScriptRealmFactory {\n realmFor(target: ScriptRealmTarget): ScriptHost;\n /** The embedder's budget (or the default): the per-run budget every minted\n * realm enforces, and the transaction aggregate consumers apply. */\n readonly budget: ScriptBudget;\n}\n\nexport function createScriptRealmFactory(\n environment: ActionsScriptEnvironment,\n identity: () => ActionsScriptIdentity | undefined,\n identityDoc: DocumentHandle,\n): ScriptRealmFactory {\n const sandboxFactory =\n environment.sandboxFactory ??\n (() =>\n import('@embedpdf/core-js-sandbox').then(({ createQuickJsSandbox }) =>\n createQuickJsSandbox(),\n ));\n const budget = environment.budget ?? DEFAULT_SCRIPT_BUDGET;\n return {\n budget,\n realmFor: (target) =>\n createScriptHost({\n sandboxFactory,\n document: () => {\n const documentInfo = target.document();\n return {\n id: target.doc.id,\n fileName: environment.fileName?.() ?? documentInfo?.name ?? 'document.pdf',\n pageCount: documentInfo?.pageCount ?? 0,\n pageNumber: 0,\n };\n },\n identity: () => resolveScriptIdentity(identityDoc, identity()),\n environment: (sequence) => {\n const nowMs = environment.now?.() ?? Date.now();\n return {\n nowMs,\n utcOffsetMinutes:\n environment.utcOffsetMinutes?.() ?? -new Date(nowMs).getTimezoneOffset(),\n randomSeed: environment.randomSeed?.() ?? seedFrom(target.doc.id, sequence),\n };\n },\n bootSources: target.bootSources,\n budget,\n }),\n };\n}\n","/**\n * The one ScriptHost per document. The `javascript.enabled` setting, as it is\n * when the document opens, decides whether a realm factory exists; the\n * factory carries the session environment and mints this document's own\n * realm here, and detached realms on demand (host lens): one environment, any\n * number of isolated realms.\n */\nimport { javaScriptProgramFromActionTree, type ScriptTransaction } from '@embedpdf/core-acrojs';\n\nimport type { ActionsScriptEnvironment } from '../contract';\nimport type { ActionsHostCapability } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { createScriptRealmFactory } from './environment';\n\nexport function createRealm(\n ctx: ActionsContext,\n { catalog, settings }: Pick<ActionsServices, 'catalog' | 'settings'>,\n environment: ActionsScriptEnvironment,\n) {\n const { readDocumentActions } = catalog;\n const realms = settings.get().javascript.enabled\n ? createScriptRealmFactory(\n environment,\n () => settings.get().javascript.identity ?? undefined,\n ctx.doc,\n )\n : null;\n const scriptHost = realms\n ? realms.realmFor({\n doc: ctx.doc,\n document: () => ctx.document(),\n bootSources: async () => {\n const snapshot = await readDocumentActions();\n return (snapshot?.nameTreeScripts ?? []).map(({ action }) =>\n javaScriptProgramFromActionTree(action),\n );\n },\n })\n : null;\n if (scriptHost) ctx.cleanup(() => scriptHost.dispose());\n\n return {\n scriptHost,\n api: {\n isScriptingEnabled: () => scriptHost !== null,\n ...(scriptHost && realms\n ? {\n scriptRealm: {\n transaction: <T>(body: (transaction: ScriptTransaction) => Promise<T>) =>\n scriptHost.transaction(body),\n budget: realms.budget,\n },\n createDetachedScriptRealm: (target) => {\n const host = realms.realmFor(target);\n return {\n transaction: <T>(body: (transaction: ScriptTransaction) => Promise<T>) =>\n host.transaction(body),\n budget: realms.budget,\n dispose: () => host.dispose(),\n };\n },\n }\n : {}),\n } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsRealm = ReturnType<typeof createRealm>;\n","/**\n * The surface door: the one UI and diagnostic port for script results. Print\n * and submitForm effects from the actions plane never reach it (the\n * JavaScript executor extracts them and routes them through\n * `firePrintThroughAdapter` and `performSubmit` after the transaction, since\n * the /WP and /DP wrap and the post-commit dataset must run outside the host\n * transaction). Such effects here come from the form pipeline's K/V/C/F path.\n */\nimport type { ActionOrigin, ActionSource } from '../contract';\nimport type {\n ActionsHostCapability,\n ScriptCommitSurface,\n ScriptRealmKind,\n ScriptSurfaceResult,\n} from '../host-contract';\nimport type { ActionsServices } from '../services';\nimport { intentOfSubmitEffect } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\n\nexport function createScriptSurface(\n services: Pick<ActionsServices, 'events' | 'ports' | 'authority' | 'printLatch'>,\n { performSubmit }: ActionsSubmit,\n) {\n const { reportDiagnostic, scriptDiagnosticReported, scriptFailed } = services.events;\n const ports = services.ports.slots;\n const { allowsPrint } = services.authority;\n const printLatch = services.printLatch;\n\n const surfaceScriptResult = (result: ScriptSurfaceResult): void => {\n const uiContext = { origin: result.origin, phase: result.phase };\n const source = result.source ?? null;\n for (const effect of result.uiEffects) {\n // A detached realm has no document surface: the document it scripted\n // is not displayed, and this door's print, goto and submit act on this\n // document. Only alerts have a valid target (the user); everything\n // else is suppressed observably, never routed to the wrong document.\n if (result.realm === 'detached' && effect.kind !== 'alert') {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: `script ${effect.kind} request from a detached realm suppressed: no document surface`,\n });\n continue;\n }\n if (effect.kind === 'submitForm') {\n // A form-pipeline scripted submit: the same door, not awaited (the\n // form queue must not wait on submit sinks). Policy, sinks and\n // diagnostics all live inside performSubmit.\n void performSubmit(\n intentOfSubmitEffect(effect),\n {\n origin: result.origin,\n source: result.source ?? { kind: 'api' },\n event: { scope: 'activate' },\n },\n (diagnostic) => reportDiagnostic(diagnostic, { action: 'javascript', source }),\n );\n continue;\n }\n // Permission, not preference: a print request without doc.print\n // authority reaches no adapter; not overridable, and observable.\n if (effect.kind === 'print' && !allowsPrint()) {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request withheld: doc.print is not allowed',\n });\n continue;\n }\n // The print latch: a /WP or /DP script (or anything running while a\n // print wrapper is active) printing again is suppressed, so there is\n // one dialog per outer request.\n if (effect.kind === 'print' && printLatch.active) {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request during a document print event — suppressed (reentrant)',\n });\n continue;\n }\n if (!ports.uiAdapter) {\n reportDiagnostic(\n { code: 'no-adapter', message: `script ${effect.kind}: no UI adapter installed` },\n { action: 'javascript', source },\n );\n continue;\n }\n if (effect.kind === 'alert') {\n ports.uiAdapter.alert?.(effect.message, {\n ...uiContext,\n icon: effect.icon,\n ...(effect.title !== undefined ? { title: effect.title } : {}),\n });\n } else if (effect.kind === 'gotoPage') {\n ports.uiAdapter.gotoPage?.(effect.page, uiContext);\n } else {\n ports.uiAdapter.print(uiContext);\n }\n }\n for (const diagnostic of result.diagnostics) scriptDiagnosticReported.emit(diagnostic);\n if (result.error) scriptFailed.emit({ error: result.error, source });\n };\n\n /** A K/V/C/F commit surfaces as up to two results: the boot phase (only\n * when it produced effects) and the user phase (always — it carries the\n * diagnostics and the error). */\n const surfaceScriptCommit = (\n commit: ScriptCommitSurface,\n context: { origin: ActionOrigin; realm: ScriptRealmKind; source?: ActionSource },\n ): void => {\n const phases: Array<'boot' | 'user'> = ['boot', 'user'];\n for (const phase of phases) {\n const uiEffects = commit.uiEffects.filter((effect) => effect.phase === phase);\n if (uiEffects.length === 0 && phase === 'boot') continue;\n surfaceScriptResult({\n uiEffects,\n diagnostics: phase === 'user' ? commit.diagnostics : [],\n ...(phase === 'user' && commit.error ? { error: commit.error } : {}),\n origin: context.origin,\n phase,\n realm: context.realm,\n ...(context.source ? { source: context.source } : {}),\n });\n }\n };\n\n return {\n surfaceScriptResult,\n api: { surfaceScriptResult, surfaceScriptCommit } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsScriptSurface = ReturnType<typeof createScriptSurface>;\n","/** Session authority the action plane enforces itself (permission, not preference). */\nimport type { ActionsContext } from './context';\n\nexport function createAuthority(ctx: ActionsContext) {\n const allowsPrint = (): boolean => ctx.allows('doc.print');\n return { allowsPrint };\n}\n","/**\n * The one catalog-actions read. The catalog /AA is immutable in a session (no\n * writer exists in the stack), so the open sequence, the boot sources and the\n * five document events share one memoized read; a rejected read is evicted,\n * so a transient failure cannot poison every later lifecycle event.\n */\nimport type { DocumentActionsSnapshot } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\n\n/** The ISO 32000-2 Table 200 key for each verb-shaped document trigger event. */\nconst DOC_EVENT_TREES = {\n 'will-save': 'willSave',\n 'did-save': 'didSave',\n 'will-print': 'willPrint',\n 'did-print': 'didPrint',\n 'will-close': 'willClose',\n} as const;\n\nexport function createCatalog(ctx: ActionsContext) {\n let snapshotRead: Promise<DocumentActionsSnapshot | null> | null = null;\n const readDocumentActions = (): Promise<DocumentActionsSnapshot | null> => {\n if (!snapshotRead) {\n const service = ctx.doc.actions;\n const read: Promise<DocumentActionsSnapshot | null> = service\n ? Promise.resolve(service.get())\n : Promise.resolve(null);\n const memoized: Promise<DocumentActionsSnapshot | null> = read.catch((error: unknown) => {\n if (snapshotRead === memoized) snapshotRead = null;\n throw error;\n });\n snapshotRead = memoized;\n }\n return snapshotRead;\n };\n return { readDocumentActions, DOC_EVENT_TREES };\n}\nexport type ActionsCatalog = ReturnType<typeof createCatalog>;\n","/** The plugin's events, disposed with it, and the one way a diagnostic is reported. */\nimport type { PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionDiagnostic,\n ActionDiagnosticReportedEvent,\n ActionExecutedEvent,\n ActionSource,\n OpenSequenceCompletedEvent,\n ScriptDiagnosticReportedEvent,\n ScriptFailedEvent,\n} from '../contract';\nimport type { ActionsContext } from './context';\n\n/** Which action a diagnostic is about, and what started it, when one is concerned. */\nexport interface DiagnosticPlace {\n readonly action?: PdfActionType | null;\n readonly source?: ActionSource | null;\n}\n\nexport function createEvents(ctx: ActionsContext) {\n const executed = ctx.events.source<ActionExecutedEvent>();\n const diagnosticReported = ctx.events.source<ActionDiagnosticReportedEvent>();\n return {\n executed,\n diagnosticReported,\n scriptDiagnosticReported: ctx.events.source<ScriptDiagnosticReportedEvent>(),\n scriptFailed: ctx.events.source<ScriptFailedEvent>(),\n openSequenceCompleted: ctx.events.source<OpenSequenceCompletedEvent>(),\n /** Fire `onDiagnosticReported` with the action and source it concerns (`null` for none). */\n reportDiagnostic(diagnostic: ActionDiagnostic, place: DiagnosticPlace = {}): void {\n diagnosticReported.emit({\n code: diagnostic.code,\n action: place.action ?? null,\n source: place.source ?? null,\n });\n },\n };\n}\nexport type ActionsEvents = ReturnType<typeof createEvents>;\n","/**\n * The form, as scripts and dispatch read it: the form plugin's view, its fields with this\n * session's pending fills, when it registered one (`registerFormReader`); the engine's\n * otherwise.\n */\nimport type { FormSnapshot } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\nimport type { ActionPorts } from './ports';\n\nexport interface ActionsForm {\n /** The form now. `read` wraps an engine read, so the caller's signal can stop it. */\n read(read?: <T>(task: Promise<T>) => Promise<T>): Promise<FormSnapshot>;\n}\n\nexport function createForm(ctx: ActionsContext, ports: ActionPorts): ActionsForm {\n return {\n read: (read = (task) => task) => {\n const shown = ports.formReader?.();\n return shown ? Promise.resolve(shown) : read(ctx.doc.forms.list());\n },\n };\n}\n","/**\n * The registration slots: every port a sibling or the embedder installs. One\n * owner: the slots live here; areas read them at call time (never captured),\n * and every disposer is identity-safe (it clears a slot only while the\n * registrant is still current). Executors are last-wins. No capability read\n * exposes a slot, so installing one wakes no reader.\n */\nimport type { Unsubscribe } from '@embedpdf/core';\nimport type { PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionExecutor, ActionSubmitHandler, ActionUiAdapter } from '../contract';\nimport type {\n ActionsHostCapability,\n AnnotCommitSink,\n FormCommitSink,\n FormReader,\n SubmitResolver,\n} from '../host-contract';\nimport type { ActionsEvents } from './events';\n\nexport interface ActionPorts {\n readonly executors: Map<PdfActionType, ActionExecutor>;\n annotCommitSink: AnnotCommitSink | null;\n formCommitSink: FormCommitSink | null;\n /** The form plugin's form, as the user sees it. */\n formReader: FormReader | null;\n uiAdapter: ActionUiAdapter | null;\n /** Sink 1 of the submit chain (consent = installation). */\n submitHandler: ActionSubmitHandler | null;\n /** The form plugin's dataset resolver: the one door every submit resolves through. */\n submitResolver: SubmitResolver | null;\n}\n\nexport function createPorts({ reportDiagnostic }: Pick<ActionsEvents, 'reportDiagnostic'>) {\n const ports: ActionPorts = {\n executors: new Map(),\n annotCommitSink: null,\n formCommitSink: null,\n formReader: null,\n uiAdapter: null,\n submitHandler: null,\n submitResolver: null,\n };\n const api = {\n registerExecutor: (type, executor): Unsubscribe => {\n if (ports.executors.has(type)) {\n reportDiagnostic(\n { code: 'duplicate-executor', message: `executor for '${type}' replaced (last-wins)` },\n { action: type },\n );\n }\n ports.executors.set(type, executor);\n return () => {\n if (ports.executors.get(type) === executor) ports.executors.delete(type);\n };\n },\n registerAnnotCommitSink: (sink): Unsubscribe => {\n ports.annotCommitSink = sink;\n return () => {\n if (ports.annotCommitSink === sink) ports.annotCommitSink = null;\n };\n },\n registerFormCommitSink: (sink): Unsubscribe => {\n ports.formCommitSink = sink;\n return () => {\n if (ports.formCommitSink === sink) ports.formCommitSink = null;\n };\n },\n registerFormReader: (reader): Unsubscribe => {\n ports.formReader = reader;\n return () => {\n if (ports.formReader === reader) ports.formReader = null;\n };\n },\n setSubmitHandler: (handler): Unsubscribe => {\n ports.submitHandler = handler;\n // Not an open-sequence release: that stays the UI adapter's role.\n return () => {\n if (ports.submitHandler === handler) ports.submitHandler = null;\n };\n },\n registerSubmitResolver: (resolver): Unsubscribe => {\n ports.submitResolver = resolver;\n return () => {\n if (ports.submitResolver === resolver) ports.submitResolver = null;\n };\n },\n } satisfies Partial<ActionsHostCapability>;\n return { slots: ports, api };\n}\n","/**\n * The document-print latch: while a print wrapper is active\n * (`firePrintThroughAdapter`, `runDocumentVerb('print')`), a nested print\n * request is suppressed (`reentrant-print`), so the adapter opens exactly one\n * dialog per outer request. Read by the script surface, held by the\n * document-events area.\n */\nexport interface PrintLatch {\n active: boolean;\n}\n\nexport const createPrintLatch = (): PrintLatch => ({ active: false });\n","/**\n * The one serial queue every dispatch, verb and open sequence rides, plus the\n * per-operation script budget: the JavaScript nodes run in the current queue\n * operation, reset at every operation boundary and read by the executor, so a\n * /Next chain shares one deterministic cap.\n */\nimport type { ActionsContext } from './context';\n\nexport function createQueue(ctx: ActionsContext) {\n const enqueue = ctx.serialQueue('actions');\n const budget = { scriptNodes: 0 };\n return { enqueue, budget };\n}\nexport type ActionsQueue = ReturnType<typeof createQueue>;\n","/**\n * Plugin-private services every area is built on: the settings, the events,\n * the policy decision, the registration ports, the serial queue, the catalog\n * read, the form, session authority and the print latch.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { ActionsSettings } from '../contract';\nimport { createAuthority } from './authority';\nimport { createCatalog, type ActionsCatalog } from './catalog';\nimport type { ActionsContext } from './context';\nimport { createEvents, type ActionsEvents } from './events';\nimport { createForm, type ActionsForm } from './form';\nimport { createPolicy, type ActionsPolicy } from './policy';\nimport { createPorts } from './ports';\nimport { createPrintLatch, type PrintLatch } from './print-latch';\nimport { createQueue, type ActionsQueue } from './queue';\n\nexport type { ActionsContext } from './context';\n\nexport interface ActionsServices {\n /** The plugin's settings: read `get()` where a setting is used, so a change applies at once. */\n readonly settings: Settings<ActionsSettings>;\n readonly events: ActionsEvents;\n readonly policy: ActionsPolicy;\n readonly ports: ReturnType<typeof createPorts>;\n readonly queue: ActionsQueue;\n readonly catalog: ActionsCatalog;\n /** The form scripts and dispatch read: the form plugin's view, else the engine's. */\n readonly form: ActionsForm;\n readonly authority: ReturnType<typeof createAuthority>;\n readonly printLatch: PrintLatch;\n}\n\nexport function createServices(ctx: ActionsContext): ActionsServices {\n const events = createEvents(ctx);\n const ports = createPorts(events);\n return {\n settings: ctx.settings(),\n events,\n policy: createPolicy(ctx),\n ports,\n queue: createQueue(ctx),\n catalog: createCatalog(ctx),\n form: createForm(ctx, ports.slots),\n authority: createAuthority(ctx),\n printLatch: createPrintLatch(),\n };\n}\n","/**\n * The submit pipeline: one intent, one resolver, one sink chain. Both submit\n * sources (a SubmitForm node, a script `doc.submitForm()`) land in\n * `performSubmit` after policy. Never a network call from this plugin.\n */\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionNodeStatus,\n ActionsScriptEnvironment,\n ActionSubmitRequest,\n SubmitIntent,\n} from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { toFormSubmissionRequest } from './intent';\n\nexport function createSubmit(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'policy' | 'ports' | 'events'>,\n environment: ActionsScriptEnvironment,\n) {\n const policy = services.policy;\n const ports = services.ports.slots;\n const { reportDiagnostic } = services.events;\n const nowMs = (): number => environment.now?.() ?? Date.now();\n\n /**\n * The one submit door. Sink order: the embedder handler (explicit beats\n * ambient; its promise is not awaited) → the document's home\n * (`doc.forms.submit`, engine-asserted and awaited: a real operation with a\n * real receipt) → blocked with `no-submit-sink`.\n */\n const performSubmit = async (\n intent: SubmitIntent,\n actionContext: ActionContext,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const decision = policy.current()['submit-form'][actionContext.origin];\n if (decision !== 'adapter' && decision !== 'allow') {\n // `block` refuses quietly; `report` says so.\n if (decision === 'report') {\n diagnose({\n code: 'blocked',\n message: `submit-form: policy 'report' for origin '${actionContext.origin}'`,\n });\n }\n return { status: 'blocked' };\n }\n if (!ports.submitResolver) {\n diagnose({\n code: 'no-submit-resolver',\n message: 'submit-form: no dataset resolver registered (form plugin missing?)',\n });\n return { status: 'blocked', detail: 'no dataset resolver' };\n }\n let request: ActionSubmitRequest;\n try {\n request = await ports.submitResolver(intent, actionContext, diagnose);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit-form: dataset resolution: ${detail}` });\n return { status: 'failed', detail };\n }\n const forms = ctx.doc.forms;\n const homeSubmit =\n typeof forms.submit === 'function'\n ? () =>\n Promise.resolve(\n forms.submit!(toFormSubmissionRequest(request, new Date(nowMs()).toISOString())),\n )\n : null;\n if (ports.submitHandler) {\n try {\n const outcome = ports.submitHandler(request, { submitToDocumentHome: homeSubmit });\n if (outcome && typeof (outcome as Promise<void>).then === 'function') {\n // Not awaited, by contract: `executed` means \"handed to the\n // embedder\"; a later rejection is a diagnostic, never a rewrite of\n // the node result.\n void (outcome as Promise<void>).catch((error: unknown) => {\n reportDiagnostic(\n {\n code: 'executor-failed',\n message: `submit handler rejected (detached): ${\n error instanceof Error ? error.message : String(error)\n }`,\n },\n { action: 'submit-form', source: actionContext.source },\n );\n });\n }\n return { status: 'executed' };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit handler threw: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n if (homeSubmit) {\n try {\n await homeSubmit();\n return { status: 'executed' };\n } catch (error) {\n // The engine's refusal (authority, transport) surfaces on the node:\n // enforcement lives at the home's boundary, this only reports it.\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `document home refused submit: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n diagnose({\n code: 'no-submit-sink',\n message: 'submit-form: no handler installed and the document has no submit-capable home',\n });\n return { status: 'blocked', detail: 'no submit sink' };\n };\n\n return { performSubmit };\n}\nexport type ActionsSubmit = ReturnType<typeof createSubmit>;\n","/**\n * The actions controller: the composition root. It builds the plugin's\n * services once, wires each area with the services it declares, and\n * assembles the host capability from the areas' API slices. No behavior\n * lives here: every verb and read has a home in `submit/`, `scripting/`,\n * `dispatch/` or `lifecycle/`. The plugin keeps no session state: its rules\n * are its settings, and its live data (ports, queue, latches) are resources\n * of the areas.\n */\nimport { composeApi } from '@embedpdf/core';\n\nimport type { ActionsConfig } from './contract';\nimport type { DispatchCore } from './dispatch/core';\nimport { createDispatcher } from './dispatch/dispatcher';\nimport { createRunner } from './dispatch/run';\nimport { createTriggers } from './dispatch/triggers';\nimport type { ActionsHostCapability } from './host-contract';\nimport { createDocumentEvents } from './lifecycle/document-events';\nimport { createOpenSequence } from './lifecycle/open-sequence';\nimport { createPageLifecycle } from './lifecycle/page-lifecycle';\nimport { registerScriptExecutor } from './scripting/executor';\nimport { createRealm } from './scripting/realm';\nimport { createScriptSurface } from './scripting/surface';\nimport { createServices, type ActionsContext } from './services';\nimport { createSubmit } from './submit/perform';\n\n/**\n * `config` is what the app registered; the settings in it reach the\n * controller through `ctx.settings()`, and only the script environment is\n * read from it here.\n */\nexport function createActionsController(ctx: ActionsContext, config: ActionsConfig = {}) {\n const services = createServices(ctx);\n const { events, ports, settings } = services;\n\n // The lifecycle areas dispatch and run trees through the dispatcher that\n // is assembled last, bound late and explicitly (see `dispatch/core.ts`).\n const core: DispatchCore = {\n dispatch: (trigger) => dispatcher.dispatch(trigger),\n runAndEmit: (tree, actionContext) => dispatcher.runAndEmit(tree, actionContext),\n };\n\n const environment = config.javascript ?? {};\n const submit = createSubmit(ctx, services, environment);\n const realm = createRealm(ctx, services, environment);\n const surface = createScriptSurface(services, submit);\n const pageLifecycle = createPageLifecycle(ctx, services, core);\n const openSequence = createOpenSequence(services, pageLifecycle, core);\n const documentEvents = createDocumentEvents(services, openSequence, core);\n const triggers = createTriggers(ctx, services);\n const runner = createRunner(ctx, services, submit, documentEvents);\n const dispatcher = createDispatcher(\n ctx,\n services,\n runner,\n triggers,\n openSequence,\n documentEvents,\n );\n registerScriptExecutor(ctx, services, environment, realm, submit, surface, documentEvents);\n\n const api: ActionsHostCapability = composeApi('actions', [\n settings.api,\n ports.api,\n realm.api,\n surface.api,\n pageLifecycle.api,\n openSequence.api,\n documentEvents.api,\n dispatcher.api,\n {\n onExecuted: events.executed.on,\n onDiagnosticReported: events.diagnosticReported.on,\n onScriptDiagnosticReported: events.scriptDiagnosticReported.on,\n onScriptFailed: events.scriptFailed.on,\n onOpenSequenceCompleted: events.openSequenceCompleted.on,\n },\n ]);\n\n return {\n api,\n connect() {\n // Confirmed document events of every origin invalidate the per-page\n // lifecycle-annotation cache.\n ctx.listen(ctx.doc.events, (event) => triggers.invalidate(event));\n // Fires the open sequence at once for 'headless', releases the page\n // barrier for 'off', and waits for an adapter or user activity for 'auto'.\n openSequence.arm();\n // The document's save actions (/WS, /DS) run around every download of its file, so\n // what WillSave changes is in the bytes.\n ctx.aroundDownload((read) => documentEvents.api.runDocumentVerb('save', read));\n },\n };\n}\n","/** The settings in what the app registered with `actionsPlugin(config)`. */\nimport type { DeepPartial } from '@embedpdf/core';\n\nimport type { ActionsConfig, ActionsSettings } from './contract';\n\n/** `config` without the script environment, which is no setting: what the settings register. */\nexport function registeredSettings(\n config: ActionsConfig | undefined,\n): DeepPartial<ActionsSettings> | undefined {\n if (!config) return undefined;\n const { javascript } = config;\n return {\n policy: config.policy,\n triggers: config.triggers,\n openSequence: config.openSequence,\n javascript: javascript && { enabled: javascript.enabled, identity: javascript.identity },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\n\nimport { ACTIONS_DEFAULTS, type ActionsConfig } from './contract';\nimport { createActionsController } from './controller';\nimport { ActionsToken } from './host-contract';\nimport { registeredSettings } from './settings';\n\n/**\n * The action engine, the dependency root of the action architecture. It\n * interprets extracted /A and /AA trees; it never detects triggers and never\n * imports another plugin's token: the stage, annotation, link and form\n * plugins optionally depend on it and register their executors and sinks\n * when they connect (the kernel's dependency order creates this plugin\n * first). JavaScript is one registered interpreter among many: Hide,\n * ResetForm, GoTo and Named work with scripting off. Document-scoped and\n * stateless; its settings are what the app registered over\n * {@link ACTIONS_DEFAULTS}.\n */\nexport const actionsPlugin = (config?: ActionsConfig) =>\n definePlugin({\n id: 'actions',\n token: ActionsToken,\n scope: 'document',\n settings: { defaults: ACTIONS_DEFAULTS, registered: registeredSettings(config) },\n create: (ctx) => createActionsController(ctx, config),\n });\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,eAAsB,oBACpB,KACA,MACA,MACA,QAA6C,SAAS,MAC/B;CACvB,MAAM,CAAC,aAAa,WAAW,MAAM,QAAQ,IAAI,CAC/C,IAAI,OAAO,mBAAmB,IAC1B,KAAK,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,SAAS,KAAK,WAAW,IAC3E,QAAQ,QAAQ,CAAC,CAAC,GACtB,IAAI,OAAO,gBAAgB,IACvB,KACG,KAAK,IAAI,CAAC,CACV,MAAM,aACL,SAAS,QAAQ,QAAQ,WAAW,OAAO,KAAK,iBAAiB,KAAK,YAAY,CACpF,IACF,QAAQ,QAAQ,CAAC,CAAC,CACxB,CAAC;CACD,OAAO,CAAC,GAAG,aAAa,GAAG,OAAO;AACpC;;;;;;AAOA,e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B,YAAY,mBAAmB,MAAM;CAAE;CAC/E,SAAS,QAAQ,wBAAwB,KAAK,MAAM;AACtD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["PluginError","triggerOriginOf","eventOf","PluginError","DEFAULT_SCRIPT_BUDGET","DocumentsToken","ActionsToken","ACTIONS_DEFAULTS"],"sources":["../src/services/annotation-rows.ts","../src/dispatch/fold.ts","../src/dispatch/dispatcher.ts","../src/services/policy.ts","../src/submit/intent.ts","../src/dispatch/run.ts","../src/dispatch/triggers.ts","../src/lifecycle/document-events.ts","../src/lifecycle/open-sequence.ts","../src/lifecycle/page-lifecycle.ts","../src/scripting/world.ts","../src/scripting/executor.ts","../src/scripting/environment.ts","../src/scripting/realm.ts","../src/scripting/surface.ts","../src/services/authority.ts","../src/services/catalog.ts","../src/services/document-print.ts","../src/services/events.ts","../src/services/form.ts","../src/services/ports.ts","../src/services/print-latch.ts","../src/services/queue.ts","../src/services/index.ts","../src/submit/perform.ts","../src/controller.ts","../src/settings.ts","../src/actions.plugin.ts"],"sourcesContent":["/**\n * The annotations an action can live on, of both read families: a page's\n * annotations (`doc.annotations`, `doc.annotate.read`) and its widgets, which\n * come with the form (`ActionsForm`, `doc.forms.read`). Each family is read\n * only when the session may read it, so a fill-only session still finds its\n * widgets' actions.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type PageRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\nimport type { ActionsForm } from './form';\n\n/** Every annotation of a page the session may read: its annotations, then its widgets. */\nexport async function readPageAnnotations(\n ctx: ActionsContext,\n form: ActionsForm,\n page: PageRef,\n read: <T>(task: Promise<T>) => Promise<T> = (task) => task,\n): Promise<Annotation[]> {\n const [annotations, widgets] = await Promise.all([\n ctx.allows('doc.annotate.read')\n ? read(ctx.doc.page(page).annotations.list()).then((list) => list.annotations)\n : Promise.resolve([]),\n ctx.allows('doc.forms.read')\n ? form\n .read(read)\n .then((snapshot) =>\n snapshot.widgets.filter((widget) => widget.page.objectNumber === page.objectNumber),\n )\n : Promise.resolve([]),\n ]);\n return [...annotations, ...widgets];\n}\n\n/**\n * The annotation `ref` names, of either family, or `null` when the session\n * can't see it: the form's widgets first (most actions a viewer runs are a\n * field's), then the page's annotations.\n */\nexport async function readAnnotation(\n ctx: ActionsContext,\n form: ActionsForm,\n ref: AnnotationRef,\n read: <T>(task: Promise<T>) => Promise<T> = (task) => task,\n): Promise<Annotation | null> {\n const key = annotationKey(ref);\n const matches = (candidate: Annotation) => annotationKey(candidate.ref) === key;\n if (ctx.allows('doc.forms.read')) {\n const widget = (await form.read(read)).widgets.find(matches);\n if (widget) return widget;\n }\n if (!ctx.allows('doc.annotate.read')) return null;\n return (await read(ctx.doc.page(ref.page).annotations.list())).annotations.find(matches) ?? null;\n}\n","/** Aggregate step statuses. A step failure never skips its siblings; this\n * only folds what each step reported. Pure. */\nimport type { ActionDiagnostic, ActionStepResult, ActionTriggerResult } from '../contract';\n\nexport const foldSteps = (\n steps: ActionStepResult[],\n diagnostics: ActionDiagnostic[],\n): ActionTriggerResult => {\n const statuses = steps.map((step) => step.result.status);\n const status: ActionTriggerResult['status'] =\n steps.length === 0\n ? 'inert'\n : statuses.every((stepStatus) => stepStatus === 'refused')\n ? 'refused'\n : statuses.every((stepStatus) => stepStatus === 'inert')\n ? 'inert'\n : statuses.every((stepStatus) => stepStatus === 'executed')\n ? 'executed'\n : 'partial';\n return { status, steps, diagnostics };\n};\n","/**\n * The dispatcher: the one serialized queue every tree rides. `execute` runs\n * a resolved tree; `dispatch` resolves a trigger inside the queued operation\n * (submission order is execution order) and fans out through the lifecycle\n * areas. `runAndEmit` is the shared per-tree unit: run, then `onExecuted`.\n *\n * A caller's signal skips an operation that hasn't started, stops a\n * trigger's reads, and stops a tree before its next node. `execute` then\n * rejects `operation-cancelled`; `dispatch` never rejects, so it resolves\n * `cancelled`.\n */\nimport { isPluginError, PluginError, type OperationOptions } from '@embedpdf/core';\nimport { annotationKey, type PdfActionTree } from '@embedpdf/engine-core/runtime';\n\nimport { eventOf, triggerOriginOf } from '../contract';\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionOrigin,\n ActionsCapability,\n ActionSource,\n ActionStepResult,\n ActionTreeSource,\n ActionTrigger,\n ActionTriggerEvent,\n ActionTriggerResult,\n PdfNamedAction,\n} from '../contract';\nimport type { ActionsDocumentEvents } from '../lifecycle/document-events';\nimport type { ActionsOpenSequence } from '../lifecycle/open-sequence';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { readAnnotation } from '../services/annotation-rows';\nimport { foldSteps } from './fold';\nimport type { ActionsRunner } from './run';\nimport type { ActionsTriggers } from './triggers';\n\n/** The source a trigger reports for: what its diagnostics carry before a tree is found. */\nconst sourceOfTrigger = (trigger: ActionTrigger): ActionSource => {\n switch (trigger.scope) {\n case 'activate':\n case 'annotation':\n return trigger.source ?? { kind: 'annotation', annotation: trigger.ref, page: trigger.page };\n case 'page':\n return { kind: 'page', page: trigger.page };\n case 'document':\n return { kind: 'document' };\n }\n};\n\nconst cancelled = (operation: string, signal: AbortSignal | undefined) =>\n new PluginError('operation-cancelled', 'actions', `${operation} was cancelled`, {\n cause: signal?.reason,\n });\n\nexport function createDispatcher(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'events' | 'policy' | 'queue' | 'catalog' | 'authority' | 'form'>,\n { run }: ActionsRunner,\n { triggerEnabled, lifecycleAnnotationsOf, planPageSteps }: ActionsTriggers,\n openSequence: Pick<ActionsOpenSequence, 'noteUserActivity' | 'claim' | 'run'>,\n { runDocumentEventOp }: Pick<ActionsDocumentEvents, 'runDocumentEventOp'>,\n) {\n const { executed, reportDiagnostic } = services.events;\n const { decisionFor } = services.policy;\n const { allowsPrint } = services.authority;\n const { enqueue, budget } = services.queue;\n const { readDocumentActions, DOC_EVENT_TREES } = services.catalog;\n const { form } = services;\n const { noteUserActivity } = openSequence;\n\n /** Run one tree and announce it: the shared per-tree unit (queued by\n * `execute`; called inline per step by the queued trigger resolver). */\n const runAndEmit = async (\n tree: PdfActionTree,\n actionContext: ActionContext,\n signal?: AbortSignal,\n ): Promise<ActionDispatchResult> => {\n const result = await run(tree, actionContext, signal);\n executed.emit({ tree, result, source: actionContext.source });\n return result;\n };\n\n const execute = (\n tree: PdfActionTree,\n actionContext: ActionContext,\n options?: OperationOptions,\n ): Promise<ActionDispatchResult> => {\n const signal = options?.signal;\n // Before enqueueing: a real user gesture arms the open sequence (its\n // operation then lands ahead of this action in the queue) and resets the\n // cascade budget.\n if (actionContext.origin === 'user') noteUserActivity();\n return enqueue(async () => {\n budget.scriptNodes = 0; // one script budget per dispatch\n const result = await runAndEmit(tree, actionContext, signal);\n if (result.status === 'cancelled') throw cancelled('actions.execute', signal);\n return result;\n }, options);\n };\n\n const canExecute = (tree: PdfActionTree, actionContext: ActionContext): boolean => {\n if (tree.incomplete || !tree.root) return false;\n const decision = decisionFor(tree.root, actionContext.origin);\n return decision === 'allow' || decision === 'adapter';\n };\n\n const runSteps = async (\n steps: Array<{ source: ActionSource; tree: PdfActionTree }>,\n origin: ActionOrigin,\n event: ActionTriggerEvent,\n diagnostics: ActionDiagnostic[],\n signal: AbortSignal | undefined,\n ): Promise<ActionTriggerResult> => {\n const results: ActionStepResult[] = [];\n for (const step of steps) {\n if (signal?.aborted) break;\n const result = await runAndEmit(step.tree, { origin, source: step.source, event }, signal);\n results.push({ source: step.source, tree: step.tree, result });\n }\n if (signal?.aborted) return { status: 'cancelled', steps: results, diagnostics };\n return foldSteps(results, diagnostics);\n };\n\n /** Everything a trigger needs, reads included, inside the queued operation:\n * submission order is execution order. Never throws. */\n const resolveAndRun = async (\n trigger: ActionTrigger,\n signal: AbortSignal | undefined,\n ): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const diagnose = (diagnostic: ActionDiagnostic): void => {\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { source: sourceOfTrigger(trigger) });\n };\n /** A read the caller's signal can stop. */\n const read = <T>(task: Promise<T>): Promise<T> => ctx.cancellable(signal, task);\n try {\n if (!triggerEnabled(trigger)) {\n diagnose({\n code: 'trigger-disabled',\n message: `${trigger.scope}: trigger family disabled by config`,\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n const origin = triggerOriginOf(trigger);\n switch (trigger.scope) {\n case 'activate':\n case 'annotation': {\n const event = trigger.scope === 'activate' ? 'activate' : trigger.event;\n const annotation = await readAnnotation(ctx, form, trigger.ref, read);\n // ISO 32000-2 Table 197: \"the A entry, if present, takes precedence\n // over [the /AA U entry]\"; a shadowed U tree is silently inert,\n // exactly like an absent one.\n if (event === 'mouseUp' && annotation?.actions?.activate) {\n return { status: 'inert', steps: [], diagnostics };\n }\n const tree = annotation?.actions?.[event];\n if (!tree?.root && !tree?.incomplete) return { status: 'inert', steps: [], diagnostics };\n const source = sourceOfTrigger(trigger);\n return await runSteps([{ source, tree }], origin, eventOf(trigger), diagnostics, signal);\n }\n case 'page': {\n // A shared read other triggers may wait on too: never aborted, only not awaited further.\n const lifecycle = await lifecycleAnnotationsOf(trigger.page);\n const pageActions = ctx.getPage(trigger.page)?.actions;\n const steps = planPageSteps(trigger.event, trigger.page, pageActions, lifecycle);\n return await runSteps(steps, origin, eventOf(trigger), diagnostics, signal);\n }\n case 'document': {\n if (trigger.event !== 'open') {\n return await runDocumentEventOp(trigger.event, diagnostics, diagnose);\n }\n if (!openSequence.claim()) {\n diagnose({\n code: 'open-sequence-replayed',\n message: 'document open sequence already fired for this document',\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n return await openSequence.run();\n }\n }\n } catch (error) {\n if (isPluginError(error, 'operation-cancelled') && signal?.aborted) {\n return { status: 'cancelled', steps: [], diagnostics };\n }\n diagnose({\n code: 'trigger-failed',\n message: `trigger resolution failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n return { status: 'refused', steps: [], diagnostics };\n }\n };\n\n const dispatch = (\n trigger: ActionTrigger,\n options?: OperationOptions,\n ): Promise<ActionTriggerResult> => {\n const signal = options?.signal;\n // A user-origin trigger is user activity (it arms the open sequence and\n // resets the cascade budget), noted before taking the queue slot, so an\n // armed open sequence runs first.\n if (triggerOriginOf(trigger) === 'user') noteUserActivity();\n return enqueue(() => {\n budget.scriptNodes = 0; // one script budget per dispatch\n return resolveAndRun(trigger, signal);\n }, options).catch(\n // Only a signal that fired while the trigger waited for its turn gets\n // here: resolveAndRun itself never throws.\n (): ActionTriggerResult => ({ status: 'cancelled', steps: [], diagnostics: [] }),\n );\n };\n\n /** The tree `executeNamed` runs, and its context: a click from your code unless `context` says otherwise. */\n const namedTree = (name: PdfNamedAction): PdfActionTree => ({\n root: { type: 'named', subtype: 'Named', name, next: [] },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n });\n const namedContext = (context?: Partial<ActionContext>): ActionContext => ({\n origin: 'user',\n source: { kind: 'api' },\n event: { scope: 'activate' },\n ...context,\n });\n\n const executeNamed = (\n name: PdfNamedAction,\n context?: Partial<ActionContext>,\n options?: OperationOptions,\n ): Promise<ActionDispatchResult> => execute(namedTree(name), namedContext(context), options);\n\n const canExecuteNamed = (name: PdfNamedAction, context?: Partial<ActionContext>): boolean =>\n canExecute(namedTree(name), namedContext(context)) && (name !== 'Print' || allowsPrint());\n\n /** The raw tree behind a source, read from the document, with no dispatch\n * rules applied (the /A-shadows-U rule lives in `resolveAndRun`). */\n const readActionTree = async (source: ActionTreeSource): Promise<PdfActionTree | null> => {\n switch (source.kind) {\n case 'annotation': {\n const annotation = await readAnnotation(ctx, form, source.annotation);\n const tree = annotation?.actions?.[source.event ?? 'activate'];\n return tree ?? null;\n }\n case 'field': {\n const { fields } = await form.read();\n const target = source.field;\n const field = fields.find((candidate) =>\n target.kind === 'objectNumber'\n ? candidate.ref.kind === 'objectNumber' &&\n candidate.ref.objectNumber === target.objectNumber\n : candidate.name === target.name,\n );\n return field?.actions?.[source.event] ?? null;\n }\n case 'page':\n return ctx.getPage(source.page)?.actions?.[source.event ?? 'open'] ?? null;\n case 'outline': {\n const { items } = await ctx.doc.outline.get();\n const item = items.find(\n (candidate) => candidate.ref.objectNumber === source.item.objectNumber,\n );\n return item?.action ?? null;\n }\n case 'document': {\n const snapshot = await readDocumentActions();\n if (!snapshot) return null;\n const event = source.event ?? 'open';\n return (event === 'open' ? snapshot.openAction : snapshot[DOC_EVENT_TREES[event]]) ?? null;\n }\n }\n };\n\n return {\n runAndEmit,\n dispatch,\n api: {\n execute,\n canExecute,\n executeNamed,\n canExecuteNamed,\n getActionTree: (source, options) => ctx.cancellable(options?.signal, readActionTree(source)),\n dispatch,\n // The synchronous twin: the trigger family is enabled. Per-tree truth\n // stays per step in the results; resolution is async and never\n // previewed here.\n canDispatch: (trigger) => triggerEnabled(trigger),\n prepareClose: (options): Promise<ActionTriggerResult> =>\n dispatch({ scope: 'document', event: 'will-close' }, options),\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsDispatcher = ReturnType<typeof createDispatcher>;\n","/**\n * The policy matrix (type × origin → decision): the fixed `never` and\n * unsupported sets, and the one decision function over the `policy` setting.\n * The setting itself (its defaults and its merge) is the plugin's settings.\n */\nimport type { PdfActionNode, PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionOrigin,\n ActionPolicy,\n ActionPolicyDecision,\n ActionPolicyRow,\n} from '../contract';\nimport type { ActionsContext } from './context';\n\n/** Never executable, not configurable — diagnostics only. */\nconst NEVER_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'launch',\n 'goto-remote',\n 'goto-embedded',\n 'sound',\n 'movie',\n 'import-data',\n]);\n\n/** Recognized types with no interpreter: reported, never executed. */\nconst UNSUPPORTED_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'rendition',\n 'thread',\n 'set-ocg-state',\n 'transition',\n 'goto-3d-view',\n 'unknown',\n]);\n\n/** Document-lifetime node types: engine mutations, committed in walk order. */\nexport const DOCUMENT_TYPES: ReadonlySet<PdfActionType> = new Set(['reset-form', 'javascript']);\n\nexport const isPrintVerb = (node: PdfActionNode): boolean =>\n node.type === 'named' && node.name === 'Print';\n\nexport function createPolicy(ctx: ActionsContext) {\n const settings = ctx.settings();\n /** The live policy: read at decision time, never captured. */\n const current = (): ActionPolicy => settings.get().policy;\n\n /** The decision for one node and origin; `'never'` and `'unsupported'` are fixed, not configurable. */\n const decisionFor = (\n node: PdfActionNode,\n origin: ActionOrigin,\n ): ActionPolicyDecision | 'never' | 'unsupported' => {\n if (NEVER_TYPES.has(node.type)) return 'never';\n if (UNSUPPORTED_TYPES.has(node.type)) return 'unsupported';\n const policy = current();\n if (isPrintVerb(node)) return policy.print[origin];\n const row = policy[node.type as keyof ActionPolicy] as ActionPolicyRow | undefined;\n return row ? row[origin] : 'unsupported';\n };\n\n return { decisionFor, current };\n}\nexport type ActionsPolicy = ReturnType<typeof createPolicy>;\n","/** The one normalized submit intent, from either source (an action node's\n * payload or a script `doc.submitForm()` effect), and the engine request\n * shape the document's home receives. Pure. */\nimport type { ScriptUiEffect } from '@embedpdf/core-acrojs';\nimport type {\n FormSubmissionRequest,\n IsoDateTime,\n SubmitFormPayload,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionSubmitRequest, SubmitIntent } from '../contract';\n\nexport const intentOfPayload = (payload: SubmitFormPayload): SubmitIntent => ({\n url: payload.url,\n fields: payload.fields,\n exclude: payload.flags.exclude,\n includeNoValueFields: payload.flags.includeNoValueFields,\n format: payload.flags.format,\n method: payload.flags.method,\n flagsRaw: payload.flags.raw,\n ...(payload.charSet === undefined ? {} : { charSet: payload.charSet }),\n});\n\nexport const toFormSubmissionRequest = (\n request: ActionSubmitRequest,\n sentAt: IsoDateTime,\n): FormSubmissionRequest => ({\n entries: request.entries,\n intent: {\n url: request.url,\n format: request.format,\n method: request.method,\n flagsRaw: request.flagsRaw,\n ...(request.charSet === undefined ? {} : { charSet: request.charSet }),\n },\n origin: request.origin,\n sentAt,\n});\n\n/** Script `doc.submitForm(...)` → the one normalized intent. Script field\n * names are include-mode by definition (Acrobat's aFields). */\nexport const intentOfSubmitEffect = (\n effect: Extract<ScriptUiEffect, { kind: 'submitForm' }>,\n): SubmitIntent => {\n const format = effect.format ?? 'fdf';\n return {\n url: effect.url,\n fields: effect.fieldNames?.map((name) => ({ kind: 'name' as const, name })) ?? null,\n exclude: false,\n includeNoValueFields: effect.includeEmpty,\n format,\n method: effect.method ?? 'post',\n flagsRaw: 0,\n };\n};\n","/**\n * The tree walker: policy per node, document-lifetime work in walk order\n * (Hide through the owner sinks, executors for the rest), and navigation and\n * external effects deferred until every document node succeeded. A caller's\n * signal that fires stops the walk before its next node, and nothing\n * deferred fires.\n */\nimport type {\n FormFieldRef,\n PdfActionNode,\n PdfActionTree,\n PdfActionType,\n} from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionExecutorResult,\n ActionNodeResult,\n ActionNodeStatus,\n} from '../contract';\nimport type { AnnotCommitEntry } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { DOCUMENT_TYPES, isPrintVerb } from '../services/policy';\nimport { intentOfPayload } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\nimport type { ActionsDocumentEvents } from '../lifecycle/document-events';\n\nexport function createRunner(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'policy' | 'ports' | 'events' | 'form'>,\n { performSubmit }: ActionsSubmit,\n { firePrintThroughAdapter }: Pick<ActionsDocumentEvents, 'firePrintThroughAdapter'>,\n) {\n const { decisionFor } = services.policy;\n const ports = services.ports.slots;\n const { reportDiagnostic } = services.events;\n const { form } = services;\n\n async function run(\n tree: PdfActionTree,\n actionContext: ActionContext,\n signal?: AbortSignal,\n ): Promise<ActionDispatchResult> {\n const diagnostics: ActionDiagnostic[] = [];\n /** Record a diagnostic in the result and report it, with the action it concerns. */\n const diagnose = (diagnostic: ActionDiagnostic, action: PdfActionType | null): void => {\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { action, source: actionContext.source });\n };\n\n // The law: never execute an incomplete tree — not even its root.\n if (tree.incomplete) {\n diagnose(\n { code: 'incomplete-tree', message: 'refused: the action tree is incomplete' },\n tree.root?.type ?? null,\n );\n return { status: 'refused', nodes: [], diagnostics };\n }\n if (!tree.root) return { status: 'inert', nodes: [], diagnostics };\n\n const nodes: ActionNodeResult[] = [];\n // Navigation and external effects are deferred thunks, fired only after\n // every document-lifetime node succeeded, in node order, so navigation\n // never yanks the user away from a failed write.\n const deferred: Array<{ result: ActionNodeResult; fire: () => Promise<void> | void }> = [];\n let documentFailed = false;\n let cancelled = false;\n\n const settle = (result: ActionNodeResult, outcome: ActionExecutorResult): void => {\n if (outcome.status === 'executed') result.status = 'executed';\n else if (outcome.status === 'inert') {\n result.status = 'inert';\n result.detail = outcome.reason;\n diagnose(\n { code: 'executor-inert', message: `${result.type}: ${outcome.reason}` },\n result.type,\n );\n } else {\n result.status = 'failed';\n result.detail = outcome.error;\n diagnose(\n { code: 'executor-failed', message: `${result.type}: ${outcome.error}` },\n result.type,\n );\n }\n };\n\n // A Hide action sets or clears the Hidden state (ISO 32000-2 §12.6.4.11):\n // a real mutation through the owning plane's commit sink, authority-gated\n // by the engine like every other write. Widgets are the forms plane's\n // visibility (the engine's field-level `setDisplay`, like Acrobat's\n // `field.display`; there is no per-widget annotation patch); plain\n // annotations are flag patches through the annotation sink.\n const interpretHide = async (\n node: Extract<PdfActionNode, { type: 'hide' }>,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const display = node.hide ? ('hidden' as const) : ('visible' as const);\n const diagnoseHide = (diagnostic: ActionDiagnostic): void => diagnose(diagnostic, 'hide');\n const fieldRefs: FormFieldRef[] = [];\n const annotEntries: AnnotCommitEntry[] = [];\n const names: string[] = [];\n const bareObjectNumbers: number[] = [];\n for (const target of node.targets) {\n if (target.kind === 'objectNumber') bareObjectNumbers.push(target.objectNumber);\n else names.push(target.name);\n }\n if (names.length || bareObjectNumbers.length) {\n const snapshot = await form.read();\n for (const name of names) {\n const field = snapshot.fields.find((candidate) => candidate.name === name);\n if (!field) {\n diagnoseHide({ code: 'unresolved-target', message: `hide: no field named '${name}'` });\n continue;\n }\n fieldRefs.push(field.ref);\n }\n for (const objectNumber of bareObjectNumbers) {\n // A bare object number may be a widget (its field's display) or a\n // plain annotation (its own flags): the forms snapshot decides.\n const owner = snapshot.fields.find((field) =>\n field.widgets.some((widget) => widget.objectNumber === objectNumber),\n );\n if (owner) {\n fieldRefs.push(owner.ref);\n } else {\n annotEntries.push({\n annotObjectNumber: objectNumber,\n patch: { flags: { hidden: node.hide } },\n });\n }\n }\n }\n let failedDetail: string | undefined;\n if (fieldRefs.length) {\n if (!ports.formCommitSink) {\n diagnoseHide({\n code: 'no-commit-sink',\n message: 'hide: no form commit sink registered (form plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const result = await ports.formCommitSink(\n fieldRefs.map((ref) => ({ kind: 'setDisplay', ref, display })),\n );\n if (result.status === 'failed') {\n failedDetail = result.error ?? 'failed';\n diagnoseHide({ code: 'executor-failed', message: `hide: ${failedDetail}` });\n }\n }\n if (annotEntries.length && !failedDetail) {\n if (!ports.annotCommitSink) {\n diagnoseHide({\n code: 'no-commit-sink',\n message: 'hide: no annotation commit sink registered (annotation plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const committed = await ports.annotCommitSink(annotEntries);\n const failed = committed.results.filter((entry) => entry.status === 'failed');\n for (const failure of failed) {\n diagnoseHide({\n code: 'executor-failed',\n message: `hide: annotation ${failure.annotObjectNumber}: ${failure.error ?? 'failed'}`,\n });\n }\n if (failed.length === committed.results.length && failed.length > 0) {\n failedDetail = failed[0]?.error;\n }\n }\n if (failedDetail) return { status: 'failed', detail: failedDetail };\n return { status: 'executed' };\n };\n\n const interpret = async (node: PdfActionNode, path: number[]): Promise<void> => {\n const result: ActionNodeResult = { path, type: node.type, status: 'blocked' };\n nodes.push(result);\n const decision = decisionFor(node, actionContext.origin);\n const diagnoseNode = (diagnostic: ActionDiagnostic): void => diagnose(diagnostic, node.type);\n\n if (decision === 'never' || decision === 'block' || decision === 'report') {\n result.status = 'blocked';\n // `block` refuses quietly; `report`, and a type that never runs, say so.\n if (decision !== 'block') {\n diagnoseNode({\n code: 'blocked',\n message: `${node.type}: ${decision === 'never' ? 'never executable' : `policy 'report' for origin '${actionContext.origin}'`}`,\n });\n }\n return;\n }\n if (decision === 'unsupported') {\n result.status = 'no-executor';\n return;\n }\n\n if (node.type === 'hide') {\n // A document mutation: an earlier document failure skips it, and its\n // own failure stops later document work and drops deferred effects.\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const outcome = await interpretHide(node);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n if (outcome.status === 'failed') documentFailed = true;\n return;\n }\n\n if (DOCUMENT_TYPES.has(node.type)) {\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const executor = ports.executors.get(node.type);\n if (!executor) {\n result.status = node.type === 'javascript' ? 'inert' : 'no-executor';\n diagnoseNode({\n code: 'no-executor',\n message: `${node.type}: no executor registered${node.type === 'javascript' ? ' (scripting unavailable)' : ''}`,\n });\n return;\n }\n try {\n settle(result, await executor(node, actionContext));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (result.status === 'failed') documentFailed = true;\n return;\n }\n\n if (node.type === 'submit-form') {\n if (!node.payload) {\n // A runtime that does not extract the submit payload: the node is\n // recognized but inert, and diagnosed.\n result.status = 'inert';\n result.detail = 'submit payload unavailable (older runtime extraction)';\n diagnoseNode({\n code: 'submit-payload-unavailable',\n message: 'submit-form: payload unavailable (older runtime extraction) — node inert',\n });\n return;\n }\n const payload = node.payload;\n // External like print and uri: deferred until every document-lifetime\n // node succeeded, so a submission never carries a half-failed form\n // state.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const outcome = await performSubmit(\n intentOfPayload(payload),\n actionContext,\n diagnoseNode,\n );\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n if (isPrintVerb(node) || node.type === 'uri') {\n // External: adapter-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n if (node.type === 'uri') {\n if (!ports.uiAdapter) {\n result.status = 'no-executor';\n diagnoseNode({\n code: 'no-adapter',\n message: `${node.type}: no UI adapter installed`,\n });\n return;\n }\n ports.uiAdapter.openUri(node.uri, {\n isMap: node.isMap,\n origin: actionContext.origin,\n });\n result.status = 'executed';\n return;\n }\n // The Print verb: /WP → the adapter (exactly once) → /DP, under\n // the print latch. Authority, adapter and reentrancy verdicts come\n // back as the node's status.\n const outcome = await firePrintThroughAdapter(undefined, diagnoseNode);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n // goto + named page verbs: navigation, executor-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const executor = ports.executors.get(node.type);\n if (!executor) {\n result.status = 'no-executor';\n diagnoseNode({ code: 'no-executor', message: `${node.type}: no executor registered` });\n return;\n }\n try {\n settle(result, await executor(node, actionContext));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n });\n };\n\n const walk = async (node: PdfActionNode, path: number[]): Promise<void> => {\n if (signal?.aborted) {\n cancelled = true;\n return;\n }\n await interpret(node, path);\n for (let index = 0; index < node.next.length && !cancelled; index++) {\n await walk(node.next[index], [...path, index]);\n }\n };\n await walk(tree.root, []);\n\n if (!documentFailed && !cancelled) {\n for (const entry of deferred) await entry.fire();\n }\n if (cancelled) return { status: 'cancelled', nodes, diagnostics };\n\n const anyExecuted = nodes.some((node) => node.status === 'executed');\n const anyFailedOrSkipped = nodes.some(\n (node) => node.status === 'failed' || node.status === 'skipped',\n );\n const status: ActionDispatchResult['status'] = anyExecuted\n ? anyFailedOrSkipped\n ? 'partial'\n : 'executed'\n : anyFailedOrSkipped\n ? 'partial'\n : 'inert';\n return { status, nodes, diagnostics };\n }\n\n return { run };\n}\nexport type ActionsRunner = ReturnType<typeof createRunner>;\n","/**\n * Trigger resolution helpers: the `triggers` setting, the per-page cache of annotations bearing page-lifecycle trees (the fan-out's\n * read amplifier) and ISO 32000-2 Table 197's page-step order.\n */\nimport type {\n AnnotationRef,\n DocumentEvent,\n PageObjectNumber,\n PageRef,\n PdfActionTree,\n PdfAnnotationActions,\n PdfPageActions,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionSource, ActionTrigger } from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { readPageAnnotations } from '../services/annotation-rows';\n\n/** An annotation that carries at least one page-lifecycle tree (/PO, /PC, /PV, /PI), as read. */\ninterface LifecycleAnnotation {\n readonly ref: AnnotationRef;\n readonly actions: PdfAnnotationActions;\n}\n\n/**\n * The pages whose annotations an event changes: those pages, every page\n * (`'all'`: a redaction, a skipped stretch of the stream, new document\n * bytes), or none.\n */\nconst annotationPagesOf = (event: DocumentEvent): readonly PageRef[] | 'all' | null => {\n switch (event.type) {\n case 'annotations.created':\n case 'annotations.updated':\n case 'annotations.deleted':\n case 'annotations.reordered':\n case 'annotations.flattened':\n case 'forms.widgetsReordered':\n return [event.page];\n // A form write can add, move or remove widgets, which carry page actions too.\n case 'forms.created':\n case 'forms.deleted':\n case 'forms.widgetAdded':\n case 'forms.widgetRemoved':\n case 'forms.widgetDeleted':\n case 'forms.widgetRestored':\n case 'forms.widgetUpdated':\n case 'forms.restored':\n case 'forms.repaired':\n return 'all';\n case 'pages.flattened':\n return event.pages;\n case 'redaction.applied':\n case 'stream.desynced':\n case 'document.versioned':\n return 'all';\n default:\n return null;\n }\n};\n\nexport function createTriggers(\n ctx: ActionsContext,\n { settings, form }: Pick<ActionsServices, 'settings' | 'form'>,\n) {\n const triggerEnabled = (trigger: ActionTrigger): boolean => {\n const { triggers } = settings.get();\n switch (trigger.scope) {\n case 'activate':\n return true; // the click door is never gated\n case 'annotation':\n return triggers.annotation;\n case 'page':\n return triggers.page;\n case 'document':\n return triggers.document;\n }\n };\n\n // Per page, the pending or settled read of its lifecycle-bearing\n // annotations. Reads start only inside the queued operation that needs\n // them, so a trigger sees every change made by the operations queued\n // before it. Holding the promise lets concurrent readers share one read,\n // and dropping it on invalidation means a read that was in flight when its\n // page changed is never reused afterwards.\n const lifecycleReads = new Map<PageObjectNumber, Promise<readonly LifecycleAnnotation[]>>();\n\n const lifecycleAnnotationsOf = (page: PageRef): Promise<readonly LifecycleAnnotation[]> => {\n const key = page.objectNumber;\n const cached = lifecycleReads.get(key);\n if (cached) return cached;\n const read = readPageAnnotations(ctx, form, page).then((annotations) =>\n annotations\n .filter(\n (annotation) =>\n annotation.actions &&\n (annotation.actions.pageOpen?.root ||\n annotation.actions.pageClose?.root ||\n annotation.actions.pageVisible?.root ||\n annotation.actions.pageInvisible?.root),\n )\n .map((annotation) => ({ ref: annotation.ref, actions: annotation.actions! })),\n );\n lifecycleReads.set(key, read);\n // A failed read is not kept: the next trigger for the page reads again.\n read.catch(() => {\n if (lifecycleReads.get(key) === read) lifecycleReads.delete(key);\n });\n return read;\n };\n\n /** Forget the pages a confirmed document event changed. */\n const invalidate = (event: DocumentEvent): void => {\n const pages = annotationPagesOf(event);\n if (pages === 'all') lifecycleReads.clear();\n else if (pages) for (const page of pages) lifecycleReads.delete(page.objectNumber);\n };\n\n /**\n * ISO 32000-2 Table 197 order: /PO \"shall be executed after the O action …\n * and the OpenAction entry\"; /PC \"shall be executed before the C action\".\n * Rootless trees are skipped (a budget-degraded tree with no root has\n * nothing to walk).\n */\n const planPageSteps = (\n event: 'open' | 'close' | 'visible' | 'invisible',\n page: PageRef,\n pageActions: PdfPageActions | undefined,\n lifecycle: readonly LifecycleAnnotation[],\n ): Array<{ source: ActionSource; tree: PdfActionTree }> => {\n const pageSource: ActionSource = { kind: 'page', page };\n const annotationSteps = (key: 'pageOpen' | 'pageClose' | 'pageVisible' | 'pageInvisible') =>\n lifecycle\n .filter((annotation) => annotation.actions[key]?.root)\n .map((annotation) => ({\n source: { kind: 'annotation', annotation: annotation.ref, page } as ActionSource,\n tree: annotation.actions[key]!,\n }));\n switch (event) {\n case 'open':\n return [\n ...(pageActions?.open?.root ? [{ source: pageSource, tree: pageActions.open }] : []),\n ...annotationSteps('pageOpen'),\n ];\n case 'close':\n return [\n ...annotationSteps('pageClose'),\n ...(pageActions?.close?.root ? [{ source: pageSource, tree: pageActions.close }] : []),\n ];\n case 'visible':\n return annotationSteps('pageVisible');\n case 'invisible':\n return annotationSteps('pageInvisible');\n }\n };\n\n return { triggerEnabled, lifecycleAnnotationsOf, invalidate, planPageSteps };\n}\nexport type ActionsTriggers = ReturnType<typeof createTriggers>;\n","/**\n * The verb-shaped document events (/WC, /WS, /DS, /WP, /DP) and the print\n * door: one catalog lifecycle tree per event, run inside the current queue\n * operation and never throwing (a broken script must not cancel the user's\n * save or print), and a print request sent to the kernel's print, or, without\n * a printer, to the adapter, wrapped /WP → print → /DP under the print latch.\n */\nimport { PluginError, type OperationOptions } from '@embedpdf/core';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionNodeStatus,\n ActionOrigin,\n ActionsCapability,\n ActionStepResult,\n ActionTriggerResult,\n DocumentTriggerEvent,\n} from '../contract';\nimport type { DispatchCore } from '../dispatch/core';\nimport { foldSteps } from '../dispatch/fold';\nimport type { ActionsServices } from '../services';\nimport type { ActionsOpenSequence } from './open-sequence';\n\nexport function createDocumentEvents(\n services: Pick<\n ActionsServices,\n | 'events'\n | 'catalog'\n | 'queue'\n | 'ports'\n | 'authority'\n | 'documentPrint'\n | 'printLatch'\n | 'settings'\n >,\n {\n ensureOpenSequenceBeforeDocEvent,\n }: Pick<ActionsOpenSequence, 'ensureOpenSequenceBeforeDocEvent'>,\n { runAndEmit }: DispatchCore,\n) {\n const { reportDiagnostic } = services.events;\n const { readDocumentActions, DOC_EVENT_TREES } = services.catalog;\n const { enqueue, budget } = services.queue;\n const ports = services.ports.slots;\n const { allowsPrint } = services.authority;\n const { documentPrint } = services;\n const printLatch = services.printLatch;\n\n /**\n * Run one catalog lifecycle tree inside the current queue operation, shared\n * by the dispatch path, `runDocumentVerb` and the print wrapper. Never\n * throws: a read or resolution failure degrades to a diagnostic, because a\n * broken script must not cancel the user's save or print.\n */\n const runDocEventTreeSafe = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionStepResult | null> => {\n if (!services.settings.get().triggers.document) return null;\n try {\n await ensureOpenSequenceBeforeDocEvent();\n const snapshot = await readDocumentActions();\n const tree = snapshot?.[DOC_EVENT_TREES[event]];\n if (!tree?.root && !tree?.incomplete) return null;\n const actionContext: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: event },\n };\n return { source: { kind: 'document' }, tree, result: await runAndEmit(tree, actionContext) };\n } catch (error) {\n diagnose({\n code: 'trigger-failed',\n message: `${event}: ${error instanceof Error ? error.message : String(error)}`,\n });\n return null;\n }\n };\n\n /** The dispatch-path body for a verb-shaped document event. */\n const runDocumentEventOp = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnostics: ActionDiagnostic[],\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionTriggerResult> => {\n const step = await runDocEventTreeSafe(event, diagnose);\n return foldSteps(step ? [step] : [], diagnostics);\n };\n\n /**\n * Both print paths (the Named Print verb, and script `doc.print()` effects\n * from the actions plane) go through here. While the latch is held\n * (including `runDocumentVerb('print')`'s body) a nested request is\n * suppressed with `reentrant-print`.\n *\n * With the kernel's print, a user's request starts `documents.print()` and\n * returns: the kernel runs /WP and /DP around the dialog through this\n * plugin's `aroundPrint` wrap, a `runDocumentVerb('print')` that waits for\n * the current queue operation, so it is never awaited here. A hover or\n * lifecycle request never opens the dialog.\n *\n * Without a printer: /WP → `ports.uiAdapter.print` exactly once → /DP,\n * with the latch reset in `finally`. An adapter throw skips /DP (the latch\n * still resets). /DP fires when the adapter call returns, since a browser\n * cannot observe dialog completion.\n */\n const firePrintThroughAdapter = async (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n if (printLatch.active) {\n diagnose({\n code: 'reentrant-print',\n message:\n 'print request during a document print event — suppressed (one dialog per request)',\n });\n return { status: 'blocked', detail: 'reentrant print suppressed' };\n }\n if (!allowsPrint()) {\n diagnose({ code: 'blocked', message: 'print: doc.print is not allowed' });\n return { status: 'blocked', detail: 'doc.print is not allowed' };\n }\n if (documentPrint.available()) {\n if (uiContext && uiContext.origin !== 'user') {\n diagnose({ code: 'blocked', message: `print: a ${uiContext.origin} request never prints` });\n return { status: 'blocked', detail: `${uiContext.origin} print request` };\n }\n documentPrint.start().catch((error: unknown) =>\n diagnose({\n code: 'trigger-failed',\n message: `print: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n return { status: 'executed' };\n }\n if (!ports.uiAdapter) {\n diagnose({ code: 'no-adapter', message: 'print: no UI adapter installed' });\n return { status: 'no-executor', detail: 'no UI adapter installed' };\n }\n printLatch.active = true;\n try {\n await runDocEventTreeSafe('will-print', diagnose);\n const adapter = ports.uiAdapter;\n if (!adapter) return { status: 'no-executor', detail: 'UI adapter uninstalled mid-print' };\n if (uiContext) adapter.print(uiContext);\n else adapter.print();\n await runDocEventTreeSafe('did-print', diagnose);\n return { status: 'executed' };\n } finally {\n printLatch.active = false;\n }\n };\n\n return {\n runDocumentEventOp,\n firePrintThroughAdapter,\n api: {\n runDocumentVerb: <T>(\n verb: 'save' | 'print',\n operation: () => Promise<T> | T,\n options?: OperationOptions,\n ): Promise<T> =>\n enqueue(async () => {\n budget.scriptNodes = 0; // one script budget for the whole verb operation\n const diagnose = (diagnostic: ActionDiagnostic): void =>\n reportDiagnostic(diagnostic, { source: { kind: 'document' } });\n const before = verb === 'save' ? ('will-save' as const) : ('will-print' as const);\n const after = verb === 'save' ? ('did-save' as const) : ('did-print' as const);\n const body = async (): Promise<T> => {\n // A before-event failure never cancels the user's verb;\n // runDocEventTreeSafe already degrades to diagnostics.\n await runDocEventTreeSafe(before, diagnose);\n // The caller can still cancel here; once the operation started,\n // it finishes, and so does its after-event.\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'actions', `${verb} was cancelled`, {\n cause: options.signal.reason,\n });\n }\n // `operation()` throwing skips the after-event and rethrows: no\n // /DS for a failed save.\n const value = await operation();\n await runDocEventTreeSafe(after, diagnose);\n return value;\n };\n if (verb !== 'print') return body();\n // The print verb holds the print latch for its whole body, so a /WP\n // or /DP script calling doc.print() is suppressed instead of\n // opening a second dialog.\n printLatch.active = true;\n try {\n return await body();\n } finally {\n printLatch.active = false;\n }\n }, options),\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsDocumentEvents = ReturnType<typeof createDocumentEvents>;\n","/**\n * The document-open sequence and its latch. The sequence runs the open\n * destination (as a lifecycle GoTo), then the catalog /OpenAction, and only\n * then releases the page-lifecycle barrier, so the first page /O fires after\n * both. It fires once: at the earliest of a UI adapter installing or the\n * first user-origin dispatch (`'auto'`), at bringup (`'headless'`), or never\n * (`'off'`, which still releases the barrier). Unless it is off, it runs\n * before the first verb-shaped document event (/WS, /WP, /WC, …).\n */\nimport type { Unsubscribe } from '@embedpdf/core';\nimport type { PdfActionTree } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionsCapability,\n ActionStepResult,\n ActionTriggerResult,\n} from '../contract';\nimport type { DispatchCore } from '../dispatch/core';\nimport { foldSteps } from '../dispatch/fold';\nimport type { ActionsServices } from '../services';\nimport type { ActionsPageLifecycle } from './page-lifecycle';\n\nexport function createOpenSequence(\n services: Pick<ActionsServices, 'events' | 'catalog' | 'queue' | 'ports' | 'settings'>,\n { releaseBarrier, resetCascade }: Pick<ActionsPageLifecycle, 'releaseBarrier' | 'resetCascade'>,\n { runAndEmit }: DispatchCore,\n) {\n const { reportDiagnostic, openSequenceCompleted } = services.events;\n /** The `openSequence` setting, read when it decides: it applies until the sequence has run. */\n const mode = () => services.settings.get().openSequence;\n const { readDocumentActions } = services.catalog;\n const { enqueue } = services.queue;\n const ports = services.ports.slots;\n let openFired = false;\n let sawUserActivity = false;\n\n /** The sequence body. Runs inside the queue (through dispatch or the\n * latch's own enqueue); callers guarantee `openFired` was set. */\n const runOpenSequenceOp = async (): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const steps: ActionStepResult[] = [];\n const openContext: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: 'open' },\n };\n try {\n const snapshot = await readDocumentActions();\n if (snapshot?.openDestination) {\n // The initial view reuses the whole spine (stage's goto executor,\n // policy included) as a synthesized lifecycle goto.\n const tree: PdfActionTree = {\n root: {\n type: 'goto',\n subtype: 'GoTo',\n destination: snapshot.openDestination,\n next: [],\n },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n };\n steps.push({\n source: { kind: 'document' },\n tree,\n result: await runAndEmit(tree, openContext),\n });\n }\n if (snapshot?.openAction?.root || snapshot?.openAction?.incomplete) {\n steps.push({\n source: { kind: 'document' },\n tree: snapshot.openAction,\n result: await runAndEmit(snapshot.openAction, openContext),\n });\n }\n } catch (error) {\n const diagnostic: ActionDiagnostic = {\n code: 'trigger-failed',\n message: `open sequence failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { source: { kind: 'document' } });\n } finally {\n // Release after the document steps, on every path; page-open emission\n // enqueues behind this operation (never awaited here: awaiting our own\n // queue would deadlock).\n releaseBarrier(true);\n }\n const result = foldSteps(steps, diagnostics);\n openSequenceCompleted.emit({ result });\n return result;\n };\n\n /**\n * The catalog /OpenAction never runs after a /WS, /WP or /WC script: before\n * the first verb-shaped document event, an armed but unfired open sequence\n * runs inline (the caller is already inside the queue; `runOpenSequenceOp`\n * never enqueues). It does not wait for the initial page /O: the guarantee\n * is catalog-level.\n */\n const ensureOpenSequenceBeforeDocEvent = async (): Promise<void> => {\n if (openFired || mode() === 'off') return;\n openFired = true;\n await runOpenSequenceOp();\n };\n\n const maybeFireOpenSequence = (): void => {\n if (openFired) return;\n if (mode() === 'off') {\n // The sequence never runs, but feeds must not buffer forever.\n openFired = true;\n releaseBarrier(false);\n return;\n }\n if (!ports.uiAdapter && mode() !== 'headless' && !sawUserActivity) return;\n openFired = true;\n void enqueue(() => runOpenSequenceOp());\n };\n\n const noteUserActivity = (): void => {\n resetCascade();\n if (!sawUserActivity) {\n sawUserActivity = true;\n maybeFireOpenSequence();\n }\n };\n\n /** Claim the one-shot open for a dispatched document-open trigger: false\n * when it already fired (the caller reports a replay). */\n const claim = (): boolean => {\n if (openFired) return false;\n openFired = true;\n return true;\n };\n\n return {\n run: runOpenSequenceOp,\n ensureOpenSequenceBeforeDocEvent,\n noteUserActivity,\n claim,\n /** Arm the latch at bringup: fires immediately for 'headless', releases\n * the barrier for 'off', waits for an adapter or user activity for 'auto'. */\n arm: maybeFireOpenSequence,\n api: {\n setUiAdapter: (adapter): Unsubscribe => {\n ports.uiAdapter = adapter;\n // An adapter arriving is the usual trigger of the open sequence.\n if (adapter) maybeFireOpenSequence();\n return () => {\n // Identity-safe: never wipe a successor installed after us.\n if (ports.uiAdapter === adapter) ports.uiAdapter = null;\n };\n },\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsOpenSequence = ReturnType<typeof createOpenSequence>;\n","/**\n * The lifecycle coordinator's page half: the document-open barrier and the\n * cascade budget. The stage owns page truth (it reports through\n * `reportPageState`); this owns when page-lifecycle triggers fire: nothing\n * emits before the document-open sequence has run (or was declared off or\n * headless), and emission is a diff against the last-emitted state, so\n * pre-open motion collapses to one open with no phantom close.\n */\nimport { toPageRef } from '@embedpdf/core';\nimport type { PageObjectNumber } from '@embedpdf/engine-core/runtime';\n\nimport type { DispatchCore } from '../dispatch/core';\nimport type { ActionsHostCapability, PageStateReport } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\n\n/** Consecutive programmatic rounds after which page-lifecycle emission is suppressed. */\nconst CASCADE_LIMIT = 8;\n\nexport function createPageLifecycle(\n ctx: ActionsContext,\n { events, settings }: Pick<ActionsServices, 'events' | 'settings'>,\n { dispatch }: DispatchCore,\n) {\n const { reportDiagnostic } = events;\n let barrierOpen = false;\n let bufferedReport: PageStateReport | null = null;\n let lastEmitted: {\n current: PageObjectNumber | null;\n visible: Set<PageObjectNumber>;\n } = {\n current: null,\n visible: new Set(),\n };\n let cascadeRounds = 0;\n\n const emitForReport = (report: PageStateReport): void => {\n if (report.cause === 'user') cascadeRounds = 0;\n const current = report.currentPage === null ? null : report.currentPage.objectNumber;\n const nextVisible = new Set(report.visiblePages.map((page) => page.objectNumber));\n const changedCurrent = current !== lastEmitted.current;\n const leaving = [...lastEmitted.visible].filter(\n (pageObjectNumber) => !nextVisible.has(pageObjectNumber),\n );\n const entering = [...nextVisible].filter(\n (pageObjectNumber) => !lastEmitted.visible.has(pageObjectNumber),\n );\n if (!changedCurrent && leaving.length === 0 && entering.length === 0) return;\n const previousCurrent = lastEmitted.current;\n // Track truth even when suppressed: the budget bounds emission, not state.\n lastEmitted = { current, visible: nextVisible };\n if (report.cause === 'programmatic') {\n cascadeRounds += 1;\n if (cascadeRounds > CASCADE_LIMIT) {\n reportDiagnostic({\n code: 'cascade-budget',\n message: `page-lifecycle emission suppressed: ${cascadeRounds} consecutive programmatic rounds (cap ${CASCADE_LIMIT})`,\n });\n return;\n }\n }\n // Canonical order (ISO leaves the cross-page order unspecified; within a\n // page, planPageSteps holds Table 197's /PO-after-/O and /PC-before-/C):\n // close(previous) → invisible set → visible set → open(current).\n if (changedCurrent && previousCurrent !== null) {\n void dispatch({ scope: 'page', event: 'close', page: toPageRef(previousCurrent) });\n }\n for (const pageObjectNumber of leaving) {\n void dispatch({ scope: 'page', event: 'invisible', page: toPageRef(pageObjectNumber) });\n }\n for (const pageObjectNumber of entering) {\n void dispatch({ scope: 'page', event: 'visible', page: toPageRef(pageObjectNumber) });\n }\n if (changedCurrent && current !== null) {\n void dispatch({ scope: 'page', event: 'open', page: toPageRef(current) });\n }\n };\n\n const reportPageState = (report: PageStateReport): void => {\n if (!report.placed) return;\n if (report.cause === 'user') cascadeRounds = 0;\n if (!barrierOpen) {\n bufferedReport = report; // coalesce: only the latest pre-open state matters\n return;\n }\n emitForReport(report);\n };\n\n const releaseBarrier = (fireFallback: boolean): void => {\n barrierOpen = true;\n const report = bufferedReport;\n bufferedReport = null;\n try {\n if (report) {\n emitForReport(report);\n } else if (fireFallback && settings.get().openSequence === 'headless') {\n // The initial page open falls back to the document's first page only\n // in declared-headless mode (no stage will ever report). In 'auto',\n // the stage report owns the initial open: firing a first-page /O\n // before a restored view reports would be exactly the phantom open\n // the coordinator exists to prevent; a stage-less 'auto' embedder\n // drives page triggers itself or declares headless.\n const first = ctx.document()?.pages[0]?.ref.objectNumber;\n if (first !== undefined) {\n lastEmitted = { current: first, visible: lastEmitted.visible };\n void dispatch({ scope: 'page', event: 'open', page: toPageRef(first) });\n }\n }\n } catch (error) {\n // The barrier is open either way: feeds must never stay buffered.\n reportDiagnostic({\n code: 'trigger-failed',\n message: `barrier release failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n };\n\n return {\n releaseBarrier,\n /** A user gesture resets the programmatic-cascade counter. */\n resetCascade: (): void => {\n cascadeRounds = 0;\n },\n api: { reportPageState } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsPageLifecycle = ReturnType<typeof createPageLifecycle>;\n","/**\n * Script world building (a page-scoped prefetch: the form as the user sees it\n * plus the annotations of the page the action runs on) and the event bridge between\n * two standards: the /AA keys are ISO 32000-2 Table 200; the event names\n * live in the JavaScript API layer (ISO 21757-1, Acrobat).\n */\nimport { scriptFieldsFromSnapshot } from '@embedpdf/core-acrojs';\nimport type {\n ScriptAnnotInput,\n ScriptColorArray,\n ScriptEventInput,\n ScriptWorldInput,\n} from '@embedpdf/core-acrojs';\nimport { pdfRectOf, rgbOf, toPageRef } from '@embedpdf/engine-core/runtime';\nimport type { FormSnapshot, PageObjectNumber } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionContext } from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\n\nexport function createScriptWorld(ctx: ActionsContext, { form }: Pick<ActionsServices, 'form'>) {\n // Acrobat's JavaScript keeps colors as color arrays, so they convert here, at its edge.\n const engineColorToArray = (color: string | null | undefined): ScriptColorArray => {\n if (!color) return ['T'];\n const { r, g, b } = rgbOf(color);\n return ['RGB', r / 255, g / 255, b / 255];\n };\n\n const scriptWorldFor = async (\n pageObjectNumber: PageObjectNumber,\n ): Promise<{ snapshot: FormSnapshot; world: Omit<ScriptWorldInput, 'event'> }> => {\n const page = toPageRef(pageObjectNumber);\n const snapshot = await form.read();\n const layout = ctx.getPage(page);\n const pageIndex = Math.max(0, layout?.index ?? -1);\n const { annotations } = await ctx.doc.page(page).annotations.list();\n const annots: ScriptAnnotInput[] = annotations\n // Script-addressable = everything except links and widgets (they are\n // Link and Field objects in Acrobat and separate planes here).\n .filter(\n (annotation) => annotation.subtype !== 'link' && !annotation.subtype.startsWith('widget'),\n )\n .map((annotation) => {\n // Acrobat's JavaScript keeps an annotation's rect in the file's\n // numbers, [x_ll, y_ll, x_ur, y_ur], so it converts here, at its edge.\n const inFile = layout ? pdfRectOf(annotation.rect, layout.pdfCropBox) : null;\n const styled = annotation as unknown as {\n color?: string;\n interiorColor?: string | null;\n opacity?: number;\n strokeWidth?: number;\n borderStyle?: string;\n dashArray?: number[];\n };\n return {\n ref: annotation.ref,\n name: annotation.nm ?? '',\n subtype: annotation.subtype,\n page: pageIndex,\n rect: (inFile\n ? [inFile.left, inFile.bottom, inFile.right, inFile.top]\n : [0, 0, 0, 0]) as [number, number, number, number],\n contents: annotation.contents ?? '',\n author: annotation.author ?? '',\n subject: annotation.subject ?? '',\n strokeColor: engineColorToArray(styled.color),\n fillColor: engineColorToArray(styled.interiorColor),\n opacity: styled.opacity ?? 1,\n width: styled.strokeWidth ?? 1,\n borderStyle: styled.borderStyle === 'dashed' ? ('D' as const) : ('S' as const),\n dash: styled.dashArray ?? [],\n hidden: annotation.hidden,\n print: annotation.print,\n readOnly: annotation.readOnly,\n locked: annotation.locked,\n noView: annotation.noView,\n toggleNoView: annotation.toggleNoView,\n opaqueBody: annotation.subtype === 'stamp',\n };\n });\n return {\n snapshot,\n world: {\n fields: scriptFieldsFromSnapshot(snapshot),\n annots,\n annotPages: [pageIndex],\n annotsCoverDocument: (ctx.document()?.pageCount ?? 0) <= 1,\n },\n };\n };\n\n const ANNOTATION_EVENT_NAMES: Record<string, string> = {\n cursorEnter: 'Mouse Enter',\n cursorExit: 'Mouse Exit',\n mouseDown: 'Mouse Down',\n mouseUp: 'Mouse Up',\n focus: 'Focus',\n blur: 'Blur',\n };\n const PAGE_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n close: 'Close',\n // /PV and /PI have no Acrobat event name: these two are an EmbedPDF extension.\n visible: 'Visible',\n invisible: 'Invisible',\n };\n // The /AA keys are ISO 32000-2 Table 200; the event names live in the\n // JavaScript API layer (ISO 21757-1, Acrobat).\n const DOC_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n 'will-save': 'WillSave',\n 'did-save': 'DidSave',\n 'will-print': 'WillPrint',\n 'did-print': 'DidPrint',\n 'will-close': 'WillClose',\n };\n\n const scriptEventFor = (\n actionContext: ActionContext,\n snapshot: FormSnapshot,\n ): ScriptEventInput => {\n const provenance = actionContext.event;\n const type =\n provenance.scope === 'page'\n ? 'Page'\n : provenance.scope === 'document'\n ? 'Doc'\n : actionContext.source.kind === 'widget'\n ? 'Field'\n : actionContext.source.kind === 'link'\n ? 'Link'\n : actionContext.source.kind === 'outline'\n ? 'Bookmark'\n : 'Annot'; // EmbedPDF extension — Acrobat has no plain-annot type\n const name =\n provenance.scope === 'activate'\n ? 'Mouse Up'\n : provenance.scope === 'annotation'\n ? (ANNOTATION_EVENT_NAMES[provenance.name] ?? 'Mouse Up')\n : provenance.scope === 'page'\n ? (PAGE_EVENT_NAMES[provenance.name] ?? 'Open')\n : (DOC_EVENT_NAMES[provenance.name] ?? 'Open');\n const targetRef =\n actionContext.source.kind === 'widget' ? actionContext.source.field : undefined;\n const targetField = targetRef\n ? snapshot.fields.find((field) =>\n targetRef.kind === 'objectNumber' && field.ref.kind === 'objectNumber'\n ? field.ref.objectNumber === targetRef.objectNumber\n : targetRef.kind === 'fqn' && field.name === targetRef.name,\n )\n : undefined;\n return {\n kind: 'widget-activate',\n type,\n name,\n ...(targetRef ? { target: targetRef, source: targetRef } : {}),\n ...(targetField && targetField.valueEntry.kind === 'scalar'\n ? { value: targetField.valueEntry.value }\n : {}),\n };\n };\n\n return { scriptWorldFor, scriptEventFor };\n}\n","/**\n * The `javascript` executor: one node is one host transaction with prefetch →\n * boot (once) → run → commit → surface inside the boundary. Print and submit\n * effects are external: replayed after the transaction releases, still inside\n * the queued dispatch operation.\n */\nimport type { ScriptOutput, ScriptUiEffect } from '@embedpdf/core-acrojs';\n\nimport type {\n ActionDiagnostic,\n ActionNodeStatus,\n ActionOrigin,\n ActionsScriptEnvironment,\n} from '../contract';\nimport type { AnnotCommitEntry } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { intentOfSubmitEffect } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\nimport type { ActionsRealm } from './realm';\nimport type { ActionsScriptSurface } from './surface';\nimport { createScriptWorld } from './world';\n\ntype FirePrint = (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n) => Promise<{ status: ActionNodeStatus; detail?: string }>;\n\n/** The default cap on JavaScript nodes one dispatch may run. */\nconst DEFAULT_SCRIPT_NODES_PER_DISPATCH = 16;\n\nexport function registerScriptExecutor(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'events' | 'ports' | 'queue' | 'form'>,\n environment: ActionsScriptEnvironment,\n { scriptHost }: Pick<ActionsRealm, 'scriptHost'>,\n { performSubmit }: ActionsSubmit,\n { surfaceScriptResult }: Pick<ActionsScriptSurface, 'surfaceScriptResult'>,\n documentEvents: { firePrintThroughAdapter: FirePrint },\n): void {\n const { reportDiagnostic } = services.events;\n const ports = services.ports.slots;\n const { budget } = services.queue;\n const { firePrintThroughAdapter } = documentEvents;\n const { scriptWorldFor, scriptEventFor } = createScriptWorld(ctx, services);\n\n /** Commit one run's document effects through the owner sinks in the\n * declared order (form first, then annotations); the first failure skips\n * the rest across both streams. Returns the failure summary, if any. */\n const commitScriptOutput = async (\n output: ScriptOutput,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<string | null> => {\n let failure: string | null = null;\n if (output.formEffects.length > 0) {\n if (!ports.formCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script form effects dropped: no form commit sink registered (${output.formEffects.length})`,\n });\n } else {\n const result = await ports.formCommitSink(output.formEffects);\n if (result.status === 'failed') failure = `form effects: ${result.error ?? 'failed'}`;\n }\n }\n if (output.annotEffects.length > 0) {\n if (failure) {\n diagnose({\n code: 'executor-failed',\n message: `script annot effects skipped after form failure (${output.annotEffects.length})`,\n });\n } else if (!ports.annotCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script annot effects dropped: no annotation commit sink registered (${output.annotEffects.length})`,\n });\n } else {\n const entries: AnnotCommitEntry[] = output.annotEffects.map((effect) => ({\n annotObjectNumber: effect.ref.kind === 'objectNumber' ? effect.ref.objectNumber : -1,\n ...(effect.ref.kind === 'objectNumber' ? { page: effect.ref.page } : {}),\n patch: effect.patch,\n }));\n const result = await ports.annotCommitSink(entries);\n const firstFailure = result.results.find((entry) => entry.status === 'failed');\n if (firstFailure)\n failure = `annotation ${firstFailure.annotObjectNumber}: ${firstFailure.error ?? 'failed'}`;\n }\n }\n if (failure) diagnose({ code: 'executor-failed', message: `script commit: ${failure}` });\n return failure;\n };\n\n if (!scriptHost) return;\n const nodeLimit = environment.maxScriptNodesPerDispatch ?? DEFAULT_SCRIPT_NODES_PER_DISPATCH;\n ports.executors.set('javascript', async (node, actionContext) => {\n if (node.type !== 'javascript') return { status: 'inert', reason: 'not a JS node' };\n if (budget.scriptNodes >= nodeLimit) {\n return {\n status: 'inert',\n reason: `dispatch script budget exhausted (${nodeLimit} JS nodes)`,\n };\n }\n budget.scriptNodes += 1;\n const source = actionContext.source;\n const firstPage = ctx.document()?.pages[0]?.ref.objectNumber;\n const pageObjectNumber =\n source.kind === 'widget' || source.kind === 'page'\n ? source.page.objectNumber\n : source.kind === 'link' || source.kind === 'annotation'\n ? (source.page?.objectNumber ?? firstPage)\n : firstPage;\n if (pageObjectNumber === undefined) {\n return { status: 'inert', reason: 'no page to anchor the world on' };\n }\n const diagnose = (diagnostic: ActionDiagnostic): void =>\n reportDiagnostic(diagnostic, { action: 'javascript', source });\n // Print and submit effects are external: the /WP and /DP wrap runs\n // action trees (which may need their own host transactions) and the\n // submit dataset must be resolved from post-commit truth, so both run\n // after the transaction releases, still inside this queued operation.\n const pendingExternal: Array<{\n effect: Extract<ScriptUiEffect, { kind: 'print' | 'submitForm' }>;\n phase: 'boot' | 'user';\n }> = [];\n const splitExternal = (output: ScriptOutput, phase: 'boot' | 'user'): ScriptUiEffect[] =>\n output.uiEffects.filter((effect) => {\n if (effect.kind === 'print' || effect.kind === 'submitForm') {\n pendingExternal.push({ effect, phase });\n return false;\n }\n return true;\n });\n const outcome = await scriptHost.transaction<\n { status: 'executed' } | { status: 'failed'; error: string }\n >(async (transaction) => {\n let built = await scriptWorldFor(pageObjectNumber);\n const boot = await transaction.boot({\n ...built.world,\n event: { kind: 'name-tree-boot', type: 'Doc', name: 'Open' },\n });\n if (boot) {\n // Boot effects belong to this first transaction; a boot fault only\n // degrades, never blocks. Refetch the world afterwards so the run\n // sees post-boot truth.\n await commitScriptOutput(boot, diagnose);\n surfaceScriptResult({\n uiEffects: splitExternal(boot, 'boot'),\n diagnostics: boot.diagnostics,\n ...(boot.error ? { error: boot.error } : {}),\n origin: actionContext.origin,\n phase: 'boot',\n realm: 'document',\n source,\n });\n if (boot.formEffects.length || boot.annotEffects.length) {\n built = await scriptWorldFor(pageObjectNumber);\n }\n }\n const output = await transaction.run(node.script, {\n ...built.world,\n event: scriptEventFor(actionContext, built.snapshot),\n });\n surfaceScriptResult({\n uiEffects: splitExternal(output, 'user'),\n diagnostics: output.diagnostics,\n ...(output.error ? { error: output.error } : {}),\n origin: actionContext.origin,\n phase: 'user',\n realm: 'document',\n source,\n });\n if (output.error) return { status: 'failed', error: output.error.message };\n const failure = await commitScriptOutput(output, diagnose);\n return failure ? { status: 'failed', error: failure } : { status: 'executed' };\n });\n for (const entry of pendingExternal) {\n if (entry.effect.kind === 'print') {\n await firePrintThroughAdapter(\n { origin: actionContext.origin, phase: entry.phase },\n diagnose,\n );\n } else {\n await performSubmit(intentOfSubmitEffect(entry.effect), actionContext, diagnose);\n }\n }\n return outcome;\n });\n}\n","import {\n createScriptHost,\n DEFAULT_SCRIPT_BUDGET,\n resolveScriptIdentity,\n seedFrom,\n type ScriptBudget,\n type ScriptHost,\n} from '@embedpdf/core-acrojs';\nimport type { DocumentHandle } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsScriptEnvironment, ActionsScriptIdentity } from '../contract';\nimport type { ScriptRealmTarget } from '../host-contract';\n\n/**\n * The scripting environment, the session-level half of the JavaScript\n * switch: sandbox factory, identity, clock, timezone, seed and budget. Policy\n * (`enabled`) decides whether one exists; realms are minted from it.\n *\n * One environment mints any number of realms: the owning document's own\n * host, and detached realms for documents that are not the viewer document\n * (a stamp asset, a template). Every realm gets a fresh sandbox from the\n * factory: the same policy and environment, isolated globals.\n *\n * Identity closes over the owning document: who the user is, is a session\n * fact resolved from the owner's claims plus the `javascript.identity`\n * setting as it is at each run, never from a detached document's\n * (authority-less) handle.\n */\nexport interface ScriptRealmFactory {\n realmFor(target: ScriptRealmTarget): ScriptHost;\n /** The embedder's budget (or the default): the per-run budget every minted\n * realm enforces, and the transaction aggregate consumers apply. */\n readonly budget: ScriptBudget;\n}\n\nexport function createScriptRealmFactory(\n environment: ActionsScriptEnvironment,\n identity: () => ActionsScriptIdentity | undefined,\n identityDoc: DocumentHandle,\n): ScriptRealmFactory {\n const sandboxFactory =\n environment.sandboxFactory ??\n (() =>\n import('@embedpdf/core-js-sandbox').then(({ createQuickJsSandbox }) =>\n createQuickJsSandbox(),\n ));\n const budget = environment.budget ?? DEFAULT_SCRIPT_BUDGET;\n return {\n budget,\n realmFor: (target) =>\n createScriptHost({\n sandboxFactory,\n document: () => {\n const documentInfo = target.document();\n return {\n id: target.doc.id,\n fileName: environment.fileName?.() ?? documentInfo?.name ?? 'document.pdf',\n pageCount: documentInfo?.pageCount ?? 0,\n pageNumber: 0,\n };\n },\n identity: () => resolveScriptIdentity(identityDoc, identity()),\n environment: (sequence) => {\n const nowMs = environment.now?.() ?? Date.now();\n return {\n nowMs,\n utcOffsetMinutes:\n environment.utcOffsetMinutes?.() ?? -new Date(nowMs).getTimezoneOffset(),\n randomSeed: environment.randomSeed?.() ?? seedFrom(target.doc.id, sequence),\n };\n },\n bootSources: target.bootSources,\n budget,\n }),\n };\n}\n","/**\n * The one ScriptHost per document. The `javascript.enabled` setting, as it is\n * when the document opens, decides whether a realm factory exists; the\n * factory carries the session environment and mints this document's own\n * realm here, and detached realms on demand (host lens): one environment, any\n * number of isolated realms.\n */\nimport { javaScriptProgramFromActionTree, type ScriptTransaction } from '@embedpdf/core-acrojs';\n\nimport type { ActionsScriptEnvironment } from '../contract';\nimport type { ActionsHostCapability } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { createScriptRealmFactory } from './environment';\n\nexport function createRealm(\n ctx: ActionsContext,\n { catalog, settings }: Pick<ActionsServices, 'catalog' | 'settings'>,\n environment: ActionsScriptEnvironment,\n) {\n const { readDocumentActions } = catalog;\n const realms = settings.get().javascript.enabled\n ? createScriptRealmFactory(\n environment,\n () => settings.get().javascript.identity ?? undefined,\n ctx.doc,\n )\n : null;\n const scriptHost = realms\n ? realms.realmFor({\n doc: ctx.doc,\n document: () => ctx.document(),\n bootSources: async () => {\n const snapshot = await readDocumentActions();\n return (snapshot?.nameTreeScripts ?? []).map(({ action }) =>\n javaScriptProgramFromActionTree(action),\n );\n },\n })\n : null;\n if (scriptHost) ctx.cleanup(() => scriptHost.dispose());\n\n return {\n scriptHost,\n api: {\n isScriptingEnabled: () => scriptHost !== null,\n ...(scriptHost && realms\n ? {\n scriptRealm: {\n transaction: <T>(body: (transaction: ScriptTransaction) => Promise<T>) =>\n scriptHost.transaction(body),\n budget: realms.budget,\n },\n createDetachedScriptRealm: (target) => {\n const host = realms.realmFor(target);\n return {\n transaction: <T>(body: (transaction: ScriptTransaction) => Promise<T>) =>\n host.transaction(body),\n budget: realms.budget,\n dispose: () => host.dispose(),\n };\n },\n }\n : {}),\n } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsRealm = ReturnType<typeof createRealm>;\n","/**\n * The surface door: the one UI and diagnostic port for script results. Print\n * and submitForm effects from the actions plane never reach it (the\n * JavaScript executor extracts them and routes them through\n * `firePrintThroughAdapter` and `performSubmit` after the transaction, since\n * the /WP and /DP wrap and the post-commit dataset must run outside the host\n * transaction). Such effects here come from the form pipeline's K/V/C/F path;\n * a print goes to the kernel's print when the host gave a printer.\n */\nimport type { ActionOrigin, ActionSource } from '../contract';\nimport type {\n ActionsHostCapability,\n ScriptCommitSurface,\n ScriptRealmKind,\n ScriptSurfaceResult,\n} from '../host-contract';\nimport type { ActionsServices } from '../services';\nimport { intentOfSubmitEffect } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\n\nexport function createScriptSurface(\n services: Pick<\n ActionsServices,\n 'events' | 'ports' | 'authority' | 'documentPrint' | 'printLatch'\n >,\n { performSubmit }: ActionsSubmit,\n) {\n const { reportDiagnostic, scriptDiagnosticReported, scriptFailed } = services.events;\n const ports = services.ports.slots;\n const { allowsPrint } = services.authority;\n const { documentPrint } = services;\n const printLatch = services.printLatch;\n\n const surfaceScriptResult = (result: ScriptSurfaceResult): void => {\n const uiContext = { origin: result.origin, phase: result.phase };\n const source = result.source ?? null;\n for (const effect of result.uiEffects) {\n // A detached realm has no document surface: the document it scripted\n // is not displayed, and this door's print, goto and submit act on this\n // document. Only alerts have a valid target (the user); everything\n // else is suppressed observably, never routed to the wrong document.\n if (result.realm === 'detached' && effect.kind !== 'alert') {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: `script ${effect.kind} request from a detached realm suppressed: no document surface`,\n });\n continue;\n }\n if (effect.kind === 'submitForm') {\n // A form-pipeline scripted submit: the same door, not awaited (the\n // form queue must not wait on submit sinks). Policy, sinks and\n // diagnostics all live inside performSubmit.\n void performSubmit(\n intentOfSubmitEffect(effect),\n {\n origin: result.origin,\n source: result.source ?? { kind: 'api' },\n event: { scope: 'activate' },\n },\n (diagnostic) => reportDiagnostic(diagnostic, { action: 'javascript', source }),\n );\n continue;\n }\n // Permission, not preference: a print request without doc.print\n // authority reaches no adapter; not overridable, and observable.\n if (effect.kind === 'print' && !allowsPrint()) {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request withheld: doc.print is not allowed',\n });\n continue;\n }\n // The print latch: a /WP or /DP script (or anything running while a\n // print wrapper is active) printing again is suppressed, so there is\n // one dialog per outer request.\n if (effect.kind === 'print' && printLatch.active) {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request during a document print event — suppressed (reentrant)',\n });\n continue;\n }\n // With the kernel's print, a user's print request prints the document, and the kernel\n // runs /WP and /DP around it. A hover or lifecycle request never prints.\n if (effect.kind === 'print' && documentPrint.available()) {\n if (result.origin !== 'user') {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: `script print request from a ${result.origin} event suppressed`,\n });\n continue;\n }\n documentPrint.start().catch((error: unknown) =>\n reportDiagnostic(\n {\n code: 'trigger-failed',\n message: `print: ${error instanceof Error ? error.message : String(error)}`,\n },\n { action: 'javascript', source },\n ),\n );\n continue;\n }\n if (!ports.uiAdapter) {\n reportDiagnostic(\n { code: 'no-adapter', message: `script ${effect.kind}: no UI adapter installed` },\n { action: 'javascript', source },\n );\n continue;\n }\n if (effect.kind === 'alert') {\n ports.uiAdapter.alert?.(effect.message, {\n ...uiContext,\n icon: effect.icon,\n ...(effect.title !== undefined ? { title: effect.title } : {}),\n });\n } else if (effect.kind === 'gotoPage') {\n ports.uiAdapter.gotoPage?.(effect.page, uiContext);\n } else {\n ports.uiAdapter.print(uiContext);\n }\n }\n for (const diagnostic of result.diagnostics) scriptDiagnosticReported.emit(diagnostic);\n if (result.error) scriptFailed.emit({ error: result.error, source });\n };\n\n /** A K/V/C/F commit surfaces as up to two results: the boot phase (only\n * when it produced effects) and the user phase (always — it carries the\n * diagnostics and the error). */\n const surfaceScriptCommit = (\n commit: ScriptCommitSurface,\n context: { origin: ActionOrigin; realm: ScriptRealmKind; source?: ActionSource },\n ): void => {\n const phases: Array<'boot' | 'user'> = ['boot', 'user'];\n for (const phase of phases) {\n const uiEffects = commit.uiEffects.filter((effect) => effect.phase === phase);\n if (uiEffects.length === 0 && phase === 'boot') continue;\n surfaceScriptResult({\n uiEffects,\n diagnostics: phase === 'user' ? commit.diagnostics : [],\n ...(phase === 'user' && commit.error ? { error: commit.error } : {}),\n origin: context.origin,\n phase,\n realm: context.realm,\n ...(context.source ? { source: context.source } : {}),\n });\n }\n };\n\n return {\n surfaceScriptResult,\n api: { surfaceScriptResult, surfaceScriptCommit } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsScriptSurface = ReturnType<typeof createScriptSurface>;\n","/** Session authority the action plane enforces itself (permission, not preference). */\nimport type { ActionsContext } from './context';\n\nexport function createAuthority(ctx: ActionsContext) {\n const allowsPrint = (): boolean => ctx.allows('doc.print');\n return { allowsPrint };\n}\n","/**\n * The one catalog-actions read. The catalog /AA is immutable in a session (no\n * writer exists in the stack), so the open sequence, the boot sources and the\n * five document events share one memoized read; a rejected read is evicted,\n * so a transient failure cannot poison every later lifecycle event.\n */\nimport type { DocumentActionsSnapshot } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\n\n/** The ISO 32000-2 Table 200 key for each verb-shaped document trigger event. */\nconst DOC_EVENT_TREES = {\n 'will-save': 'willSave',\n 'did-save': 'didSave',\n 'will-print': 'willPrint',\n 'did-print': 'didPrint',\n 'will-close': 'willClose',\n} as const;\n\nexport function createCatalog(ctx: ActionsContext) {\n let snapshotRead: Promise<DocumentActionsSnapshot | null> | null = null;\n const readDocumentActions = (): Promise<DocumentActionsSnapshot | null> => {\n if (!snapshotRead) {\n const service = ctx.doc.actions;\n const read: Promise<DocumentActionsSnapshot | null> = service\n ? Promise.resolve(service.get())\n : Promise.resolve(null);\n const memoized: Promise<DocumentActionsSnapshot | null> = read.catch((error: unknown) => {\n if (snapshotRead === memoized) snapshotRead = null;\n throw error;\n });\n snapshotRead = memoized;\n }\n return snapshotRead;\n };\n return { readDocumentActions, DOC_EVENT_TREES };\n}\nexport type ActionsCatalog = ReturnType<typeof createCatalog>;\n","/**\n * The kernel's print, where the document's own print requests go (the Named Print verb, a\n * script's `print()`) when the host gave the kernel a printer. The kernel prints the\n * document's pages, and runs the document's /WP and /DP around the dialog through the wrap\n * this plugin registers (`ctx.aroundPrint`). Without a printer, requests fall back to the UI\n * adapter's `print`.\n */\nimport { DocumentsToken } from '@embedpdf/core';\n\nimport type { ActionsContext } from './context';\n\nexport function createDocumentPrint(ctx: ActionsContext) {\n const documents = () => ctx.get(DocumentsToken);\n return {\n /** Whether the kernel prints this document: `doc.print`, and the host gave a printer. */\n available: (): boolean => documents().canPrint(),\n /** Print the document through the kernel. */\n start: (): Promise<void> => documents().print(),\n };\n}\n","/** The plugin's events, disposed with it, and the one way a diagnostic is reported. */\nimport type { PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionDiagnostic,\n ActionDiagnosticReportedEvent,\n ActionExecutedEvent,\n ActionSource,\n OpenSequenceCompletedEvent,\n ScriptDiagnosticReportedEvent,\n ScriptFailedEvent,\n} from '../contract';\nimport type { ActionsContext } from './context';\n\n/** Which action a diagnostic is about, and what started it, when one is concerned. */\nexport interface DiagnosticPlace {\n readonly action?: PdfActionType | null;\n readonly source?: ActionSource | null;\n}\n\nexport function createEvents(ctx: ActionsContext) {\n const executed = ctx.events.source<ActionExecutedEvent>();\n const diagnosticReported = ctx.events.source<ActionDiagnosticReportedEvent>();\n return {\n executed,\n diagnosticReported,\n scriptDiagnosticReported: ctx.events.source<ScriptDiagnosticReportedEvent>(),\n scriptFailed: ctx.events.source<ScriptFailedEvent>(),\n openSequenceCompleted: ctx.events.source<OpenSequenceCompletedEvent>(),\n /** Fire `onDiagnosticReported` with the action and source it concerns (`null` for none). */\n reportDiagnostic(diagnostic: ActionDiagnostic, place: DiagnosticPlace = {}): void {\n diagnosticReported.emit({\n code: diagnostic.code,\n action: place.action ?? null,\n source: place.source ?? null,\n });\n },\n };\n}\nexport type ActionsEvents = ReturnType<typeof createEvents>;\n","/**\n * The form, as scripts and dispatch read it: the form plugin's view, its fields with this\n * session's pending fills, when it registered one (`registerFormReader`); the engine's\n * otherwise.\n */\nimport type { FormSnapshot } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\nimport type { ActionPorts } from './ports';\n\nexport interface ActionsForm {\n /** The form now. `read` wraps an engine read, so the caller's signal can stop it. */\n read(read?: <T>(task: Promise<T>) => Promise<T>): Promise<FormSnapshot>;\n}\n\nexport function createForm(ctx: ActionsContext, ports: ActionPorts): ActionsForm {\n return {\n read: (read = (task) => task) => {\n const shown = ports.formReader?.();\n return shown ? Promise.resolve(shown) : read(ctx.doc.forms.list());\n },\n };\n}\n","/**\n * The registration slots: every port a sibling or the embedder installs. One\n * owner: the slots live here; areas read them at call time (never captured),\n * and every disposer is identity-safe (it clears a slot only while the\n * registrant is still current). Executors are last-wins. No capability read\n * exposes a slot, so installing one wakes no reader.\n */\nimport type { Unsubscribe } from '@embedpdf/core';\nimport type { PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionExecutor, ActionSubmitHandler, ActionUiAdapter } from '../contract';\nimport type {\n ActionsHostCapability,\n AnnotCommitSink,\n FormCommitSink,\n FormReader,\n SubmitResolver,\n} from '../host-contract';\nimport type { ActionsEvents } from './events';\n\nexport interface ActionPorts {\n readonly executors: Map<PdfActionType, ActionExecutor>;\n annotCommitSink: AnnotCommitSink | null;\n formCommitSink: FormCommitSink | null;\n /** The form plugin's form, as the user sees it. */\n formReader: FormReader | null;\n uiAdapter: ActionUiAdapter | null;\n /** Sink 1 of the submit chain (consent = installation). */\n submitHandler: ActionSubmitHandler | null;\n /** The form plugin's dataset resolver: the one door every submit resolves through. */\n submitResolver: SubmitResolver | null;\n}\n\nexport function createPorts({ reportDiagnostic }: Pick<ActionsEvents, 'reportDiagnostic'>) {\n const ports: ActionPorts = {\n executors: new Map(),\n annotCommitSink: null,\n formCommitSink: null,\n formReader: null,\n uiAdapter: null,\n submitHandler: null,\n submitResolver: null,\n };\n const api = {\n registerExecutor: (type, executor): Unsubscribe => {\n if (ports.executors.has(type)) {\n reportDiagnostic(\n { code: 'duplicate-executor', message: `executor for '${type}' replaced (last-wins)` },\n { action: type },\n );\n }\n ports.executors.set(type, executor);\n return () => {\n if (ports.executors.get(type) === executor) ports.executors.delete(type);\n };\n },\n registerAnnotCommitSink: (sink): Unsubscribe => {\n ports.annotCommitSink = sink;\n return () => {\n if (ports.annotCommitSink === sink) ports.annotCommitSink = null;\n };\n },\n registerFormCommitSink: (sink): Unsubscribe => {\n ports.formCommitSink = sink;\n return () => {\n if (ports.formCommitSink === sink) ports.formCommitSink = null;\n };\n },\n registerFormReader: (reader): Unsubscribe => {\n ports.formReader = reader;\n return () => {\n if (ports.formReader === reader) ports.formReader = null;\n };\n },\n setSubmitHandler: (handler): Unsubscribe => {\n ports.submitHandler = handler;\n // Not an open-sequence release: that stays the UI adapter's role.\n return () => {\n if (ports.submitHandler === handler) ports.submitHandler = null;\n };\n },\n registerSubmitResolver: (resolver): Unsubscribe => {\n ports.submitResolver = resolver;\n return () => {\n if (ports.submitResolver === resolver) ports.submitResolver = null;\n };\n },\n } satisfies Partial<ActionsHostCapability>;\n return { slots: ports, api };\n}\n","/**\n * The document-print latch: while a print wrapper is active\n * (`firePrintThroughAdapter`, `runDocumentVerb('print')`), a nested print\n * request is suppressed (`reentrant-print`), so the adapter opens exactly one\n * dialog per outer request. Read by the script surface, held by the\n * document-events area.\n */\nexport interface PrintLatch {\n active: boolean;\n}\n\nexport const createPrintLatch = (): PrintLatch => ({ active: false });\n","/**\n * The one serial queue every dispatch, verb and open sequence rides, plus the\n * per-operation script budget: the JavaScript nodes run in the current queue\n * operation, reset at every operation boundary and read by the executor, so a\n * /Next chain shares one deterministic cap.\n */\nimport type { ActionsContext } from './context';\n\nexport function createQueue(ctx: ActionsContext) {\n const enqueue = ctx.serialQueue('actions');\n const budget = { scriptNodes: 0 };\n return { enqueue, budget };\n}\nexport type ActionsQueue = ReturnType<typeof createQueue>;\n","/**\n * Plugin-private services every area is built on: the settings, the events,\n * the policy decision, the registration ports, the serial queue, the catalog\n * read, the form, session authority, the kernel's print and the print latch.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { ActionsSettings } from '../contract';\nimport { createAuthority } from './authority';\nimport { createCatalog, type ActionsCatalog } from './catalog';\nimport type { ActionsContext } from './context';\nimport { createDocumentPrint } from './document-print';\nimport { createEvents, type ActionsEvents } from './events';\nimport { createForm, type ActionsForm } from './form';\nimport { createPolicy, type ActionsPolicy } from './policy';\nimport { createPorts } from './ports';\nimport { createPrintLatch, type PrintLatch } from './print-latch';\nimport { createQueue, type ActionsQueue } from './queue';\n\nexport type { ActionsContext } from './context';\n\nexport interface ActionsServices {\n /** The plugin's settings: read `get()` where a setting is used, so a change applies at once. */\n readonly settings: Settings<ActionsSettings>;\n readonly events: ActionsEvents;\n readonly policy: ActionsPolicy;\n readonly ports: ReturnType<typeof createPorts>;\n readonly queue: ActionsQueue;\n readonly catalog: ActionsCatalog;\n /** The form scripts and dispatch read: the form plugin's view, else the engine's. */\n readonly form: ActionsForm;\n readonly authority: ReturnType<typeof createAuthority>;\n /** The kernel's print, when the host gave it a printer. */\n readonly documentPrint: ReturnType<typeof createDocumentPrint>;\n readonly printLatch: PrintLatch;\n}\n\nexport function createServices(ctx: ActionsContext): ActionsServices {\n const events = createEvents(ctx);\n const ports = createPorts(events);\n return {\n settings: ctx.settings(),\n events,\n policy: createPolicy(ctx),\n ports,\n queue: createQueue(ctx),\n catalog: createCatalog(ctx),\n form: createForm(ctx, ports.slots),\n authority: createAuthority(ctx),\n documentPrint: createDocumentPrint(ctx),\n printLatch: createPrintLatch(),\n };\n}\n","/**\n * The submit pipeline: one intent, one resolver, one sink chain. Both submit\n * sources (a SubmitForm node, a script `doc.submitForm()`) land in\n * `performSubmit` after policy. Never a network call from this plugin.\n */\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionNodeStatus,\n ActionsScriptEnvironment,\n ActionSubmitRequest,\n SubmitIntent,\n} from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { toFormSubmissionRequest } from './intent';\n\nexport function createSubmit(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'policy' | 'ports' | 'events'>,\n environment: ActionsScriptEnvironment,\n) {\n const policy = services.policy;\n const ports = services.ports.slots;\n const { reportDiagnostic } = services.events;\n const nowMs = (): number => environment.now?.() ?? Date.now();\n\n /**\n * The one submit door. Sink order: the embedder handler (explicit beats\n * ambient; its promise is not awaited) → the document's home\n * (`doc.forms.submit`, engine-asserted and awaited: a real operation with a\n * real receipt) → blocked with `no-submit-sink`.\n */\n const performSubmit = async (\n intent: SubmitIntent,\n actionContext: ActionContext,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const decision = policy.current()['submit-form'][actionContext.origin];\n if (decision !== 'adapter' && decision !== 'allow') {\n // `block` refuses quietly; `report` says so.\n if (decision === 'report') {\n diagnose({\n code: 'blocked',\n message: `submit-form: policy 'report' for origin '${actionContext.origin}'`,\n });\n }\n return { status: 'blocked' };\n }\n if (!ports.submitResolver) {\n diagnose({\n code: 'no-submit-resolver',\n message: 'submit-form: no dataset resolver registered (form plugin missing?)',\n });\n return { status: 'blocked', detail: 'no dataset resolver' };\n }\n let request: ActionSubmitRequest;\n try {\n request = await ports.submitResolver(intent, actionContext, diagnose);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit-form: dataset resolution: ${detail}` });\n return { status: 'failed', detail };\n }\n const forms = ctx.doc.forms;\n const homeSubmit =\n typeof forms.submit === 'function'\n ? () =>\n Promise.resolve(\n forms.submit!(toFormSubmissionRequest(request, new Date(nowMs()).toISOString())),\n )\n : null;\n if (ports.submitHandler) {\n try {\n const outcome = ports.submitHandler(request, { submitToDocumentHome: homeSubmit });\n if (outcome && typeof (outcome as Promise<void>).then === 'function') {\n // Not awaited, by contract: `executed` means \"handed to the\n // embedder\"; a later rejection is a diagnostic, never a rewrite of\n // the node result.\n void (outcome as Promise<void>).catch((error: unknown) => {\n reportDiagnostic(\n {\n code: 'executor-failed',\n message: `submit handler rejected (detached): ${\n error instanceof Error ? error.message : String(error)\n }`,\n },\n { action: 'submit-form', source: actionContext.source },\n );\n });\n }\n return { status: 'executed' };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit handler threw: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n if (homeSubmit) {\n try {\n await homeSubmit();\n return { status: 'executed' };\n } catch (error) {\n // The engine's refusal (authority, transport) surfaces on the node:\n // enforcement lives at the home's boundary, this only reports it.\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `document home refused submit: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n diagnose({\n code: 'no-submit-sink',\n message: 'submit-form: no handler installed and the document has no submit-capable home',\n });\n return { status: 'blocked', detail: 'no submit sink' };\n };\n\n return { performSubmit };\n}\nexport type ActionsSubmit = ReturnType<typeof createSubmit>;\n","/**\n * The actions controller: the composition root. It builds the plugin's\n * services once, wires each area with the services it declares, and\n * assembles the host capability from the areas' API slices. No behavior\n * lives here: every verb and read has a home in `submit/`, `scripting/`,\n * `dispatch/` or `lifecycle/`. The plugin keeps no session state: its rules\n * are its settings, and its live data (ports, queue, latches) are resources\n * of the areas.\n */\nimport { composeApi } from '@embedpdf/core';\n\nimport type { ActionsConfig } from './contract';\nimport type { DispatchCore } from './dispatch/core';\nimport { createDispatcher } from './dispatch/dispatcher';\nimport { createRunner } from './dispatch/run';\nimport { createTriggers } from './dispatch/triggers';\nimport type { ActionsHostCapability } from './host-contract';\nimport { createDocumentEvents } from './lifecycle/document-events';\nimport { createOpenSequence } from './lifecycle/open-sequence';\nimport { createPageLifecycle } from './lifecycle/page-lifecycle';\nimport { registerScriptExecutor } from './scripting/executor';\nimport { createRealm } from './scripting/realm';\nimport { createScriptSurface } from './scripting/surface';\nimport { createServices, type ActionsContext } from './services';\nimport { createSubmit } from './submit/perform';\n\n/**\n * `config` is what the app registered; the settings in it reach the\n * controller through `ctx.settings()`, and only the script environment is\n * read from it here.\n */\nexport function createActionsController(ctx: ActionsContext, config: ActionsConfig = {}) {\n const services = createServices(ctx);\n const { events, ports, settings } = services;\n\n // The lifecycle areas dispatch and run trees through the dispatcher that\n // is assembled last, bound late and explicitly (see `dispatch/core.ts`).\n const core: DispatchCore = {\n dispatch: (trigger) => dispatcher.dispatch(trigger),\n runAndEmit: (tree, actionContext) => dispatcher.runAndEmit(tree, actionContext),\n };\n\n const environment = config.javascript ?? {};\n const submit = createSubmit(ctx, services, environment);\n const realm = createRealm(ctx, services, environment);\n const surface = createScriptSurface(services, submit);\n const pageLifecycle = createPageLifecycle(ctx, services, core);\n const openSequence = createOpenSequence(services, pageLifecycle, core);\n const documentEvents = createDocumentEvents(services, openSequence, core);\n const triggers = createTriggers(ctx, services);\n const runner = createRunner(ctx, services, submit, documentEvents);\n const dispatcher = createDispatcher(\n ctx,\n services,\n runner,\n triggers,\n openSequence,\n documentEvents,\n );\n registerScriptExecutor(ctx, services, environment, realm, submit, surface, documentEvents);\n\n const api: ActionsHostCapability = composeApi('actions', [\n settings.api,\n ports.api,\n realm.api,\n surface.api,\n pageLifecycle.api,\n openSequence.api,\n documentEvents.api,\n dispatcher.api,\n {\n onExecuted: events.executed.on,\n onDiagnosticReported: events.diagnosticReported.on,\n onScriptDiagnosticReported: events.scriptDiagnosticReported.on,\n onScriptFailed: events.scriptFailed.on,\n onOpenSequenceCompleted: events.openSequenceCompleted.on,\n },\n ]);\n\n return {\n api,\n connect() {\n // Confirmed document events of every origin invalidate the per-page\n // lifecycle-annotation cache.\n ctx.listen(ctx.doc.events, (event) => triggers.invalidate(event));\n // Fires the open sequence at once for 'headless', releases the page\n // barrier for 'off', and waits for an adapter or user activity for 'auto'.\n openSequence.arm();\n // The document's save actions (/WS, /DS) run around every download of its file, so\n // what WillSave changes is in the bytes.\n ctx.aroundDownload((read) => documentEvents.api.runDocumentVerb('save', read));\n // Its print actions (/WP, /DP) run around every print, so what WillPrint changes is on\n // the paper: the kernel prepares a print again when the document changed.\n ctx.aroundPrint((print) => documentEvents.api.runDocumentVerb('print', print));\n },\n };\n}\n","/** The settings in what the app registered with `actionsPlugin(config)`. */\nimport type { DeepPartial } from '@embedpdf/core';\n\nimport type { ActionsConfig, ActionsSettings } from './contract';\n\n/** `config` without the script environment, which is no setting: what the settings register. */\nexport function registeredSettings(\n config: ActionsConfig | undefined,\n): DeepPartial<ActionsSettings> | undefined {\n if (!config) return undefined;\n const { javascript } = config;\n return {\n policy: config.policy,\n triggers: config.triggers,\n openSequence: config.openSequence,\n javascript: javascript && { enabled: javascript.enabled, identity: javascript.identity },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\n\nimport { ACTIONS_DEFAULTS, type ActionsConfig } from './contract';\nimport { createActionsController } from './controller';\nimport { ActionsToken } from './host-contract';\nimport { registeredSettings } from './settings';\n\n/**\n * The action engine, the dependency root of the action architecture. It\n * interprets extracted /A and /AA trees; it never detects triggers and never\n * imports another plugin's token: the stage, annotation, link and form\n * plugins optionally depend on it and register their executors and sinks\n * when they connect (the kernel's dependency order creates this plugin\n * first). JavaScript is one registered interpreter among many: Hide,\n * ResetForm, GoTo and Named work with scripting off. Document-scoped and\n * stateless; its settings are what the app registered over\n * {@link ACTIONS_DEFAULTS}.\n */\nexport const actionsPlugin = (config?: ActionsConfig) =>\n definePlugin({\n id: 'actions',\n token: ActionsToken,\n scope: 'document',\n settings: { defaults: ACTIONS_DEFAULTS, registered: registeredSettings(config) },\n create: (ctx) => createActionsController(ctx, config),\n });\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,eAAsB,oBACpB,KACA,MACA,MACA,QAA6C,SAAS,MAC/B;CACvB,MAAM,CAAC,aAAa,WAAW,MAAM,QAAQ,IAAI,CAC/C,IAAI,OAAO,mBAAmB,IAC1B,KAAK,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,SAAS,KAAK,WAAW,IAC3E,QAAQ,QAAQ,CAAC,CAAC,GACtB,IAAI,OAAO,gBAAgB,IACvB,KACG,KAAK,IAAI,CAAC,CACV,MAAM,aACL,SAAS,QAAQ,QAAQ,WAAW,OAAO,KAAK,iBAAiB,KAAK,YAAY,CACpF,IACF,QAAQ,QAAQ,CAAC,CAAC,CACxB,CAAC;CACD,OAAO,CAAC,GAAG,aAAa,GAAG,OAAO;AACpC;;;;;;AAOA,eAAsB,eACpB,KACA,MACA,KACA,QAA6C,SAAS,MAC1B;CAC5B,MAAM,OAAA,GAAA,8BAAA,cAAA,CAAoB,GAAG;CAC7B,MAAM,WAAW,eAAA,GAAA,8BAAA,cAAA,CAAwC,UAAU,GAAG,MAAM;CAC5E,IAAI,IAA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