# @embedpdf/engine-services — . ALL_STANDARD_SECURITY_PERMISSIONS [VariableDeclaration] (from packages/engine/services/src/shared/securityPermissions.ts): ALL_STANDARD_SECURITY_PERMISSIONS = 0xfffffffc AcquiredBaseDocument [InterfaceDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export interface AcquiredBaseDocument{ readonly key: string; readonly kind: 'memory' | 'file'; readonly path?: string; readonly basePtr: Ptr; release(): void; } ActionReadBudgetTracker [ClassDeclaration] (from packages/engine/services/src/features/actions/ActionModelReader.ts): export class ActionReadBudgetTracker{ private models = 0; private nodes = 0; private scriptCodeUnits = 0; private targetEntries = 0; private payloadCodeUnits = 0; constructor(private readonly limits: ActionReadBudget = DEFAULT_ACTION_READ_BUDGET){ } addModel(nodeCount: number): void{ this.models += 1; this.nodes += nodeCount; this.assertWithinBudget(); } addScript(script: string): void{ this.scriptCodeUnits += script.length; this.assertWithinBudget(); } reserveTargets(count: number): void{ this.targetEntries += count; this.assertWithinBudget(); } reservePayloadBytes(length: number): void{ this.payloadCodeUnits += length; this.assertWithinBudget(); } private assertWithinBudget(): void{ if ( this.models > this.limits.maxModels || this.nodes > this.limits.maxNodes || this.scriptCodeUnits > this.limits.maxScriptCodeUnits || this.targetEntries > this.limits.maxTargetEntries || this.payloadCodeUnits > this.limits.maxPayloadCodeUnits ){ throw new EngineError( EngineErrorCode.MalformedPdf, 'aggregate PDF action read budget exceeded', { details:{ models: this.models, nodes: this.nodes, scriptCodeUnits: this.scriptCodeUnits, targetEntries: this.targetEntries, payloadCodeUnits: this.payloadCodeUnits, limits: this.limits, } , } , ); } } } AnnotationAppearanceReader [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationAppearanceReader.ts): export class AnnotationAppearanceReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } async render( pageObjectNumber: PageObjectNumber, family: AnnotationFamily, options: AnnotationAppearanceRenderOptions, signal: AbortSignal, slices: Slices, ): Promise>{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const pool = this.session.pagePool(); const pagePtr = await pool.acquireInSlices(pageObjectNumber, signal, slices); const rotation = (options.rotation ?? 0) as PdfRotation; const modes = resolveModes(options.modes); const docPtr = this.session.requireDocPtr(); const pageRef = toPageRef(pageObjectNumber); const appearances: AnnotationAppearanceRaster[] = []; try{ const page = readPageBox(this.runtime, pagePtr); const scale = viewportScale( options.viewport, { width: page.right - page.left, height: page.top - page.bottom} , rotation, ); const count = fn.FPDFPage_GetAnnotCount(pagePtr); const timer = new SliceTimer(slices, signal); for (let i = 0; i < count; i++){ if (timer.due) await timer.pause(); throwIfAborted(signal); const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, i); if (!annotPtr) continue; try{ const subtypeCode = fn.FPDFAnnot_GetSubtype(annotPtr); if (familyOfCode(subtypeCode) !== family) continue; const available = fn.EPDFAnnot_GetAvailableAppearanceModes(annotPtr); const drawn = available & NORMAL.bit ? null : readDrawingRect(fn, mem, annotPtr); if (!available && !drawn) continue; const ref = annotationRefOf(fn, mem, docPtr, pageRef, annotPtr, i); const pageRect = normalizePdfRect(readAnnotRect(fn, mem, annotPtr)); const turn = readAnnotationTurn(fn, mem, annotPtr); const stripped = turn && pdfAppearanceTurnOf({ subtype: subtypeFromCode(subtypeCode), rect: pageRect, box: turn.box, rotation: turn.rotation, intent: subtypeCode === ANNOT_SUBTYPE_FREETEXT ? freeTextIntentFromName(readIntent(fn, mem, annotPtr)) : null, } ) !== null ? turn : undefined; const rect = stripped ? normalizePdfRect(stripped.box) : pageRect; for (const mode of modes){ const stored = !!(available & mode.bit); const box = stored ? rect : mode === NORMAL ? drawn : null; if (!box) continue; const states = stored ? statesOf(fn, mem, annotPtr, mode.modeInt) : SHOWN_ONLY; for (const state of states){ const raster = this.renderOne( pagePtr, annotPtr, mode.modeInt, state.draw, box, page, rotation, scale, stored ? stripped : undefined, options.maxOutputPixels, ); if (!raster) continue; appearances.push({ ref, mode: mode.name, state: state.label, rect: box, raster, } ); } } } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } } return{ page: pageRef, appearances} ; } finally{ pool.release(pageObjectNumber); } } private renderOne( pagePtr: Ptr, annotPtr: Ptr, modeInt: number, state: string, rect: PdfRect, page: PdfRect, rotation: PdfRotation, scale: number, turn: AnnotationTurn | undefined, maxOutputPixels?: number, ): PageRaster | null{ const{ fn} = this.runtime; const rectArea = Math.max(1, (rect.right - rect.left) * (rect.top - rect.bottom)); const effScale = Math.min(scale, Math.sqrt(APPEARANCE_PIXEL_CLAMP / rectArea)); return rasterize(this.runtime, { rect, page, rotation, viewport:{ kind: 'scale', scale: effScale} , ...(maxOutputPixels !== undefined ?{ maxOutputPixels} :{ } ), background: 'transparent', draw: (bitmapPtr, matrixPtr) => turn ? withScratch(this.runtime.mem, RECTF_BYTES, (boxPtr) =>{ writeRectF(this.runtime.mem, boxPtr, turn.box); return fn.EPDF_RenderAnnotBitmapUnrotated( bitmapPtr, pagePtr, annotPtr, modeInt, state, pdfFromClockwise(turn.rotation), boxPtr, matrixPtr, FPDF_REVERSE_BYTE_ORDER, ); } ) : fn.EPDF_RenderAnnotBitmap( bitmapPtr, pagePtr, annotPtr, modeInt, state, matrixPtr, FPDF_REVERSE_BYTE_ORDER, ), } ); } } AnnotationBatchApplier [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationBatchApplier.ts): export class AnnotationBatchApplier{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } create(creates: readonly BatchCreate[], signal: AbortSignal): BatchCreateResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const claimed = new Set(); const prepared = creates.map((create) =>{ const record = this.session.resolvePageRef(create.page); const ctx = this.writeContext(create.resources); const given = labelled(create.label, () => prepareCreate(create.draft, create.resources, ctx), ); labelled(create.label, () => this.claimName(given.nm, record, claimed)); const draft = given.nm !== undefined || create.attribution.kind !== 'stamp' ? given :{ ...given, nm: generateUuidV7()} ; if (create.objectNumber !== undefined){ labelled(create.label, () => this.session.claimObjectNumber(create.objectNumber!)); } const replyTo = create.replyTo &&{ type: create.replyTo.type, to: labelled(create.label, () => this.linkTarget(create.replyTo!.to, create.page, creates.length, 'reply'), ), } ; if (draft.subtype === 'popup' && !create.parent){ throw new EngineError( EngineErrorCode.InvalidArg, `${ create.label ?? 'create'} : a popup needs the annotation it shows (parent)`, { details:{ field: 'parent'} } , ); } const parent = create.parent && labelled(create.label, () => this.linkTarget(create.parent!, create.page, creates.length, 'popup'), ); return{ create, record, ctx, draft, replyTo, parent} ; } ); throwIfAborted(signal); if (prepared.length === 0) return{ created: [], meta: metaOf(this.session.writeStamp(), [], [])} ; const placed = prepared.map(({ create, record, ctx, draft} ): Placed =>{ throwIfAborted(signal); const annotPtr = fn.EPDFPage_CreateAnnotRaw( docPtr, record.pageIndex, PDF_SUBTYPE_TO_CODE[draft.subtype], create.objectNumber ?? 0, ); if (!annotPtr && create.objectNumber !== undefined){ throw objectNumberUnavailable(create.objectNumber, 'taken'); } if (!annotPtr){ throw new EngineError( EngineErrorCode.Unknown, `${ create.label ?? 'create'} : EPDFPage_CreateAnnotRaw returned NULL`, ); } let objectNumber: number; try{ labelled(create.label, () => applyDraft(fn, mem, annotPtr, draft, ctx)); generateAppearance(fn, annotPtr, draft.blendMode); objectNumber = fn.EPDFAnnot_GetObjectNumber(annotPtr); if (objectNumber <= 0){ throw new EngineError( EngineErrorCode.Unknown, `${ create.label ?? 'create'} : EPDFPage_CreateAnnotRaw made a direct object`, ); } } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } return{ pageIndex: record.pageIndex, pageObjectNumber: record.pageObjectNumber, index: fn.EPDFPage_GetAnnotCountRaw(docPtr, record.pageIndex) - 1, objectNumber, } ; } ); const linked: AnnotationRef[] = []; const openTarget = (target: number | Existing, body: (parentPtr: Ptr) => T): T => typeof target === 'number' ? this.withOpen(placed[target]!, body) : this.withOpenExisting(target, body); prepared.forEach(({ replyTo, parent} , at) =>{ if (replyTo){ this.withOpen(placed[at]!, (annotPtr) => openTarget(replyTo.to, (parentPtr) => linkReply(this.runtime, annotPtr, parentPtr, replyTo.type), ), ); } if (parent !== undefined){ this.withOpen(placed[at]!, (popupPtr) => openTarget(parent, (parentPtr) =>{ linkPopup(this.runtime, popupPtr, parentPtr); if (typeof parent === 'number') return; linked.push(annotationRefOf(fn, mem, docPtr, parent.page, parentPtr, parent.index)); } ), ); } } ); const now = new Date(); prepared.forEach(({ create:{ attribution, fileDates, label} } , at) =>{ this.withOpen(placed[at]!, (annotPtr) => labelled(label, () =>{ if (attribution.kind === 'stamp'){ stampCreation(fn, mem, annotPtr, attribution.actor, now); } else{ restoreAttribution(fn, mem, annotPtr, attribution.from, attribution.importedBy); } if (fileDates) restoreFileDates(fn, mem, annotPtr, fileDates); } ), ); } ); const readContext = readContextFor(this.session, this.fonts); const created = placed.map((at) => this.withOpen(at, (annotPtr) => readAnnotationFromPtr(fn, mem, annotPtr, at.pageObjectNumber, at.index, readContext), ), ); joinWidgetFieldNumbers(this.runtime, this.session, created); return{ created, meta: metaOf(this.session.writeStamp(), placed, linked)} ; } private claimName( nm: string | null | undefined, record:{ pageIndex: number; pageObjectNumber: PageObjectNumber} , claimed: Set, ): void{ if (!nm) return; const claim = `${ record.pageIndex} \u0000${ nm} `; const docPtr = this.session.requireDocPtr(); if ( claimed.has(claim) || annotationIndexByName(this.runtime, docPtr, record.pageIndex, nm) >= 0 ){ throw nameTakenError(nm, record.pageObjectNumber); } claimed.add(claim); } private linkTarget( target: BatchLinkTarget, page: PageRef, count: number, link: 'reply' | 'popup', ): number | Existing{ if ('planned' in target){ if (target.planned < 0 || target.planned >= count){ throw new EngineError(EngineErrorCode.InvalidArg, `no create ${ target.planned} to link to`); } return target.planned; } const{ existing} = target; if (existing.page.objectNumber !== page.objectNumber){ throw new EngineError( EngineErrorCode.InvalidArg, link === 'reply' ? `/IRT parent must be on the same page as the reply (parent page ${ existing.page.objectNumber} , reply page ${ page.objectNumber} )` : `a popup's parent must be on the same page (parent page ${ existing.page.objectNumber} , popup page ${ page.objectNumber} )`, ); } return{ page: existing.page, ...resolveAnnotIndexRaw(this.runtime, this.session, existing)} ; } private writeContext(resources?: WireAnnotationResources): AnnotationWriteContext{ return{ ...fontWriteContext(this.runtime, this.session, this.fonts), docPtr: this.session.requireDocPtr(), drawings: this.session.drawingIndex(), pdfPageCount: (bytes) => pdfPageCountOf(this.runtime.fn, this.runtime.mem, bytes), ...(resources ?{ resources} :{ } ), } ; } private withOpen(at: Placed, body: (annotPtr: Ptr) => T): T{ const{ fn} = this.runtime; const annotPtr = fn.EPDFPage_GetAnnotRaw(this.session.requireDocPtr(), at.pageIndex, at.index); if (!annotPtr){ throw new EngineError(EngineErrorCode.Unknown, 'a created annotation is not where it was'); } try{ if (fn.EPDFAnnot_GetObjectNumber(annotPtr) !== at.objectNumber){ throw new EngineError(EngineErrorCode.Unknown, 'a created annotation is not where it was'); } return body(annotPtr); } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } } private withOpenExisting(at: Existing, body: (annotPtr: Ptr) => T): T{ const{ fn} = this.runtime; const annotPtr = fn.EPDFPage_GetAnnotRaw(this.session.requireDocPtr(), at.pageIndex, at.index); if (!annotPtr){ throw new EngineError( EngineErrorCode.Unknown, 'an annotation to link to is not where it was', ); } try{ return body(annotPtr); } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } } } AnnotationExporter [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationExporter.ts): export class AnnotationExporter{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } export( selection: AnnotationExportSelection, limits: BundleLimits, signal: AbortSignal, ): WireAnnotationBundle{ throwIfAborted(signal); const records = this.session.allRecords(); const reader = new RawAnnotationReader(this.runtime, this.session, this.fonts); const annotations = closeExportSelection( selection, records.map((record) => toPageRef(record.pageObjectNumber)), (page) => reader.listOne(page.objectNumber, signal, 'annotations').annotations, ); assertWithinLimit('annotation', limits, 'items', annotations.length); const resources = new ResourceCollector(this.runtime, this.session, limits); const boxOf = visibleBoxReader(this.runtime, this.session); const items: AnnotationBundleItem[] = annotations.map((data) =>{ throwIfAborted(signal); return{ data: pageAnnotationOf(data, boxOf(data.ref.page), boxOf), resources: resources.of(data), } ; } ); const pages = bundlePagesOf( this.runtime, this.session, items.map((item) => item.data), ); assertWithinLimit('annotation', limits, 'pages', pages.length); const manifestBytes = manifestBytesOf({ pages, items} ); assertWithinLimit('annotation', limits, 'manifestBytes', manifestBytes); assertWithinLimit('annotation', limits, 'bundleBytes', manifestBytes + resources.totalBytes); return{ format: 'embedpdf/annotations', version: 1, pages, items, resources: resources.byId} ; } } AnnotationFlattener [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationFlattener.ts): export class AnnotationFlattener{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } flatten( pageObjectNumber: PageObjectNumber, refs: AnnotationRef[], usage: PageFlattenUsage, signal: AbortSignal, ): AnnotationFlattenResult{ throwIfAborted(signal); this.requireRefs('annotations.flatten', pageObjectNumber, refs); const{ fn, mem} = this.runtime; const promoted = promoteInlineAnnotations(this.runtime, this.session, pageObjectNumber); const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); try{ const annotPtrs = this.resolveAll(pagePtr, refs); let code: number; let statuses: number[]; try{ [code, statuses] = this.withHandleArray(annotPtrs, (arrayPtr) => withScratch(mem, 4 * refs.length, (statusPtr) =>{ const rc = fn.EPDFPage_FlattenAnnotations( pagePtr, arrayPtr, refs.length, usage === 'print' ? 1 : 0, statusPtr, ); const out: number[] = []; for (let i = 0; i < refs.length; i++){ out.push(Number(mem.peek(statusPtr, 'i32', 4 * i))); } return [rc, out] as const; } ), ); } finally{ for (const annotPtr of annotPtrs) fn.FPDFPage_CloseAnnot(annotPtr); } if (code === FLATTEN_FAIL){ const foreign = statuses.findIndex((status) => status === STATUS_NOT_ON_PAGE); throw new EngineError( foreign >= 0 ? EngineErrorCode.InvalidArg : EngineErrorCode.Unknown, foreign >= 0 ? `annotations.flatten: ref ${ foreign} is not an annotation of page ${ pageObjectNumber} ` : 'native annotation flatten failed after preflight', ); } const results = refs.map((ref, i) => ({ ref, status: statuses[i] === STATUS_APPLIED ? ('applied' as const) : ('unchanged' as const), } )); if (code !== FLATTEN_SUCCESS && !promoted){ const meta: MutationMeta ={ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} ; return{ page: toPageRef(pageObjectNumber), usage, results, meta} ; } this.session.invalidateDerived(); const meta: MutationMeta ={ affectedPages: [toPageRef(pageObjectNumber)], cacheDelta: null, ...this.session.writeStamp(), } ; return{ page: toPageRef(pageObjectNumber), usage, results, meta} ; } finally{ pool.release(pageObjectNumber); } } exportAppearance( pageObjectNumber: PageObjectNumber, refs: AnnotationRef[], signal: AbortSignal, ):{ bytes: ArrayBuffer; size: number} { throwIfAborted(signal); this.requireRefs('annotations.exportAppearance', pageObjectNumber, refs); const{ fn} = this.runtime; const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); let exportedPtr: Ptr | null = null; try{ const annotPtrs = this.resolveAll(pagePtr, refs); try{ exportedPtr = this.withHandleArray(annotPtrs, (arrayPtr) => fn.EPDFPage_ExportAnnotationsAsDocument(pagePtr, arrayPtr, refs.length), ); } finally{ for (const annotPtr of annotPtrs) fn.FPDFPage_CloseAnnot(annotPtr); } if (!exportedPtr){ throw new EngineError( EngineErrorCode.InvalidArg, 'annotations.exportAppearance: every ref must be a visible annotation of this page with a normal appearance', ); } return saveDocumentToBuffer( this.runtime.fn, this.runtime.mem, exportedPtr, 'exported appearances', ); } finally{ if (exportedPtr) fn.FPDF_CloseDocument(exportedPtr); pool.release(pageObjectNumber); } } readAppearance( pageObjectNumber: PageObjectNumber, ref: AnnotationRef, signal: AbortSignal, ):{ bytes: ArrayBuffer; size: number} { throwIfAborted(signal); const{ fn} = this.runtime; const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); let exportedPtr: Ptr | null = null; try{ const annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref); try{ const subtype = subtypeFromCode(fn.FPDFAnnot_GetSubtype(annotPtr)); if (ANNOTATION_RESOURCE_ROLES[subtype]?.appearance === undefined){ throw new EngineError( EngineErrorCode.InvalidArg, `a ${ subtype} annotation has no 'appearance' resource`, ); } exportedPtr = exportUnturnedAppearance(fn, this.runtime.mem, annotPtr); } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } if (!exportedPtr){ throw new EngineError( EngineErrorCode.InvalidArg, 'the annotation has no normal appearance to read', ); } return saveDocumentToBuffer(this.runtime.fn, this.runtime.mem, exportedPtr, 'the appearance'); } finally{ if (exportedPtr) fn.FPDF_CloseDocument(exportedPtr); pool.release(pageObjectNumber); } } private resolveAll(pagePtr: Ptr, refs: AnnotationRef[]): Ptr[]{ const{ fn} = this.runtime; const annotPtrs: Ptr[] = []; try{ for (const ref of refs){ annotPtrs.push(resolveAnnotPtr(this.runtime, this.session, pagePtr, ref)); } return annotPtrs; } catch (error){ for (const annotPtr of annotPtrs) fn.FPDFPage_CloseAnnot(annotPtr); throw error; } } private withHandleArray(annotPtrs: Ptr[], body: (arrayPtr: Ptr) => T): T{ const{ mem} = this.runtime; const isWasm = this.runtime.kind === 'wasm'; const ptrSize = isWasm ? 4 : 8; return withScratch(mem, Math.max(1, annotPtrs.length * ptrSize), (arrayPtr) =>{ annotPtrs.forEach((ptr, i) => isWasm ? mem.poke(arrayPtr, 'i32', Number(ptr), i * 4) : mem.poke(arrayPtr, 'i64', ptr, i * 8), ); return body(arrayPtr); } ); } private requireRefs(op: string, pageObjectNumber: PageObjectNumber, refs: AnnotationRef[]): void{ if (refs.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, `${ op} requires at least one ref`); } for (const ref of refs){ if (ref.page.objectNumber !== pageObjectNumber){ throw new EngineError( EngineErrorCode.InvalidArg, `${ op} refs must all target page ${ pageObjectNumber} ; got ref on page ${ ref.page.objectNumber} `, ); } } } } AnnotationImporter [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationImporter.ts): export class AnnotationImporter{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } import( request: AnnotationImportRequest, signal: AbortSignal, ): AnnotationImportResult{ throwIfAborted(signal); const{ bundle, limits} = request; this.assertBundle(bundle, limits); const plan = planAnnotationImport({ bundle: request.attribution === 'stamp' ? withoutNames(bundle) : bundle, ...(request.pages !== undefined ?{ pages: request.pages} :{ } ), target: this.session.allRecords().map((record) => ({ page: toPageRef(record.pageObjectNumber), position: record.pageIndex, } )), nameTaken: (page, nm) => annotationIndexByName( this.runtime, this.session.requireDocPtr(), this.session.resolvePageRef(page).pageIndex, nm, ) >= 0, } ); const boxOf = visibleBoxReader(this.runtime, this.session); const creates = plan.creates.map((planned): BatchCreate =>{ const item = bundle.items[planned.item]!; const resources: WireAnnotationResources ={ } ; for (const [role, id] of Object.entries(item.resources)){ resources[role as keyof WireAnnotationResources] = bundle.resources[id]!; } return{ page: planned.page, draft: pdfAnnotationDraftOf(planned.draft, boxOf(planned.page), boxOf), ...(planned.replyTo ?{ replyTo:{ to:{ planned: planned.replyTo.planned} , type: planned.replyTo.type} } :{ } ), ...(planned.parent !== undefined ?{ parent:{ planned: planned.parent} } :{ } ), resources, attribution: attributionOf(request, planned.draft, item.data), ...(item.data.subtype === 'file-attachment' && item.data.file ?{ fileDates:{ createdAt: item.data.file.createdAt, modifiedAt: item.data.file.modifiedAt, } , } :{ } ), label: `import: item ${ planned.item} `, } ; } ); for (const create of creates) request.authorizeCreate?.(create.draft); const{ created, meta} = new AnnotationBatchApplier( this.runtime, this.session, this.fonts, ).create(creates, signal); return{ annotations: created, refMap: plan.creates.map((planned, at) => ({ from: bundle.items[planned.item]!.data.ref, to: created[at]!.ref, } )), dropped: [...plan.dropped], meta, } ; } private assertBundle(bundle: WireAnnotationBundle, limits: BundleLimits): void{ const hashes = checkWireBundle( this.runtime, 'annotation', bundle, limits, assertAnnotationBundleManifest, ); const drawings = this.session.drawingIndex(); for (const [bytes, hex] of hashes) drawings.hashes.set(bytes, hex); for (const item of bundle.items){ const id = item.resources.appearance; if (id) assertImageWithinLimit('annotation', limits, bundle.resources[id]!); } } } AnnotationMutator [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationMutator.ts): export class AnnotationMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } private writeContext(resources?: WireAnnotationResources): AnnotationWriteContext{ return{ ...fontWriteContext(this.runtime, this.session, this.fonts), runtime: this.runtime, docPtr: this.session.requireDocPtr(), drawings: this.session.drawingIndex(), pdfPageCount: (bytes) => pdfPageCountOf(this.runtime.fn, this.runtime.mem, bytes), ...(resources ?{ resources} :{ } ), } ; } create( pageObjectNumber: PageObjectNumber, draft: AnnotationDraft, signal: AbortSignal, options:{ readonly actor?: AnnotationActor; readonly resources?: WireAnnotationResources; readonly objectNumber?: number; } ={ } , ): AnnotationCreateResult{ const{ actor, resources, objectNumber} = options; const{ reply, ...data} = draft as AnnotationDraft &{ parent?: AnnotationRef | null; } ; const parent = draft.subtype === 'popup' ? draft.parent : null; if (draft.subtype === 'popup') delete (data as{ parent?: unknown} ).parent; const{ created, meta} = new AnnotationBatchApplier( this.runtime, this.session, this.fonts, ).create( [{ page: toPageRef(pageObjectNumber), draft: data as AnnotationDraft, ...(reply ?{ replyTo:{ to:{ existing: reply.to} , type: reply.type ?? 'reply'} } :{ } ), ...(parent ?{ parent:{ existing: parent} } :{ } ), ...(resources ?{ resources} :{ } ), ...(objectNumber !== undefined ?{ objectNumber} :{ } ), attribution:{ kind: 'stamp', ...(actor ?{ actor} :{ } )} , } , ], signal, ); return{ annotation: created[0]!, meta} ; } update( ref: AnnotationRef, patch: AnnotationPatch, authority: AnnotationAuthority, signal: AbortSignal, resources?: WireAnnotationResources, ): AnnotationUpdateResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const{ pageIndex, index} = resolveAnnotIndexRaw(this.runtime, this.session, ref); let annotPtr: Ptr | null = openAnnotAtRaw(this.runtime, this.session, pageIndex, index); try{ throwIfAborted(signal); const writeContext = this.writeContext(resources); const previousBlendMode = blendModeFromCode(fn.EPDFAnnot_GetBlendMode(annotPtr)); const currentDto = readAnnotationFromPtr( fn, mem, annotPtr, ref.page.objectNumber, index, readContextFor(this.session, this.fonts), ); joinWidgetFieldNumbers(this.runtime, this.session, [currentDto]); const actor = authorizeAnnotationUpdate( authority, currentDto, (patch as{ groupId?: string | null} ).groupId, ); assertCaptionMetadataWritable(fn, annotPtr, currentDto, patch); patch = pdfResolveAnnotationPatch(currentDto, patch, { describeFont: writeContext.describeFont, } ); assertMarkKeepsItsLook(currentDto, patch); assertAnnotationResources(currentDto.subtype, resources, 'update'); preflightPatch(patch, writeContext); throwIfAborted(signal); const impact = resources?.appearance ? 'regenerate' : appearanceImpactOf(currentDto, patch); if (impact !== 'inert') settleAnnotationTurn(fn, mem, annotPtr); if (patch.subtype !== undefined && patch.subtype !== currentDto.subtype){ if (!fn.EPDFAnnot_SetSubtype(annotPtr, PDF_SUBTYPE_TO_CODE[patch.subtype])){ throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetSubtype returned false'); } } applyPatch(fn, mem, annotPtr, patch, writeContext); if ( patch.contents !== undefined && patch.contents !== currentDto.contents && isDimension({ ...currentDto, ...patch} ) ){ fn.EPDFAnnot_RemoveKey(annotPtr, 'RC'); } let linkedParent: AnnotationRef | null = null; if (patch.reply !== undefined && !sameReply(patch.reply, currentDto.reply)){ writeAnnotationRelationship( this.runtime, this.session, annotPtr, ref.page.objectNumber, patch.reply === null ?{ inReplyTo: null} :{ inReplyTo: patch.reply.to, replyType: patch.reply.type ?? 'reply'} , ); } let relinked = false; if ( patch.subtype === 'popup' && currentDto.subtype === 'popup' && patch.parent !== undefined && !sameRef(patch.parent, currentDto.parent) ){ relinked = true; linkedParent = writePopupParent( this.runtime, this.session, annotPtr, ref.page.objectNumber, patch.parent, currentDto.parent, ); } let linkedOpen: AnnotationRef | null = null; const open = (patch as{ open?: boolean} ).open; if (open !== undefined && !relinked){ const other = currentDto.subtype === 'text' ? currentDto.popup : currentDto.subtype === 'popup' ? currentDto.parent : null; if (other){ linkedOpen = writeLinkedOpen( this.runtime, this.session, other, open, currentDto.subtype === 'popup', ); } } writeAnnotationModified(fn, mem, annotPtr); applyEmbedMetadataOnUpdate(fn, mem, annotPtr, actor); let appearance: AppearanceOutcome; if (impact === 'inert' || impact === 'translation'){ appearance ={ action: 'preserved', changed: false} ; } else{ let ok: boolean; if (currentDto.subtype !== 'widget'){ ok = generateAppearance(fn, annotPtr, patch.blendMode ?? previousBlendMode); } else if (currentDto.hasMark){ refitWidgetMark(fn, mem, annotPtr); ok = false; } else{ ok = fn.EPDFAnnot_GenerateFormFieldAP(annotPtr); } appearance = ok ?{ action: 'regenerated', changed: true} :{ action: 'generation-unavailable', changed: impact === 'regenerate'} ; } fn.FPDFPage_CloseAnnot(annotPtr); annotPtr = null; annotPtr = openAnnotAtRaw(this.runtime, this.session, pageIndex, index); const dto = readAnnotationFromPtr( fn, mem, annotPtr, ref.page.objectNumber, index, readContextFor(this.session, this.fonts), ); joinWidgetFieldNumbers(this.runtime, this.session, [dto]); const meta = annotationMutationMeta( this.session.writeStamp(), ref.page.objectNumber, uniqueRefs([dto.ref, linkedParent, linkedOpen]), ); return{ annotation: dto, appearance, meta} ; } finally{ if (annotPtr !== null) fn.FPDFPage_CloseAnnot(annotPtr); } } private assertNotAttachedWidget(annotPtr: Ptr, releasedFieldObjectNumber: number): void{ const{ fn} = this.runtime; if (fn.FPDFAnnot_GetSubtype(annotPtr) !== PdfAnnotationSubtypeCode.WIDGET) return; const annotObjectNumber = fn.EPDFAnnot_GetObjectNumber(annotPtr); if (releasedFieldObjectNumber > 0 && annotObjectNumber === releasedFieldObjectNumber){ return; } const fieldObjectNumber = resolveWidgetFieldObjectNumber( this.runtime, this.session, annotObjectNumber, ); if (fieldObjectNumber === 0){ return; } throw new EngineError( EngineErrorCode.InvalidArg, fieldObjectNumber === annotObjectNumber ? "widget is its form field's own dictionary (a merged field/widget) - delete the field with doc.forms.delete" : 'widget is attached to a form field - use doc.forms.removeWidget or doc.forms.delete', ); } delete( ref: AnnotationRef, authority: AnnotationAuthority, signal: AbortSignal, ): AnnotationDeleteResult{ throwIfAborted(signal); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const pageObjectNumber = ref.page.objectNumber; const{ pageIndex} = this.session.resolvePageRef(ref.page); const{ annotations} = new RawAnnotationReader(this.runtime, this.session, this.fonts).listOne( pageObjectNumber, signal, ); const members = deletedWith(annotations, ref); if (members.length === 0) throw missingAnnotation(ref); authorizeAnnotationDelete(authority, members); const indexOf = (member: AnnotationRef) => resolveAnnotIndexRaw(this.runtime, this.session, member).index; const positions = members.map((member) => indexOf(member.ref)); for (const index of positions){ this.withAnnotAt(pageIndex, index, (annotPtr) => this.assertNotAttachedWidget(annotPtr, 0)); } const going = new Set(members.map((member) => annotationKey(member.ref))); const keptParents = members.flatMap((member) =>{ if (member.subtype !== 'popup' || !member.parent) return []; const key = annotationKey(member.parent); const parent = annotations.find((annotation) => annotationKey(annotation.ref) === key); return parent && !going.has(key) ? [indexOf(parent.ref)] : []; } ); throwIfAborted(signal); promoteInlineAnnotations(this.runtime, this.session, pageObjectNumber); for (const index of [...positions].sort((a, b) => b - a)){ if (!fn.EPDFPage_RemoveAnnotRaw(docPtr, pageIndex, index)){ throw new EngineError( EngineErrorCode.Unknown, `failed to remove annotation ${ index} on page ${ pageObjectNumber} `, ); } } for (const parent of keptParents){ const before = positions.filter((index) => index < parent).length; this.withAnnotAt(pageIndex, parent - before, (annotPtr) => fn.EPDFAnnot_RemoveKey(annotPtr, 'Popup'), ); } const changed = [...members].reverse().map((member) => member.ref); return{ meta: annotationMutationMeta(this.session.writeStamp(), pageObjectNumber, changed)} ; } deleteReleasedWidget( ref: AnnotationRef, releasedFieldObjectNumber: number, ): AnnotationDeleteResult{ const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const pageObjectNumber = ref.page.objectNumber; const{ pageIndex, index} = resolveAnnotIndexRaw(this.runtime, this.session, ref); const deleted = this.withAnnotAt(pageIndex, index, (annotPtr) =>{ this.assertNotAttachedWidget(annotPtr, releasedFieldObjectNumber); return annotationRefOf(fn, mem, docPtr, ref.page, annotPtr, index); } ); promoteInlineAnnotations(this.runtime, this.session, pageObjectNumber); if (!fn.EPDFPage_RemoveAnnotRaw(docPtr, pageIndex, index)){ throw new EngineError(EngineErrorCode.Unknown, `failed to remove annotation: ${ ref.kind} `); } return{ meta: annotationMutationMeta(this.session.writeStamp(), pageObjectNumber, [deleted])} ; } private withAnnotAt(pageIndex: number, index: number, body: (annotPtr: Ptr) => T): T{ const annotPtr = openAnnotAtRaw(this.runtime, this.session, pageIndex, index); try{ return body(annotPtr); } finally{ this.runtime.fn.FPDFPage_CloseAnnot(annotPtr); } } } AnnotationReader [ClassDeclaration] (from packages/engine/services/src/features/annotations/AnnotationReader.ts): export class AnnotationReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } list(pageObjectNumber: PageObjectNumber, signal: AbortSignal): AnnotationList{ throwIfAborted(signal); const{ fn} = this.runtime; const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); try{ const count = fn.FPDFPage_GetAnnotCount(pagePtr); return collectPageAnnotations({ runtime: this.runtime, session: this.session, pageObjectNumber, count, getAnnotPtrAt: (i) => fn.FPDFPage_GetAnnot(pagePtr, i), signal, ...(this.fonts ?{ fonts: this.fonts} :{ } ), } ); } finally{ pool.release(pageObjectNumber); } } } AppliedChange [InterfaceDeclaration] (from packages/engine/services/src/features/changes/ChangeApplier.ts): export interface AppliedChange{ readonly items: ChangeItem[]; readonly record: ChangeRecord; } AttachmentMutator [ClassDeclaration] (from packages/engine/services/src/features/attachments/AttachmentMutator.ts): export class AttachmentMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } create( file: AttachmentFileBase, bytes: ArrayBuffer | undefined, signal: AbortSignal, ): AttachmentCreateResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); if (!bytes){ throw new EngineError( EngineErrorCode.InvalidArg, 'an attachments.create op needs its bytes as its file resource', { details:{ field: 'resources.file'} } , ); } if (file.name.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'attachment file requires a name'); } if (resolveAttachmentIndex(fn, mem, docPtr, { kind: 'key', key: file.name} ) !== -1){ throw new EngineError( EngineErrorCode.InvalidArg, `an embedded file with key '${ file.name} ' already exists — keys are unique; rename and retry`, ); } throwIfAborted(signal); const namePtr = mem.writeU16String(file.name); let attachmentPtr: Ptr; try{ attachmentPtr = fn.FPDFDoc_AddAttachment(docPtr, namePtr); } finally{ mem.free(namePtr); } if (!attachmentPtr){ throw new EngineError(EngineErrorCode.Unknown, 'FPDFDoc_AddAttachment returned NULL'); } writeAttachmentFilePayload(fn, mem, attachmentPtr, docPtr, file, { bytes, ...(file.mimeType !== undefined ?{ mimeType: file.mimeType} :{ } ), name: file.name, } ); const ref = toAttachmentRef(file.name); const attachment = this.find(ref); if (!attachment){ throw new EngineError( EngineErrorCode.Unknown, 'created attachment did not resolve by key after the write', ); } return{ attachment, meta: this.meta(ref)} ; } find(ref: AttachmentRef): Attachment | null{ const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const index = resolveAttachmentIndex(fn, mem, docPtr, ref); const attachmentPtr = index < 0 ? null : fn.FPDFDoc_GetAttachment(docPtr, index); if (!attachmentPtr) return null; return{ ...readAttachmentFileInfo(fn, mem, attachmentPtr), ref, index} ; } meta(ref: AttachmentRef): AttachmentMutationMeta{ return{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp(), changedRefs: [ref], } ; } delete(ref: AttachmentRef, signal: AbortSignal): AttachmentDeleteResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const index = resolveAttachmentIndex(fn, mem, docPtr, ref); if (index < 0){ throw new EngineError( EngineErrorCode.NotFound, `no embedded file with key '${ ref.key} ' in the document`, ); } if (!fn.FPDFDoc_DeleteAttachment(docPtr, index)){ throw new EngineError(EngineErrorCode.Unknown, 'FPDFDoc_DeleteAttachment returned false'); } return{ meta: this.meta(ref)} ; } } AttachmentReader [ClassDeclaration] (from packages/engine/services/src/features/attachments/AttachmentReader.ts): export class AttachmentReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } list(signal: AbortSignal): Attachment[]{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const count = fn.FPDFDoc_GetAttachmentCount(docPtr); const items: Attachment[] = []; for (let index = 0; index < count; index++){ const attachmentPtr = fn.FPDFDoc_GetAttachment(docPtr, index); if (!attachmentPtr) continue; const key = readAttachmentKey(fn, mem, docPtr, index) ?? ''; items.push({ ...readAttachmentFileInfo(fn, mem, attachmentPtr), ref: toAttachmentRef(key), index, } ); } return items; } readFile( ref: AttachmentRef, path: string | undefined, maxDecodedBytes: number | undefined, signal: AbortSignal, ): AttachmentFileWorkerPayload{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const index = resolveAttachmentIndex(fn, mem, docPtr, ref); if (index < 0){ throw new EngineError( EngineErrorCode.NotFound, `no embedded file with key '${ ref.key} ' in the document`, ); } const attachmentPtr = fn.FPDFDoc_GetAttachment(docPtr, index); if (!attachmentPtr){ throw new EngineError( EngineErrorCode.Unknown, `embedded file with key '${ ref.key} ' resolved to index ${ index} but could not be opened`, ); } const info = readAttachmentFileInfo(fn, mem, attachmentPtr); return this.extract( attachmentPtr, info.name, info.mimeType ?? undefined, path, maxDecodedBytes, ); } async readAnnotationFile( pageObjectNumber: PageObjectNumber, ref: AnnotationRef, path: string | undefined, maxDecodedBytes: number | undefined, signal: AbortSignal, slices: Slices, ): Promise{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const pool = this.session.pagePool(); const pagePtr = await pool.acquireInSlices(pageObjectNumber, signal, slices); let annotPtr: Ptr | null = null; try{ annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref); const attachmentPtr = fn.FPDFAnnot_GetFileAttachment(annotPtr); if (!attachmentPtr){ throw new EngineError( EngineErrorCode.InvalidArg, 'annotation is not a file attachment or carries no embedded file (/FS)', ); } const info = readAttachmentFileInfo(fn, mem, attachmentPtr); return this.extract( attachmentPtr, info.name, info.mimeType ?? undefined, path, maxDecodedBytes, ); } finally{ if (annotPtr !== null) fn.FPDFPage_CloseAnnot(annotPtr); pool.release(pageObjectNumber); } } private extract( attachmentPtr: Ptr, name: string, mimeType: string | undefined, path: string | undefined, maxDecodedBytes: number | undefined, ): AttachmentFileWorkerPayload{ if (path !== undefined){ const{ size} = extractAttachmentToFile(this.runtime, attachmentPtr, path, maxDecodedBytes); return{ name, ...(mimeType ?{ mimeType} :{ } ), size, path} ; } const{ bytes, size} = extractAttachmentToBuffer(this.runtime, attachmentPtr, maxDecodedBytes); return{ name, ...(mimeType ?{ mimeType} :{ } ), size, bytes} ; } } BaseDocumentRegistry [ClassDeclaration] (from packages/engine/services/src/document-session/lifecycle/BaseDocumentRegistry.ts): export class BaseDocumentRegistry{ private readonly entries = new Map(); constructor(private readonly runtime: PdfRuntimeModule){ } acquireMemoryBase(opts:{ key: string; bytes: Uint8Array; password?: string | null; knownSha256?: string; } ): AcquiredBaseDocument{ const existing = this.retain(opts.key); if (existing) return existing; const{ mem, fn} = this.runtime; const stack = new CloseStack(); const dataPtr = mem.alloc(opts.bytes.byteLength); stack.push(() => mem.free(dataPtr)); try{ mem.writeBytes(dataPtr, opts.bytes); const basePtr = fn.EPDF_LoadMemBaseDocument64( dataPtr, opts.bytes.byteLength, opts.password ?? '', ); if (!basePtr){ throw baseOpenError(this.runtime, opts.password); } setRuntimeOwnerPermissionsIfEncrypted(this.runtime, basePtr); stack.push(() => fn.EPDF_ReleaseBaseDocument(basePtr)); this.supplyKnownSha(basePtr, opts.knownSha256); return this.insert({ key: opts.key, kind: 'memory', basePtr, refs: 1, close: () => stack.close(), } ); } catch (error){ stack.close(); throw error; } } acquireFileBase(opts:{ key: string; path: string; password?: string | null; knownSha256?: string; } ): AcquiredBaseDocument{ const existing = this.retain(opts.key); if (existing) return existing; const{ fn} = this.runtime; const stack = new CloseStack(); let access: PdfFileAccessHandle | null = null; try{ access = this.runtime.fileAccess.fromNodeFile(opts.path); stack.push(() => access?.close()); const basePtr = fn.EPDF_LoadBaseDocument(access.ptr, opts.password ?? ''); if (!basePtr){ throw baseOpenError(this.runtime, opts.password); } setRuntimeOwnerPermissionsIfEncrypted(this.runtime, basePtr); stack.push(() => fn.EPDF_ReleaseBaseDocument(basePtr)); this.supplyKnownSha(basePtr, opts.knownSha256); return this.insert({ key: opts.key, kind: 'file', path: opts.path, basePtr, refs: 1, close: () => stack.close(), } ); } catch (error){ stack.close(); throw error; } } retainByKey(key: string): AcquiredBaseDocument | null{ return this.retain(key); } private supplyKnownSha(basePtr: Ptr, sha256Hex: string | undefined): void{ if (!sha256Hex || !/^[0-9a-fA-F]{ 64} $/.test(sha256Hex)) return; const{ mem, fn} = this.runtime; const bytes = new Uint8Array(32); for (let i = 0; i < 32; i++) bytes[i] = parseInt(sha256Hex.slice(i * 2, i * 2 + 2), 16); const ptr = mem.alloc(32); try{ mem.writeBytes(ptr, bytes); fn.EPDF_SetBaseDocumentSha256(basePtr, ptr); } finally{ mem.free(ptr); } } releaseAll(): void{ const entries = Array.from(this.entries.values()); this.entries.clear(); let firstError: unknown = null; for (const entry of entries){ try{ entry.close(); } catch (error){ firstError ??= error; } } if (firstError) throw firstError; } getRefCountForTesting(key: string): number{ return this.entries.get(key)?.refs ?? 0; } private retain(key: string): AcquiredBaseDocument | null{ const entry = this.entries.get(key); if (!entry) return null; entry.refs++; return this.handleFor(entry); } private insert(entry: BaseEntry): AcquiredBaseDocument{ this.entries.set(entry.key, entry); return this.handleFor(entry); } private handleFor(entry: BaseEntry): AcquiredBaseDocument{ let released = false; return{ key: entry.key, kind: entry.kind, ...(entry.path !== undefined ?{ path: entry.path} :{ } ), basePtr: entry.basePtr, release: () =>{ if (released) return; released = true; const live = this.entries.get(entry.key); if (!live) return; live.refs--; if (live.refs > 0) return; this.entries.delete(entry.key); live.close(); } , } ; } } BatchCreate [InterfaceDeclaration] (from packages/engine/services/src/features/annotations/AnnotationBatchApplier.ts): export interface BatchCreate{ readonly page: PageRef; readonly draft: AnnotationDraft; readonly replyTo?:{ readonly to: BatchLinkTarget; readonly type: AnnotationReplyType} ; readonly parent?: BatchLinkTarget; readonly resources?: WireAnnotationResources; readonly objectNumber?: number; readonly attribution: |{ readonly kind: 'stamp'; readonly actor?: AnnotationActor} |{ readonly kind: 'restore'; readonly from: RestoredAttribution; readonly importedBy?: string; } ; readonly fileDates?: Pick; readonly label?: string; } BatchCreateResult [InterfaceDeclaration] (from packages/engine/services/src/features/annotations/AnnotationBatchApplier.ts): export interface BatchCreateResult{ created: Annotation[]; meta: AnnotationListMutationMeta; } CandidateFinalizer [ClassDeclaration] (from packages/engine/services/src/features/signature/CandidateFinalizer.ts): export class CandidateFinalizer{ constructor( private readonly runtime: PdfRuntimeModule, private readonly baseDocuments: BaseDocumentRegistry, ){ } finalize(input: FinalizeCandidateInput): FinalizedCandidate{ const [r0, r1, r2, r3] = input.byteRange; const size = this.runtime.fileAccess.sizeOf(input.path); const isOffset = (n: number) => Number.isSafeInteger(n) && n >= 0; if (!input.byteRange.every(isOffset) || r0 !== 0 || r1 >= r2 || r2 + r3 !== size){ throw new EngineError( EngineErrorCode.InvalidArg, `byteRange [${ input.byteRange.join(' ')} ] does not span a ${ size} -byte candidate`, ); } const hexLength = r2 - r1 - 2; if ( !Number.isSafeInteger(input.contentsSizeBytes) || hexLength !== 2 * input.contentsSizeBytes ){ throw new EngineError( EngineErrorCode.InvalidArg, `the /Contents hole holds ${ hexLength} hex digits, not the ${ 2 * input.contentsSizeBytes} of contentsSize`, ); } if (input.cms.byteLength === 0 || input.cms[0] !== 0x30){ throw new EngineError(EngineErrorCode.SignatureRefused, 'the CMS is not a DER SEQUENCE'); } if (input.cms.byteLength > input.contentsSizeBytes){ throw new EngineError( EngineErrorCode.SignatureRefused, `the CMS (${ input.cms.byteLength} bytes) does not fit the reserved ${ input.contentsSizeBytes} bytes`, ); } writeContentsIntoFile(this.runtime, input.path, { holeOffset: r1, hexLength} , input.cms); const session = new DocumentSession(this.runtime); const base = this.baseDocuments.acquireFileBase({ key: `finalize:${ generateUuid()} `, path: input.path, password: input.password, } ); try{ session.openFromHandle( openLayerDocument(this.runtime, base, { kind: 'fresh'} , input.password), ); const model = acquireSignatureModel(this.runtime, session); assertSealedSignature(this.runtime, session.requireDocPtr(), model, { fieldObjectNumber: input.fieldObjectNumber, byteRange: input.byteRange, cms: input.cms, } ); const reader = new SignatureReader(this.runtime, session); const snapshot = reader.readSnapshot(); const signature = snapshot.signatures.find( (s) => s.field.kind === 'objectNumber' && s.field.objectNumber === input.fieldObjectNumber, )!; return{ signature, protection: snapshot.protection, version: reader.version(), lastObjectNumber: session.lastObjectNumber(), } ; } finally{ session.close(); } } } ChangeApplier [ClassDeclaration] (from packages/engine/services/src/features/changes/ChangeApplier.ts): export class ChangeApplier{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, private readonly limits: BundleLimits = DEFAULT_BUNDLE_LIMITS, ){ } apply( ops: readonly RecordedOp[], authority: ChangeAuthority, signal: AbortSignal, space: ChangeSpace, ): AppliedChange{ const ctx = this.context(authority, signal, (self) => opsFillOwnField(self, ops)); return collect( this.session, authority, ops.map((op, at) => () => runOp(ctx, space.opInFileSpace(op), at)), space, signal, ); } undo( record: ChangeRecord, authority: ChangeAuthority, signal: AbortSignal, space: Pick, 'itemOut'>, ): AppliedChange{ const ctx = this.context(authority, signal, (self) => stepsFillOwnField(self, record.steps)); return collect( this.session, authority, record.steps.map((step) => () => runStep(ctx, step)), space, signal, ); } private context( authority: ChangeAuthority, signal: AbortSignal, ownFill: (ctx: ChangeContext) => boolean, ): ChangeContext{ let answer: boolean | undefined; const ctx: ChangeContext ={ runtime: this.runtime, session: this.session, ...(this.fonts ?{ fonts: this.fonts} :{ } ), authority, signal, limits: this.limits, fillsOwnField: () => (answer ??= ownFill(ctx)), } ; return ctx; } } ChangeLedger [ClassDeclaration] (from packages/engine/services/src/features/changes/ChangeLedger.ts): export class ChangeLedger{ private readonly entries = new Map(); private bytes = 0; outcome(opId: string): ChangeOutcome | undefined{ return this.entries.get(opId)?.outcome; } record( opId: string, ): |{ readonly record: ChangeRecord | null} |{ readonly unavailable: UndoUnavailableReason} | undefined{ const entry = this.entries.get(opId); if (!entry) return undefined; if (entry.unavailable) return{ unavailable: entry.unavailable} ; return{ record: entry.record} ; } keepApplied( opId: string, fingerprint: string, result: KeptResult, record: ChangeRecord | null, ): void{ const bytes = record ? recordBytes(record) : 0; this.add(opId, { outcome:{ kind: 'applied', fingerprint, result} , record, bytes} ); this.bytes += bytes; this.trimCaptures(); } keepRefused(opId: string, fingerprint: string, error: SerializedEngineError): void{ this.add(opId, { outcome:{ kind: 'refused', fingerprint, error} , record: null, bytes: 0} ); } endUndo(): void{ for (const entry of this.entries.values()){ if (entry.outcome.kind === 'applied' && !entry.unavailable){ this.drop(entry, 'final-change'); } } } private add(opId: string, entry: Entry): void{ this.entries.set(opId, entry); for (const [key, old] of this.entries){ if (this.entries.size <= OUTCOME_LIMIT) break; this.drop(old, 'expired'); this.entries.delete(key); } } private trimCaptures(): void{ for (const entry of this.entries.values()){ if (this.bytes <= CAPTURE_BUDGET) break; if (entry.bytes > 0) this.drop(entry, 'expired'); } } private drop(entry: Entry, reason: UndoUnavailableReason): void{ this.bytes -= entry.bytes; entry.record = null; entry.bytes = 0; entry.unavailable = reason; } } ChangeOutcome [TypeAliasDeclaration] (from packages/engine/services/src/features/changes/ChangeLedger.ts): export type ChangeOutcome = |{ readonly kind: 'applied'; readonly fingerprint: string; readonly result: KeptResult; } |{ readonly kind: 'refused'; readonly fingerprint: string; readonly error: SerializedEngineError; } ; ChangeRecord [InterfaceDeclaration] (from packages/engine/services/src/features/changes/ChangeRecord.ts): export interface ChangeRecord{ readonly userId: string | null; readonly steps: readonly ReverseStep[]; } ChangeSpace [InterfaceDeclaration] (from packages/engine/services/src/features/changes/ChangeApplier.ts): export interface ChangeSpace{ opInFileSpace( op: RecordedOp, ): RecordedOp; itemOut(item: ChangeItem): ChangeItem; } CloseStack [ClassDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export class CloseStack{ private readonly actions: Array<() => void> = []; private closed = false; push(action: () => void): void{ if (this.closed){ action(); return; } this.actions.push(action); } close(): void{ if (this.closed) return; this.closed = true; let firstError: unknown = null; for (let i = this.actions.length - 1; i >= 0; i--){ try{ this.actions[i]?.(); } catch (error){ firstError ??= error; } } this.actions.length = 0; if (firstError) throw firstError; } } DIGEST_CODE [VariableDeclaration] (from packages/engine/services/src/features/signature/SignatureReader.ts): DIGEST_CODE: Record ={ sha1: 0, sha256: 1, sha384: 2, sha512: 3, } DocumentActionsReader [ClassDeclaration] (from packages/engine/services/src/features/actions/DocumentActionsReader.ts): export class DocumentActionsReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } read(signal: AbortSignal): DocumentActionsSnapshot{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const budget = new ActionReadBudgetTracker(); const count = fn.FPDFDoc_GetJavaScriptActionCount(docPtr); if (count < 0){ throw new EngineError( EngineErrorCode.MalformedPdf, 'failed to enumerate PDF name-tree scripts', ); } const nameTreeScripts: DocumentActionsSnapshot['nameTreeScripts'] = []; for (let index = 0; index < count; index++){ throwIfAborted(signal); const namedPtr = fn.FPDFDoc_GetJavaScriptAction(docPtr, index); if (namedPtr === NULL_PTR){ throw new EngineError(EngineErrorCode.MalformedPdf, 'invalid PDF name-tree script entry', { details:{ index} , } ); } let name: string; try{ name = readUtf16String(mem, (buf, capacity) => fn.FPDFJavaScriptAction_GetName(namedPtr, buf, capacity), ) ?? ''; } finally{ fn.FPDFDoc_CloseJavaScriptAction(namedPtr); } budget.reservePayloadBytes(name.length); const action = requireAction( readActionModel( fn, mem, docPtr, fn.EPDFDoc_GetNamedJavaScriptActionModel(docPtr, index), budget, ), 'name-tree script', index, ); nameTreeScripts.push({ name, action} ); } const openAction = readActionModel( fn, mem, docPtr, fn.EPDFDoc_GetOpenActionModel(docPtr), budget, ); const openDestPtr = openAction ? NULL_PTR : fn.EPDFDoc_GetOpenActionDest(docPtr); const openDestination = openDestPtr !== NULL_PTR ? readDestination(fn, mem, docPtr, openDestPtr) : null; const additional: Partial< Record<(typeof DOCUMENT_ACTION_EVENTS)[number][0], PdfActionTree> > ={ } ; for (const [key, event] of DOCUMENT_ACTION_EVENTS){ throwIfAborted(signal); const action = readActionModel( fn, mem, docPtr, fn.EPDFDoc_GetAdditionalActionModel(docPtr, event), budget, ); if (action) additional[key] = action; } return{ nameTreeScripts, openAction, openDestination, ...additional} ; } } DocumentFontChoice [TypeAliasDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export type DocumentFontChoice = NonNullable>; DocumentFontReader [ClassDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export class DocumentFontReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts: FontRegistrar, ){ } facts(): FontListFacts{ return{ faces: this.faces(), engineFonts: this.fonts.engineFontFacts(), fallbacks: this.fonts.fallbackKeys(), } ; } faces(): DocumentFaceFacts[]{ return readDocumentFaces(this.runtime, this.session); } resolve( annotation: AnnotationRef | undefined, runs: readonly FontResolveRun[], facts: FontListFacts, ):{ runs: ResolvedRunFacts[]; missingCharacters: string[]} { const{ fn, mem} = this.runtime; const faces = runs.map((run) => this.faceOfRun(run, facts)); const texts = runs.map((run) => mem.writeU16String(run.text)); const families = faces.map((face) => mem.writeU16String(face.family)); const annotPtr = annotation ? this.openAnnotation(annotation) : NULL_PTR; try{ const resolution = withPointerTable(this.runtime, texts, (textTable) => withPointerTable(this.runtime, families, (familyTable) => withI32Array( mem, faces.map((face) => face.weight), (weights) => withI32Array( mem, faces.map((face) => (face.italic ? 1 : 0)), (italics) => withI32Array( mem, faces.map((face) => face.program), (programs) => fn.EPDFDoc_ResolveFonts( this.session.requireDocPtr(), annotPtr, runs.length, textTable, familyTable, weights, italics, programs, ), ), ), ), ), ); if (!resolution){ throw new EngineError(EngineErrorCode.Unknown, 'EPDFDoc_ResolveFonts failed'); } try{ return this.readResolution(resolution, runs.length); } finally{ fn.EPDFFontResolution_Close(resolution); } } finally{ if (annotPtr) fn.FPDFPage_CloseAnnot(annotPtr); for (const ptr of [...texts, ...families]) mem.free(ptr); } } private readResolution( resolution: Ptr, count: number, ):{ runs: ResolvedRunFacts[]; missingCharacters: string[]} { const{ fn, mem} = this.runtime; const runs: ResolvedRunFacts[] = []; for (let run = 0; run < count; run++){ const registered = fn.EPDFFontResolution_GetRegisteredFont(resolution, run); const fallbackCount = fn.EPDFFontResolution_GetFallbacks(resolution, run, NULL_PTR, 0); const fallbackIds = withScratch(mem, Math.max(1, fallbackCount) * 4, (out) =>{ fn.EPDFFontResolution_GetFallbacks(resolution, run, out, fallbackCount); return Array.from({ length: fallbackCount} , (_, at) => Number(mem.peek(out, 'i32', at * 4)) >>> 0, ); } ); runs.push({ source: SOURCES[fn.EPDFFontResolution_GetSource(resolution, run)] ?? 'standard', engineFont: registered ? (this.fonts.keyForId(registered) ?? null) : null, objectNumber: fn.EPDFFontResolution_GetProgramObjNum(resolution, run), displaySha256: withScratch(mem, 32, (out) => fn.EPDFFontResolution_GetProgramDisplayHash(resolution, run, out) ? hex(mem.readBytes(out, 32)) : null, ), baseFontName: readUtf8String(mem, (buf, cap) => fn.EPDFFontResolution_GetBaseFontName(resolution, run, buf, cap), ) || null, familyName: readUtf16String(mem, (buf, cap) => fn.EPDFFontResolution_GetFamily(resolution, run, buf, cap), ) ?? '', weight: fn.EPDFFontResolution_GetWeight(resolution, run), italic: fn.EPDFFontResolution_IsItalic(resolution, run), degraded: fn.EPDFFontResolution_IsDegraded(resolution, run), fallbacks: fallbackIds.flatMap((id) =>{ const key = this.fonts.keyForId(id); return key ? [key] : []; } ), } ); } const missingCharacters: string[] = []; const missingCount = fn.EPDFFontResolution_CountMissingCharacters(resolution); for (let index = 0; index < missingCount; index++){ const character = readUtf16String(mem, (buf, cap) => fn.EPDFFontResolution_GetMissingCharacter(resolution, index, buf, cap), ); if (character) missingCharacters.push(character); } return{ runs, missingCharacters} ; } private faceOfRun( run: FontResolveRun, facts: FontListFacts, ):{ family: string; weight: number; italic: boolean; program: number} { if (!('fontFamily' in run)){ return{ family: run.family, weight: run.weight, italic: run.italic, program: 0} ; } const name = run.fontFamily; if (isStandardFontName(name)){ const face = STANDARD_FACES[name]; return{ family: face.family, weight: face.weight, italic: face.italic, program: 0} ; } const registered = this.fonts.describeOrUndefined(name); if (registered){ const{ familyName, weight, italic} = registered; return{ family: familyName, weight, italic, program: 0} ; } const document = documentFontsOf(facts.faces).find((font) => font.name === name); if (document){ const{ familyName, weight, italic} = document.face; const choice = documentProgramForName(facts, name); const program = choice?.choosable ? choice.objectNumber : 0; return{ family: familyName, weight, italic, program} ; } const face = faceForFontName(name); return{ family: face.family, weight: face.weight ?? 400, italic: face.italic ?? false, program: 0, } ; } private openAnnotation(ref: AnnotationRef): Ptr{ const{ pageIndex, index} = resolveAnnotIndexRaw(this.runtime, this.session, ref); const annotPtr = this.runtime.fn.EPDFPage_GetAnnotRaw( this.session.requireDocPtr(), pageIndex, index, ); if (!annotPtr){ throw new EngineError(EngineErrorCode.NotFound, 'annotation not found'); } return annotPtr; } program( displaySha256: string, data: boolean, ):{ covers: CodePointRange[]; ascent: number; descent: number; bytes: Uint8Array | null} { const engineFont = this.fonts.programFor(displaySha256); if (engineFont) return{ ...engineFont.info(), bytes: data ? engineFont.bytes() : null} ; const program = this.faces() .flatMap((face) => face.programs) .find((candidate) => candidate.displaySha256 === displaySha256 && candidate.objectNumber > 0); if (!program){ throw new EngineError(EngineErrorCode.NotFound, `no font program ${ displaySha256} `); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); return withScratch(mem, 32, (hash) =>{ mem.writeBytes(hash, bytesOfHex(displaySha256)); const covers = readRanges(this.runtime, (out, capacity) => fn.EPDFDoc_GetFontDisplayProgramCoverage(docPtr, hash, out, capacity), ); let bytes: Uint8Array | null = null; if (data){ const length = fn.EPDFDoc_GetFontDisplayProgramData(docPtr, hash, NULL_PTR, 0); bytes = withScratch(mem, Math.max(1, length), (out) =>{ fn.EPDFDoc_GetFontDisplayProgramData(docPtr, hash, out, length); return mem.readBytes(out, length); } ); } return{ covers, ascent: program.ascent, descent: program.descent, bytes} ; } ); } } DocumentPagesMutator [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesMutator.ts): export class PagesMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } reorder( pages: PageRef[], position: PagePosition, signal: AbortSignal, ): PageReorderResult{ const pageObjectNumbers = this.session.resolvePageRefs(pages); throwIfAborted(signal); this.requireUniquePageObjectNumbers('pages.reorder', pageObjectNumbers); const anchor = anchorOf(position); if (anchor && pageObjectNumbers.includes(anchor.objectNumber)){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.reorder: the neighbour page ${ anchor.objectNumber} is one of the pages that move`, { details:{ field: 'position'} } , ); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const fromIndices = pageObjectNumbers.map((pageObjectNumber) =>{ throwIfAborted(signal); return this.session.recordByObjectNumber(pageObjectNumber).pageIndex; } ); const at = pageIndexAt(this.session, position, fn.FPDF_GetPageCount(docPtr)); const toIndex = at - fromIndices.filter((index) => index < at).length; const arrPtr = mem.alloc(4 * fromIndices.length); let ok: boolean; try{ for (let i = 0; i < fromIndices.length; i++){ mem.poke(arrPtr, 'i32', fromIndices[i], 4 * i); } ok = fn.FPDF_MovePages(docPtr, arrPtr, fromIndices.length, toIndex); } finally{ mem.free(arrPtr); } if (!ok){ throw new EngineError( EngineErrorCode.InvalidArg, `FPDF_MovePages rejected the request (toIndex=${ toIndex} , fromIndices=[${ fromIndices.join( ', ', )} ])`, ); } this.session.refreshPageRegistry(); const layout = new PagesReader(this.runtime, this.session).read(signal); return{ pages: pageObjectNumbers.map(toPageRef), layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} , } ; } rotate( pages: PageRef[], rotation: PdfRotation, signal: AbortSignal, ): PageRotateResult{ const pageObjectNumbers = this.session.resolvePageRefs(pages); throwIfAborted(signal); this.requireUniquePageObjectNumbers('pages.rotate', pageObjectNumbers); if (rotation !== 0 && rotation !== 90 && rotation !== 180 && rotation !== 270){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.rotate rotation must be 0, 90, 180 or 270 (got ${ rotation} )`, ); } const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); for (const pageObjectNumber of pageObjectNumbers){ this.session.recordByObjectNumber(pageObjectNumber); } const quarterTurns = rotation / 90; for (const pageObjectNumber of pageObjectNumbers){ if (!fn.EPDFDoc_SetPageRotationByObjectNumber(docPtr, pageObjectNumber, quarterTurns)){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_SetPageRotationByObjectNumber rejected page ${ pageObjectNumber} after validation`, ); } } const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } delete(pages: PageRef[], signal: AbortSignal): PageDeleteResult{ const pageObjectNumbers = this.session.resolvePageRefs(pages); throwIfAborted(signal); this.requireUniquePageObjectNumbers('pages.delete', pageObjectNumbers); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const totalPages = fn.FPDF_GetPageCount(docPtr); if (pageObjectNumbers.length >= totalPages){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.delete would remove every page (${ pageObjectNumbers.length} of ${ totalPages} ); a document must keep at least one`, ); } const pool = this.session.pagePool(); for (const pageObjectNumber of pageObjectNumbers){ this.session.recordByObjectNumber(pageObjectNumber); if (pool.isHeld(pageObjectNumber)){ throw new EngineError( EngineErrorCode.Unknown, `internal invariant violation: pagePtr for page ${ pageObjectNumber} is still held during pages.delete`, ); } } for (const pageObjectNumber of pageObjectNumbers){ if (!fn.EPDFDoc_DeletePageByObjectNumber(docPtr, pageObjectNumber)){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_DeletePageByObjectNumber rejected page ${ pageObjectNumber} after validation`, ); } } this.session.refreshPageRegistry(); const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } setName(input: PageNameInput, signal: AbortSignal): PageNameResult{ throwIfAborted(signal); if (input.name.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'pages.setName requires a non-empty name'); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const pageObjectNumber = this.session.resolvePageRef(input.page).pageObjectNumber; if (input.replace !== undefined && input.replace !== input.name && input.replace.length > 0){ writeUtf16String(mem, input.replace, (ptr) => fn.EPDFDoc_RemoveNamedPage(docPtr, ptr)); } const ok = writeUtf16String(mem, input.name, (ptr) => fn.EPDFDoc_SetNamedPage(docPtr, ptr, pageObjectNumber), ); if (!ok){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_SetNamedPage rejected '${ input.name} ' for page ${ pageObjectNumber} `, ); } const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } removeName(input: PageRemoveNameInput, signal: AbortSignal): PageNameResult{ throwIfAborted(signal); if (input.name.length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'pages.removeName requires a non-empty name', ); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const removed = writeUtf16String(mem, input.name, (ptr) => fn.EPDFDoc_RemoveNamedPage(docPtr, ptr), ); if (!removed){ throw new EngineError( EngineErrorCode.NotFound, `pages.removeName: no /Names /Pages registration '${ input.name} '`, ); } const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } private requireUniquePageObjectNumbers(op: string, pageObjectNumbers: PageObjectNumber[]): void{ if (pageObjectNumbers.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, `${ op} requires at least one page`); } const seen = new Set(); for (const pageObjectNumber of pageObjectNumbers){ if (seen.has(pageObjectNumber)){ throw new EngineError( EngineErrorCode.InvalidArg, `${ op} was given duplicate page object number ${ pageObjectNumber} `, ); } seen.add(pageObjectNumber); } } } DocumentSaver [ClassDeclaration] (from packages/engine/services/src/features/save/DocumentSaver.ts): export class DocumentSaver{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } snapshot():{ bytes: ArrayBuffer; source: SaveSource} { if (!this.session.hasUnsavedEdits()){ return{ bytes: this.loadedBytes(), source: 'loaded'} ; } const saved = this.saveStandaloneToBufferEx('incremental'); if (saved.unchangedSinceLoad){ return{ bytes: this.loadedBytes(), source: 'loaded'} ; } return{ bytes: saved.bytes, source: 'working-copy'} ; } loadedBytes(): ArrayBuffer{ return new SignatureReader(this.runtime, this.session).loadedBytes(); } copyLoadedBytesToFile(path: string): void{ const reader = new SignatureReader(this.runtime, this.session); const size = Number(this.runtime.fn.EPDFDoc_GetLoadedBytesSize(this.session.requireDocPtr())); const chunk = 4 * 1024 * 1024; this.runtime.fileWrite.removeFile(path); for (let offset = 0; offset < size; offset += chunk){ const length = Math.min(chunk, size - offset); this.runtime.fileWrite.appendBytes(path, new Uint8Array(reader.readLoadedBytes(offset, length))); } if (size === 0) this.runtime.fileWrite.appendBytes(path, new Uint8Array(0)); } snapshotToFile(path: string):{ path: string; source: SaveSource} { if (!this.session.hasUnsavedEdits()){ this.copyLoadedBytesToFile(path); return{ path, source: 'loaded'} ; } const saved = this.saveStandaloneToFileEx(path, 'incremental'); if (saved.unchangedSinceLoad){ this.copyLoadedBytesToFile(path); return{ path, source: 'loaded'} ; } return{ path, source: 'working-copy'} ; } canWriteScratchFiles(): boolean{ return this.runtime.kind === 'native' && this.session.source.base?.kind === 'file'; } saveLayerArtifact():{ bytes: ArrayBuffer; size: number} { const saved = this.saveLayerArtifactImpl( false); if (saved.size <= 0){ throw layerSaveError(-1); } return{ bytes: saved.bytes, size: saved.size} ; } saveLayerArtifactEx():{ bytes: ArrayBuffer; size: number; changedSinceLoad: boolean} { return this.saveLayerArtifactImpl( true); } saveLayerArtifactToFileEx(path: string):{ path: string; changedSinceLoad: boolean} { this.requireLayer(); return this.saveLayerToFileImpl(path, 'artifact'); } saveLayerDeltaToFileEx(path: string):{ path: string; changedSinceLoad: boolean} { this.requireLayer(); return this.saveLayerToFileImpl(path, 'delta'); } private saveLayerToFileImpl( path: string, what: 'artifact' | 'delta', ):{ path: string; changedSinceLoad: boolean} { const{ mem, fn} = this.runtime; const statusPtr = mem.alloc(4); const changedPtr = mem.alloc(4); this.runtime.fileWrite.removeFile(path); const writer = this.runtime.fileWrite.toNodeFile(path); try{ mem.poke(statusPtr, 'i32', -1); mem.poke(changedPtr, 'i32', 1); const ok = what === 'artifact' ? fn.EPDFLayer_SaveLayerArtifactEx(this.session.requireDocPtr(), writer.ptr, statusPtr, changedPtr) : fn.EPDFLayer_SaveDeltaEx(this.session.requireDocPtr(), writer.ptr, statusPtr, changedPtr); const status = Number(mem.peek(statusPtr, 'i32')); if (!ok || status !== 0){ throw layerSaveError(status); } return{ path, changedSinceLoad: Number(mem.peek(changedPtr, 'i32')) !== 0} ; } finally{ writer.close(); mem.free(changedPtr); mem.free(statusPtr); } } private saveLayerArtifactImpl(reporting: boolean):{ bytes: ArrayBuffer; size: number; changedSinceLoad: boolean; } { this.requireLayer(); const{ mem, fn} = this.runtime; const sizePtr = mem.alloc(8); const statusPtr = mem.alloc(4); const changedPtr = mem.alloc(4); let artifactPtr: Ptr | null = null; try{ mem.poke(sizePtr, 'i32', 0); mem.poke(statusPtr, 'i32', -1); mem.poke(changedPtr, 'i32', 1); artifactPtr = reporting ? fn.EPDFLayer_SaveLayerArtifactToOwnedBufferEx( this.session.requireDocPtr(), sizePtr, statusPtr, changedPtr, ) : fn.EPDFLayer_SaveLayerArtifactToOwnedBuffer( this.session.requireDocPtr(), sizePtr, statusPtr, ); const status = Number(mem.peek(statusPtr, 'i32')); const size = Number(mem.peek(sizePtr, 'i32')); const changedSinceLoad = reporting ? Number(mem.peek(changedPtr, 'i32')) !== 0 : true; if (status !== 0){ throw layerSaveError(status); } if (reporting && !changedSinceLoad){ return{ bytes: new ArrayBuffer(0), size: 0, changedSinceLoad: false} ; } if (!artifactPtr || size <= 0){ throw layerSaveError(status); } const bytes = mem.readBytes(artifactPtr, size); const buffer = new ArrayBuffer(bytes.byteLength); new Uint8Array(buffer).set(bytes); return{ bytes: buffer, size, changedSinceLoad} ; } finally{ if (artifactPtr) fn.EPDF_FreeBuffer(artifactPtr); mem.free(changedPtr); mem.free(statusPtr); mem.free(sizePtr); } } saveLayerDelta():{ bytes: ArrayBuffer; size: number} { const saved = this.saveLayerDeltaImpl( false); return{ bytes: saved.bytes, size: saved.size} ; } saveLayerDeltaEx():{ bytes: ArrayBuffer; size: number; changedSinceLoad: boolean} { return this.saveLayerDeltaImpl( true); } private saveLayerDeltaImpl(reporting: boolean):{ bytes: ArrayBuffer; size: number; changedSinceLoad: boolean; } { this.requireLayer(); const{ mem, fn} = this.runtime; const sizePtr = mem.alloc(8); const statusPtr = mem.alloc(4); const changedPtr = mem.alloc(4); let deltaPtr: Ptr | null = null; try{ mem.poke(sizePtr, 'i32', 0); mem.poke(statusPtr, 'i32', -1); mem.poke(changedPtr, 'i32', 1); deltaPtr = reporting ? fn.EPDFLayer_SaveDeltaToOwnedBufferEx( this.session.requireDocPtr(), sizePtr, statusPtr, changedPtr, ) : fn.EPDFLayer_SaveDeltaToOwnedBuffer(this.session.requireDocPtr(), sizePtr, statusPtr); const status = Number(mem.peek(statusPtr, 'i32')); const size = Number(mem.peek(sizePtr, 'i32')); const changedSinceLoad = reporting ? Number(mem.peek(changedPtr, 'i32')) !== 0 : true; if (status !== 0){ throw layerSaveError(status); } if (!deltaPtr || size <= 0){ return{ bytes: new ArrayBuffer(0), size: 0, changedSinceLoad} ; } const bytes = mem.readBytes(deltaPtr, size); const buffer = new ArrayBuffer(bytes.byteLength); new Uint8Array(buffer).set(bytes); return{ bytes: buffer, size, changedSinceLoad} ; } finally{ if (deltaPtr) fn.EPDF_FreeBuffer(deltaPtr); mem.free(changedPtr); mem.free(statusPtr); mem.free(sizePtr); } } saveLayerArtifactToFile(path: string):{ path: string} { this.requireLayer(); const{ mem, fn} = this.runtime; const statusPtr = mem.alloc(4); const writer = this.runtime.fileWrite.toNodeFile(path); try{ mem.poke(statusPtr, 'i32', -1); const ok = fn.EPDFLayer_SaveLayerArtifact( this.session.requireDocPtr(), writer.ptr, statusPtr, ); const status = Number(mem.peek(statusPtr, 'i32')); if (!ok || status !== 0){ throw layerSaveError(status); } return{ path} ; } finally{ writer.close(); mem.free(statusPtr); } } saveStandaloneToBuffer(mode: PdfSaveMode):{ bytes: ArrayBuffer; size: number} { const{ mem, fn} = this.runtime; const sizePtr = mem.alloc(8); let pdfPtr: Ptr | null = null; try{ mem.poke(sizePtr, 'i32', 0); pdfPtr = fn.EPDF_SaveDocumentToOwnedBuffer( this.session.requireDocPtr(), pdfSaveModeFlags(mode), sizePtr, ); const size = Number(mem.peek(sizePtr, 'i32')); if (!pdfPtr || size <= 0){ throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save document'); } return{ bytes: readSavedBuffer(mem, pdfPtr, size), size} ; } finally{ if (pdfPtr) fn.EPDF_FreeBuffer(pdfPtr); mem.free(sizePtr); } } saveStandaloneToBufferEx(mode: PdfSaveMode):{ bytes: ArrayBuffer; size: number; unchangedSinceLoad: boolean; } { const{ mem, fn} = this.runtime; const sizePtr = mem.alloc(8); const statusPtr = mem.alloc(4); let pdfPtr: Ptr | null = null; try{ mem.poke(sizePtr, 'i32', 0); mem.poke(statusPtr, 'i32', 0); pdfPtr = fn.EPDF_SaveDocumentToOwnedBufferEx( this.session.requireDocPtr(), pdfSaveModeFlags(mode), 0, sizePtr, statusPtr, ); const status = Number(mem.peek(statusPtr, 'i32')); if (status === EPDF_SAVE_UNCHANGED_SINCE_LOAD){ return{ bytes: new ArrayBuffer(0), size: 0, unchangedSinceLoad: true} ; } const size = Number(mem.peek(sizePtr, 'i32')); if (!pdfPtr || size <= 0 || status !== EPDF_SAVE_WRITTEN){ throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save document'); } return{ bytes: readSavedBuffer(mem, pdfPtr, size), size, unchangedSinceLoad: false, } ; } finally{ if (pdfPtr) fn.EPDF_FreeBuffer(pdfPtr); mem.free(statusPtr); mem.free(sizePtr); } } saveStandaloneToFile(path: string, mode: PdfSaveMode):{ path: string} { const writer = this.runtime.fileWrite.toNodeFile(path); try{ const ok = this.runtime.fn.FPDF_SaveAsCopy( this.session.requireDocPtr(), writer.ptr, pdfSaveModeFlags(mode), ); if (!ok){ throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save document'); } return{ path} ; } finally{ writer.close(); } } saveStandaloneToFileEx(path: string, mode: PdfSaveMode):{ path: string; unchangedSinceLoad: boolean} { const{ mem, fn} = this.runtime; const writer = this.runtime.fileWrite.toNodeFile(path); const statusPtr = mem.alloc(4); try{ mem.poke(statusPtr, 'i32', 0); const ok = fn.EPDF_SaveAsCopyEx( this.session.requireDocPtr(), writer.ptr, pdfSaveModeFlags(mode), statusPtr, ); const status = Number(mem.peek(statusPtr, 'i32')); if (!ok || status === 0){ throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save document'); } return{ path, unchangedSinceLoad: status === EPDF_SAVE_UNCHANGED_SINCE_LOAD} ; } finally{ mem.free(statusPtr); writer.close(); } } private requireLayer(): void{ if (this.session.kind !== 'layer'){ throw new EngineError(EngineErrorCode.InvalidArg, 'document session is not a layer'); } } } DocumentSession [ClassDeclaration] (from packages/engine/services/src/document-session/DocumentSession.ts): export class DocumentSession{ private docPtr: Ptr | null = null; private closeDocument: (() => void) | null = null; private _kind: OpenedPdfDocumentKind | null = null; private _source: DocumentSource | null = null; private readonly _sessionId: string; private readonly recordsByObjectNumber = new Map(); private readonly recordsByIndex = new Map(); private fullyEnumerated = false; private cacheSeqCounter = 0; private editsSeqCounter = 0; private transaction: OpenTransaction | null = null; private unusableReason: string | null = null; private pages: PagePtrPool | null = null; residency: PageResidency | null = null; signedDocumentPolicy: SignedDocumentPolicy = 'protect'; password: string | null = null; persistLayerArtifact = true; private loadedSeq = 0; private plainSha256:{ loadedSeq: number; sha256: string} | null = null; pendingSigning: PendingSigning | null = null; lastCompletion: SigningCompletion | null = null; private drawings: DrawingIndex | null = null; constructor( private readonly runtime: PdfRuntimeModule, sessionId?: string, ){ this._sessionId = sessionId ?? generateSessionId(); } get sessionId(): string{ return this._sessionId; } get kind(): OpenedPdfDocumentKind | null{ return this._kind; } get source(): DocumentSource{ if (!this._source){ throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open'); } return this._source; } isOpen(): boolean{ return this.docPtr !== null; } open(bytes: Uint8Array, password: string | null = null): void{ this.openFromHandle(openFatMemoryDocument(this.runtime, bytes, password)); } openFromHandle(handle: OpenedPdfDocument): void{ if (this.docPtr){ handle.close(); throw new EngineError(EngineErrorCode.InvalidArg, 'document already open'); } this.docPtr = handle.docPtr; this.closeDocument = () => handle.close(); this._kind = handle.kind; this._source = handle.source; this.pages = new PagePtrPool(this.runtime, handle.docPtr, this.residency); this.parkedLoad = null; this.drawings = null; this.loadedSeq = this.editsSeqCounter; } hasUnsavedEdits(): boolean{ return this.editsSeqCounter !== this.loadedSeq; } cachedPlainSha256(): string | null{ return this.plainSha256 && this.plainSha256.loadedSeq === this.loadedSeq ? this.plainSha256.sha256 : null; } rememberPlainSha256(sha256: string): void{ this.plainSha256 ={ loadedSeq: this.loadedSeq, sha256} ; } install(handle: OpenedPdfDocument): void{ if (!this.docPtr){ handle.close(); throw new EngineError(EngineErrorCode.DocNotOpen, 'no document to replace'); } let firstError: unknown = null; try{ this.pages?.closeAll(); } catch (error){ firstError = error; } try{ this.closeDocument?.(); } catch (error){ firstError ??= error; } this.docPtr = handle.docPtr; this.closeDocument = () => handle.close(); this._kind = handle.kind; this._source = handle.source; this.pages = new PagePtrPool(this.runtime, handle.docPtr, this.residency); this.recordsByIndex.clear(); this.recordsByObjectNumber.clear(); this.fullyEnumerated = false; this.cacheSeqCounter++; this.editsSeqCounter++; this.loadedSeq = this.editsSeqCounter; this.pendingSigning = null; this.drawings = null; this.heldObjectNumbers.clear(); this.objectNumbersInUse = []; if (firstError) throw firstError; } versionRef(baseSha256: string): DocumentVersionRef{ return{ baseSha256, editsVersion: this.editsSeqCounter} ; } parkLocked(load: (password: string | null) => void): void{ if (this.docPtr){ throw new EngineError(EngineErrorCode.InvalidArg, 'document already open'); } this.parkedLoad = load; } isLocked(): boolean{ return this.docPtr === null && this.parkedLoad !== null; } unlockWith(password: string | null): void{ if (!this.parkedLoad){ throw new EngineError(EngineErrorCode.DocNotOpen, 'document session is not locked'); } this.parkedLoad(password); this.parkedLoad = null; } private parkedLoad: ((password: string | null) => void) | null = null; pageCount(): number{ return this.runtime.fn.FPDF_GetPageCount(this.requireDocPtr()); } ensureFullPageRegistry(): void{ if (this.fullyEnumerated) return; const{ fn} = this.runtime; const docPtr = this.requireDocPtr(); const count = fn.FPDF_GetPageCount(docPtr); for (let i = 0; i < count; i++){ if (this.recordsByIndex.has(i)) continue; const pageObjectNumber = fn.EPDFDoc_GetPageObjectNumberByIndex(docPtr, i); if (!isValidPageObjectNumber(pageObjectNumber)){ throw new EngineError( EngineErrorCode.MalformedPdf, `page at index ${ i} is a direct (non-indirect) PDF object; the engine requires every page to have a stable indirect object number`, { details:{ pageIndex: i, pageObjectNumber} } , ); } const record: PageRecord ={ pageObjectNumber, pageIndex: i} ; this.recordsByIndex.set(i, record); this.recordsByObjectNumber.set(pageObjectNumber, record); } this.fullyEnumerated = true; } recordByObjectNumber(pageObjectNumber: PageObjectNumber): PageRecord{ const cached = this.recordsByObjectNumber.get(pageObjectNumber); if (cached) return cached; this.ensureFullPageRegistry(); const found = this.recordsByObjectNumber.get(pageObjectNumber); if (!found){ throw new EngineError( EngineErrorCode.NotFound, `no page with object number ${ pageObjectNumber} `, ); } return found; } resolvePageRef(ref: PageRef): PageRecord{ return this.recordByObjectNumber(ref.objectNumber); } resolvePageRefs(refs: readonly PageRef[]): PageObjectNumber[]{ return refs.map((ref) => this.resolvePageRef(ref).pageObjectNumber); } allRecords(): PageRecord[]{ this.ensureFullPageRegistry(); return Array.from(this.recordsByIndex.entries()) .sort(([a], [b]) => a - b) .map(([, r]) => r); } refreshPageRegistry(): void{ this.recordsByIndex.clear(); this.recordsByObjectNumber.clear(); this.fullyEnumerated = false; this.ensureFullPageRegistry(); } cacheSeq(): number{ return this.cacheSeqCounter; } invalidateDerived(): void{ this.cacheSeqCounter++; } editsSeq(): number{ return this.editsSeqCounter; } noteEdit(): void{ this.editsSeqCounter++; } clearMissingCharacters(): void{ if (this.docPtr) this.runtime.fn.EPDFDoc_ClearMissingCharacters(this.docPtr); } missingCharacters(): string[]{ if (!this.docPtr) return []; const{ fn, mem} = this.runtime; const docPtr = this.docPtr; const characters: string[] = []; const count = fn.EPDFDoc_CountMissingCharacters(docPtr); for (let index = 0; index < count; index++){ const character = readUtf16String(mem, (buf, cap) => fn.EPDFDoc_GetMissingCharacter(docPtr, index, buf, cap), ); if (character) characters.push(character); } return characters; } inTransaction(): boolean{ return this.transaction !== null; } beginTransaction(opId: string): void{ const docPtr = this.requireDocPtr(); if (this.transaction){ throw new EngineError(EngineErrorCode.Unknown, 'a transaction is already open'); } if (!this.runtime.fn.EPDFLayer_BeginTransaction(docPtr)){ throw new EngineError(EngineErrorCode.Unknown, 'EPDFLayer_BeginTransaction refused'); } this.transaction ={ docPtr, opId, undoable: false} ; } writeStamp(): WriteStamp{ const{ opId, undoable} = this.requireTransaction(); return{ opId, undoable} ; } markUndoable(): void{ this.requireTransaction().undoable = true; } commitTransaction(): void{ const{ docPtr} = this.requireTransaction(); if (!this.runtime.fn.EPDFLayer_IsInTransaction(docPtr)){ throw new EngineError(EngineErrorCode.Unknown, 'the layer transaction is no longer open'); } const lastObjectNumber = this.runtime.fn.EPDFLayer_GetLastObjectNumber(docPtr); if (lastObjectNumber > OBJECT_NUMBER_CEILING){ throw new EngineError( EngineErrorCode.LayerFull, `the document would pass object number ${ OBJECT_NUMBER_CEILING} `, { details:{ lastObjectNumber} } , ); } this.transaction = null; let committed = false; try{ committed = this.runtime.fn.EPDFLayer_CommitTransaction(docPtr); } finally{ if (!committed) this.unusableReason = COMMIT_FAILED; } if (!committed) throw new EngineError(EngineErrorCode.DocNotOpen, COMMIT_FAILED); for (const objectNumber of this.objectNumbersInUse) this.heldObjectNumbers.delete(objectNumber); this.objectNumbersInUse = []; } abortTransaction(): void{ const{ docPtr} = this.requireTransaction(); this.transaction = null; this.objectNumbersInUse = []; let aborted = false; try{ aborted = this.runtime.fn.EPDFLayer_AbortTransaction(docPtr); } catch{ } this.drawings?.forget(); this.recordsByIndex.clear(); this.recordsByObjectNumber.clear(); this.fullyEnumerated = false; this.invalidateDerived(); if (!aborted) this.unusableReason = 'a layer transaction failed to abort'; } objectNumberAuthority: 'session' | 'caller' = 'session'; private readonly heldObjectNumbers = new Set(); private objectNumbersInUse: number[] = []; lastObjectNumber(): number{ return this.runtime.fn.EPDFLayer_GetLastObjectNumber(this.requireDocPtr()); } raiseLastObjectNumber(last: number): void{ if (!this.runtime.fn.EPDFLayer_RaiseLastObjectNumber(this.requireDocPtr(), last)){ throw new EngineError( EngineErrorCode.LayerFull, `the document would pass object number ${ last} `, { details:{ lastObjectNumber: this.lastObjectNumber()} } , ); } } reserveObjectNumbers(count: number): ObjectNumberRange{ if (this.objectNumberAuthority !== 'session'){ throw new EngineError( EngineErrorCode.InvalidArg, 'object numbers are handed out by the caller, not this session', ); } if (!Number.isInteger(count) || count < 1){ throw new EngineError(EngineErrorCode.InvalidArg, `cannot reserve ${ count} object numbers`, { details:{ field: 'count'} , } ); } const{ fn} = this.runtime; const docPtr = this.requireDocPtr(); const last = fn.EPDFLayer_GetLastObjectNumber(docPtr); if (last + count > OBJECT_NUMBER_ISSUE_LIMIT){ throw new EngineError(EngineErrorCode.LayerFull, 'no more object numbers to hand out', { details:{ lastObjectNumber: last} , } ); } if (!fn.EPDFLayer_RaiseLastObjectNumber(docPtr, last + count)){ throw new EngineError(EngineErrorCode.Unknown, 'EPDFLayer_RaiseLastObjectNumber refused'); } const range ={ first: last + 1, count} ; for (let i = 0; i < count; i++) this.heldObjectNumbers.add(range.first + i); return range; } claimObjectNumber(objectNumber: number): void{ if (!Number.isInteger(objectNumber) || objectNumber < 1){ throw new EngineError(EngineErrorCode.InvalidArg, `${ objectNumber} is not an object number`, { details:{ field: 'objectNumber'} , } ); } if (this.objectNumberAuthority === 'session' && !this.heldObjectNumbers.has(objectNumber)){ throw objectNumberUnavailable(objectNumber, 'not-held'); } if (this.objectNumbersInUse.includes(objectNumber)){ throw objectNumberUnavailable(objectNumber, 'taken'); } this.objectNumbersInUse.push(objectNumber); } assertUsable(): void{ if (this.unusableReason){ throw new EngineError( EngineErrorCode.DocNotOpen, `${ this.unusableReason} ; open the document again`, ); } } private requireTransaction(): OpenTransaction{ if (!this.transaction){ throw new EngineError(EngineErrorCode.Unknown, 'no transaction is open'); } return this.transaction; } pagePool(): PagePtrPool{ if (!this.pages){ throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open'); } return this.pages; } drawingIndex(): DrawingIndex{ if (!this.docPtr){ throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open'); } this.drawings ??= new DrawingIndex(); return this.drawings; } requireDocPtr(): Ptr{ if (!this.docPtr){ throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open'); } return this.docPtr; } retainUntilClose(dispose: () => void): void{ this.retained.push(dispose); } private readonly retained: Array<() => void> = []; close(): void{ let firstError: unknown = null; try{ this.pages?.closeAll(); } catch (error){ firstError = error; } finally{ this.pages = null; } if (this.pendingSigning?.saved.kind === 'file'){ try{ this.runtime.fileWrite.removeFile(this.pendingSigning.saved.path); } catch (error){ firstError ??= error; } } try{ this.closeDocument?.(); } catch (error){ firstError ??= error; } finally{ this.closeDocument = null; this.docPtr = null; this._kind = null; this._source = null; this.parkedLoad = null; this.pendingSigning = null; this.lastCompletion = null; this.drawings = null; this.transaction = null; this.recordsByIndex.clear(); this.recordsByObjectNumber.clear(); this.fullyEnumerated = false; } for (let i = this.retained.length - 1; i >= 0; i--){ try{ this.retained[i](); } catch (error){ firstError ??= error; } } this.retained.length = 0; if (firstError) throw firstError; } } EPDF_CHAR_GEOMETRY_LAYOUT [VariableDeclaration] (from packages/engine/services/src/runtime/memory/structs.ts): EPDF_CHAR_GEOMETRY_LAYOUT ={ bytes: 124, offsets:{ looseBox: 0, tightBox: 16, looseQuad: 32, tightQuad: 64, matrix: 96, flags: 120, } , flags:{ hasTightBox: 1 << 0, hasLooseQuad: 1 << 1, hasTightQuad: 1 << 2, upright: 1 << 3, space: 1 << 4, empty: 1 << 5, synthesized: 1 << 6, } , } as const FILE_SPACE [VariableDeclaration] (from packages/engine/services/src/features/changes/ChangeApplier.ts): FILE_SPACE: ChangeSpace ={ opInFileSpace: (op) => op, itemOut: (item) => item, } FontRegistrar [ClassDeclaration] (from packages/engine/services/src/features/fonts/FontRegistrar.ts): export class FontRegistrar{ private readonly fileHandles: PdfFileAccessHandle[] = []; private readonly identities = new Map(); private readonly programs = new Map< string, { sha256: string; format: FontFormat; postScriptName: string | null; served: boolean} >(); private fallbacks:{ key: string; tier: FallbackTier} [] = []; private readonly builtIn = new Set(); constructor( private readonly runtime: PdfRuntimeModule, private readonly ids: Map, ){ this.registerLastResort(); } private registerLastResort(): void{ const bytes = lastResortFontBytes(); const{ mem, fn} = this.runtime; const ptr = mem.alloc(bytes.byteLength); try{ mem.writeBytes(ptr, bytes); const id = fn.EPDFFont_RegisterMemFont64('', 0, -1, ptr, bytes.byteLength); if (id === 0 || !fn.EPDFFont_SetLastResortFont(id)){ throw new EngineError( EngineErrorCode.RuntimeUnavailable, 'the last-resort font did not register', ); } } finally{ mem.free(ptr); } } register( fontKey: string, familyName: string, weight: number, italic: number, bytes: Uint8Array, builtIn = false, ): void{ if (this.ids.has(fontKey)) return; if (bytes.byteLength === 0){ throw new EngineError(EngineErrorCode.InvalidArg, `empty font data: ${ fontKey} `); } const{ mem, fn} = this.runtime; const ptr = mem.alloc(bytes.byteLength); try{ mem.writeBytes(ptr, bytes); const id = fn.EPDFFont_RegisterMemFont64(familyName, weight, italic, ptr, bytes.byteLength); if (id === 0){ throw new EngineError( EngineErrorCode.InvalidArg, `font registration failed (unloadable or no glyphs): ${ fontKey} `, ); } this.ids.set(fontKey, id); this.identities.set(fontKey, this.readIdentity(id, { familyName, weight, italic} )); this.programs.set(fontKey, { ...this.readProgram(id), served: true} ); if (builtIn) this.builtIn.add(fontKey); } finally{ mem.free(ptr); } } registerFromNodeFile( fontKey: string, familyName: string, weight: number, italic: number, path: string, served = false, builtIn = false, ): void{ if (this.ids.has(fontKey)) return; const access = this.runtime.fileAccess.fromNodeFile(path); let id = 0; try{ id = this.runtime.fn.EPDFFont_RegisterFont(familyName, weight, italic, access.ptr); } catch (error){ access.close(); throw error; } if (id === 0){ access.close(); throw new EngineError( EngineErrorCode.InvalidArg, `font registration failed (unloadable or no glyphs): ${ fontKey} (${ path} )`, ); } this.ids.set(fontKey, id); this.identities.set(fontKey, this.readIdentity(id, { familyName, weight, italic} )); this.programs.set(fontKey, { ...this.readProgram(id), served} ); if (builtIn) this.builtIn.add(fontKey); this.fileHandles.push(access); } describe(fontKey: string): FontIdentityInfo{ const identity = this.identities.get(fontKey); if (!identity){ throw new EngineError( EngineErrorCode.InvalidArg, `font not registered on this thread: ${ fontKey} `, ); } return identity; } describeOrUndefined(fontKey: string): FontIdentityInfo | undefined{ return this.identities.get(fontKey); } keyForFace(family: string, weight: number, italic: boolean): string | undefined{ const wanted = familyKey(family); let best:{ key: string; score: number} | undefined; for (const [key, identity] of this.identities){ if (familyKey(identity.familyName) !== wanted) continue; const score = Math.abs(identity.weight - weight) + (identity.italic === italic ? 0 : 1000); if (!best || score < best.score) best ={ key, score} ; } return best?.key; } authorizeEditing(fontKey: string): FontIdentityInfo{ const id = this.requireId(fontKey); if (!this.runtime.fn.EPDFFont_AuthorizeEditing(id)){ throw new EngineError(EngineErrorCode.InvalidArg, `authorizeEditing failed: ${ fontKey} `); } const previous = this.describe(fontKey); const identity = this.readIdentity(id, { familyName: previous.familyName, weight: previous.weight, italic: previous.italic ? 1 : 0, } ); this.identities.set(fontKey, identity); return identity; } private readIdentity( id: number, given:{ familyName: string; weight: number; italic: number} , ): FontIdentityInfo{ const{ fn, mem} = this.runtime; const attempt = (read: () => T, fallback: T): T =>{ try{ return read(); } catch{ return fallback; } } ; return{ familyName: attempt( () => readUtf8String(mem, (buf, cap) => fn.EPDFFont_GetFamilyName(id, buf, cap)) ?? given.familyName, given.familyName, ), weight: attempt(() => fn.EPDFFont_GetWeight(id), given.weight || 400), italic: attempt(() => fn.EPDFFont_IsItalic(id), given.italic === 1), embeddingPermission: attempt( () => permissionFromCode(fn.EPDFFont_GetEmbeddingPermission(id)), 'installable' as const, ), editingAuthorized: attempt(() => fn.EPDFFont_IsEditingAuthorized(id), true), instanced: attempt(() => fn.EPDFFont_IsInstanced(id), false), } ; } registerStartup(specs: readonly StartupFontSpec[]): void{ for (const spec of specs){ const italic = spec.italic === undefined ? -1 : spec.italic ? 1 : 0; this.registerFromNodeFile( spec.key, spec.familyName ?? '', spec.weight ?? 0, italic, spec.path, spec.serve ?? false, spec.builtIn ?? false, ); if (spec.fallback){ this.addFallback(spec.key, spec.tier); } } } addFallback(fontKey: string, tier: FallbackTier = FALLBACK_TIERS.own): void{ const id = this.requireId(fontKey); if (!this.runtime.fn.EPDFFont_AddFallbackFont(id, tier)){ throw new EngineError(EngineErrorCode.InvalidArg, `addFallback failed: ${ fontKey} `); } const existing = this.fallbacks.find((fallback) => fallback.key === fontKey); if (existing) existing.tier = tier; else this.fallbacks.push({ key: fontKey, tier} ); } clearFallbacks(): void{ this.runtime.fn.EPDFFont_ClearFallbackFonts(); this.fallbacks = []; } fallbackKeys(): string[]{ return [...this.fallbacks] .sort((left, right) => left.tier - right.tier) .map((fallback) => fallback.key); } engineFontFacts(): EngineFontFacts[]{ const facts: EngineFontFacts[] = []; for (const [key, identity] of this.identities){ const program = this.programs.get(key); if (!program) continue; facts.push({ key, identity, postScriptName: program.postScriptName, format: program.format, sha256: program.sha256, served: program.served, builtIn: this.builtIn.has(key), } ); } return facts; } keyForId(id: number): string | undefined{ for (const [key, candidate] of this.ids){ if (candidate === id) return key; } return undefined; } programFor(sha256: string): |{ info():{ covers: CodePointRange[]; ascent: number; descent: number} ; bytes(): Uint8Array; } | undefined{ const key = [...this.programs].find(([, program]) => program.sha256 === sha256)?.[0]; if (key === undefined) return undefined; const id = this.requireId(key); const{ fn, mem} = this.runtime; return{ info: () =>{ const covers = readRanges(this.runtime, (out, capacity) => fn.EPDFFont_GetCoverage(id, out, capacity), ); const metrics = withScratchN(mem, [4, 4], ([ascent, descent]) => fn.EPDFFont_GetMetrics(id, ascent, descent) ?{ ascent: Number(mem.peek(ascent, 'f32')), descent: Number(mem.peek(descent, 'f32'))} :{ ascent: 0, descent: 0} , ); return{ covers, ascent: Math.round(metrics.ascent * 1000), descent: -Math.round(metrics.descent * 1000), } ; } , bytes: () =>{ const length = fn.EPDFFont_GetProgramData(id, NULL_PTR, 0); return withScratch(mem, Math.max(1, length), (out) =>{ fn.EPDFFont_GetProgramData(id, out, length); return mem.readBytes(out, length); } ); } , } ; } private readProgram(id: number):{ sha256: string; format: FontFormat; postScriptName: string | null; } { const{ fn, mem} = this.runtime; const sha256 = withScratch(mem, 32, (out) => fn.EPDFFont_GetProgramHash(id, out) ? Array.from(mem.readBytes(out, 32), (byte) => byte.toString(16).padStart(2, '0')).join('') : '', ); return{ sha256, format: fn.EPDFFont_GetProgramFormat(id) === 2 ? 'opentype' : 'truetype', postScriptName: readUtf8String(mem, (buf, cap) => fn.EPDFFont_GetPostScriptName(id, buf, cap)) || null, } ; } clear(): void{ this.runtime.fn.EPDFFont_ClearRegisteredFonts(); this.registerLastResort(); this.ids.clear(); this.identities.clear(); this.programs.clear(); this.fallbacks = []; this.builtIn.clear(); for (const access of this.fileHandles){ access.close(); } this.fileHandles.length = 0; } idFor(fontKey: string): number{ return this.requireId(fontKey); } private requireId(fontKey: string): number{ const id = this.ids.get(fontKey); if (id === undefined){ throw new EngineError( EngineErrorCode.InvalidArg, `font not registered on this thread: ${ fontKey} `, ); } return id; } } FormExporter [ClassDeclaration] (from packages/engine/services/src/features/forms/FormExporter.ts): export class FormExporter{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } export( selection: FormExportSelection, limits: BundleLimits, signal: AbortSignal, ): WireFormBundle{ throwIfAborted(signal); const form = new FormReader(this.runtime, this.session, this.fonts).snapshot(signal); const snapshot = pageFormSnapshotOf(form, visibleBoxReader(this.runtime, this.session)); const{ fields, widgets, calculationOrder} = formExportRowsOf( snapshot, selection, this.session.allRecords().map((record) => toPageRef(record.pageObjectNumber)), ); assertWithinLimit('form', limits, 'items', fields.length + widgets.length); const rows ={ pages: bundlePagesOf(this.runtime, this.session, widgets), fields: fields.map((data) => ({ data} )), widgets: widgets.map((data) => ({ data, resources:{ } } )), calculationOrder, } ; assertWithinLimit('form', limits, 'pages', rows.pages.length); const manifestBytes = manifestBytesOf(rows); assertWithinLimit('form', limits, 'manifestBytes', manifestBytes); assertWithinLimit('form', limits, 'bundleBytes', manifestBytes); return{ format: 'embedpdf/form', version: 1, ...rows, resources:{ } } ; } } FormImporter [ClassDeclaration] (from packages/engine/services/src/features/forms/FormImporter.ts): export class FormImporter{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } import(request: FormImportRequest, signal: AbortSignal): FormImportResult{ throwIfAborted(signal); const{ bundle} = request; checkWireBundle(this.runtime, 'form', bundle, request.limits, assertFormBundleManifest); const names = this.fieldNames(); const plan = planFormImport({ bundle, ...(request.pages !== undefined ?{ pages: request.pages} :{ } ), target: this.session.allRecords().map((record) => ({ page: toPageRef(record.pageObjectNumber), position: record.pageIndex, } )), nameTaken: (name) => fieldNameTaken(names, name), mayScript: request.mayScript, values: request.values, } ); const docPtr = this.session.requireDocPtr(); const importedBy = request.actor.userId ?? null; const restores = request.attribution === 'restore'; const made = createPlannedFields( this.runtime, this.session, this.fonts, plan.creates, plan.calculationOrder, { actor: request.actor, groupOf: request.groupOf, signal, made: (objectNumber, at) =>{ if (!restores) return; const planned = plan.creates[at]!; const source = bundle.fields[planned.field]!.data; restoreFieldCreation(this.runtime, docPtr, objectNumber, source, importedBy); if (planned.value){ restoreFieldFill(this.runtime, docPtr, objectNumber, source, importedBy); } } , } , ); return{ ...made, refMap: plan.creates.map((planned, at) => ({ from: bundle.fields[planned.field]!.data.ref, to: made.fields[at]!.ref, } )), dropped: [...plan.dropped], } ; } planValues( bundle: WireFormBundle, limits: BundleLimits, signal: AbortSignal, mayFill: (field: FormField) => boolean, ): FormValuesImportPlan{ throwIfAborted(signal); checkWireBundle(this.runtime, 'form', bundle, limits, assertFormBundleManifest); const locks = readFieldLocks(this.runtime, this.session); const plan = planFormValuesImport({ bundle, target: this.readFields(), refusal: (field, value) =>{ if (field.ref.kind !== 'objectNumber') return 'value-not-allowed'; try{ fieldValueWriteOf(field, value); } catch (error){ if (EngineError.is(error)) return 'value-not-allowed'; throw error; } if (locks?.(field.name)) return 'locked'; return mayFill(field) ? null : 'fill-not-allowed'; } , } ); return{ writes: plan.writes.filter( ({ target, value} ) => !isNoOpWrite(target, fieldValueWriteOf(target, value)), ), dropped: plan.dropped, } ; } writeValue( write: PlannedValueWrite>, bundle: WireFormBundle, attribution: 'restore' | 'stamp', actor: AnnotationActor, signal: AbortSignal, ): FormField{ new FormMutator(this.runtime, this.session, this.fonts).setValue( write.target.ref, write.value, signal, actor, ); const objectNumber = objectNumberOf(write.target.ref); if (attribution === 'restore'){ restoreFieldFill( this.runtime, this.session.requireDocPtr(), objectNumber, bundle.fields[write.field]!.data, actor.userId ?? null, ); this.session.invalidateDerived(); } return this.readField(objectNumber); } private fieldNames(): Set{ const{ fn, mem} = this.runtime; const model = acquireFormModel(this.runtime, this.session); const names = new Set(); for (let index = 0; index < fn.EPDFForm_CountFields(model); index++){ const name = readUtf16String(mem, (buf, cap) => fn.EPDFForm_GetFieldName(model, index, buf, cap), ); if (name) names.add(name); } return names; } private readFields(): FormField[]{ const model = acquireFormModel(this.runtime, this.session); const docPtr = this.session.requireDocPtr(); const count = this.runtime.fn.EPDFForm_CountFields(model); return Array.from({ length: count} , (_, index) => readFieldAt(this.runtime, model, index, docPtr), ); } private readField(objectNumber: number): FormField{ const model = acquireFormModel(this.runtime, this.session); const index = this.runtime.fn.EPDFForm_GetFieldIndexByObjNum(model, objectNumber); return readFieldAt(this.runtime, model, index, this.session.requireDocPtr()); } } FormMutator [ClassDeclaration] (from packages/engine/services/src/features/forms/FormMutator.ts): export class FormMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } setValue( ref: FormFieldRef, value: FormFieldValue, signal: AbortSignal, actor: AnnotationActor, ): FieldWriteResult>{ throwIfAborted(signal); const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const docPtr = this.session.requireDocPtr(); const before = readFieldAt(this.runtime, model, resolved.fieldIndex, docPtr); const after = fieldAfterValue({ field: before, widgets: []} , value).field; const changed = this.writeFieldAfter(resolved.fieldObjectNumber, before, after); if (changed) stampFieldFill(this.runtime, docPtr, resolved.fieldObjectNumber, actor); return this.readBack(resolved.fieldObjectNumber, changed ?? []); } setDisplay( ref: FormFieldRef, display: FormFieldDisplay, signal: AbortSignal, ): FieldWriteResult>{ throwIfAborted(signal); const resolved = resolveFieldRef( this.runtime, acquireFormModel(this.runtime, this.session), ref, ); this.assertWritable(resolved); const docPtr = this.session.requireDocPtr(); const changed = this.withChangedWidgets((buf, cap, countPtr) => this.runtime.fn.EPDFForm_SetFieldDisplay( docPtr, resolved.fieldObjectNumber, DISPLAY_CODE[display], buf, cap, countPtr, ), ); if (changed === null){ throw new EngineError(EngineErrorCode.Unknown, 'the field could not be shown or hidden'); } return this.readBack(resolved.fieldObjectNumber, changed, false); } setAppearanceText( ref: FormFieldRef, text: string, signal: AbortSignal, ): FieldWriteResult>{ throwIfAborted(signal); const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const docPtr = this.session.requireDocPtr(); const field = readFieldAt(this.runtime, model, resolved.fieldIndex, docPtr); if (field.kind !== 'text' && field.kind !== 'combobox'){ throw new EngineError( EngineErrorCode.InvalidArg, `appearance text does not apply to a ${ field.kind} field`, ); } const changed = withUtf16String(this.runtime.mem, text, (textPtr) => this.withChangedWidgets((buf, cap, countPtr) => this.runtime.fn.EPDFForm_SetFieldAppearanceText( docPtr, resolved.fieldObjectNumber, textPtr, buf, cap, countPtr, ), ), ); if (changed === null){ throw new EngineError(EngineErrorCode.Unknown, 'the appearance text could not be drawn'); } return this.readBack(resolved.fieldObjectNumber, changed, true); } private emptyMeta(): MutationMeta{ return{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} ; } reset( refs: FormFieldRef[] | undefined, signal: AbortSignal, ): FieldWriteResult>{ throwIfAborted(signal); const docPtr = this.session.requireDocPtr(); const model = acquireFormModel(this.runtime, this.session); const targets = refs === undefined ? this.wholeFormTargets(model) : this.namedTargets(model, refs); throwIfAborted(signal); const written = targets .filter((field) => !isAtDefault(field)) .flatMap((before) =>{ const after = fieldAfterReset({ field: before, widgets: []} ).field; const changed = this.writeFieldAfter(fieldObjectNumberOf(before), before, after); if (!changed) return []; clearFieldFill(this.runtime, docPtr, fieldObjectNumberOf(before)); return [{ before, changed} ]; } ); if (written.length > 0) this.session.invalidateDerived(); const fields: FormField[] = []; const changedWidgets: FormWidget[] = []; const redrawnWidgets: FormWidget[] = []; for (const{ before, changed} of written){ const after = this.readBackField(fieldObjectNumberOf(before)); if (changed.length === 0 && valueEntriesEqual(before.valueEntry, after.valueEntry)) continue; fields.push(after); const changedSet = new Set(changed); const fieldWidgets = after.widgets .filter((widget) => changedSet.has(widget.objectNumber)) .map((widget) => formWidget(widget.objectNumber, widget.page)); changedWidgets.push(...fieldWidgets); redrawnWidgets.push(...redrawnByValue(after.kind, fieldWidgets)); } return{ fields, meta: formMutationMeta( this.session.writeStamp(), fields.map((field) => field.ref), changedWidgets, redrawnWidgets, ), } ; } private wholeFormTargets(model: Ptr): FormField[]{ const docPtr = this.session.requireDocPtr(); const locks = readFieldLocks(this.runtime, this.session); const targets: FormField[] = []; const count = this.runtime.fn.EPDFForm_CountFields(model); for (let index = 0; index < count; index++){ const field = readFieldAt(this.runtime, model, index, docPtr); if (!VALUE_FAMILIES.has(field.kind) || field.ref.kind !== 'objectNumber') continue; if (locks?.(field.name)) continue; targets.push(field); } return targets; } private namedTargets(model: Ptr, refs: FormFieldRef[]): FormField[]{ const docPtr = this.session.requireDocPtr(); const seen = new Set(); const targets: FormField[] = []; for (const ref of refs){ const resolved = resolveFieldRef(this.runtime, model, ref); const field = readFieldAt(this.runtime, model, resolved.fieldIndex, docPtr); if (!VALUE_FAMILIES.has(field.kind) || seen.has(resolved.fieldObjectNumber)) continue; this.assertWritable(resolved); seen.add(resolved.fieldObjectNumber); targets.push(field); } return targets; } repair(bakeAppearances: boolean, signal: AbortSignal): FormRepairResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const flags = bakeAppearances ? REPAIR_BAKE_APPEARANCES : 0; const report = withScratch(mem, 24, (reportPtr) =>{ const ok = fn.EPDFForm_Repair(this.session.requireDocPtr(), flags, reportPtr); if (!ok){ throw new EngineError(EngineErrorCode.Unknown, 'form repair failed'); } return{ acroformCreated: Number(mem.peek(reportPtr, 'i32', 0)) !== 0, fieldsLinked: Number(mem.peek(reportPtr, 'i32', 4)), widgetsLinked: Number(mem.peek(reportPtr, 'i32', 8)), fieldsUnrepairable: Number(mem.peek(reportPtr, 'i32', 12)), appearancesBaked: Number(mem.peek(reportPtr, 'i32', 16)), needsAppearancesCleared: Number(mem.peek(reportPtr, 'i32', 20)) !== 0, } ; } ); this.session.invalidateDerived(); return{ ...report, meta: this.emptyMeta()} ; } createField( draft: FormFieldDraft, signal: AbortSignal, actor: AnnotationActor, numbers:{ readonly objectNumber?: number; readonly widgetObjectNumbers?: readonly number[]; } ={ } , ):{ field: FormField; calculationOrder: OrderChange | null} { throwIfAborted(signal); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const placements = (draft.widgets ?? []).map((placement) => placedWidgetOf(fitWidgetToFamily(draft.kind, placement)), ); const pageIndexes = placements.map((placement) => this.preflightPlacement(placement)); const onStates = placements.map((placement) => onStateOf(draft.kind, placement)); defaultEntryOfDraft(draft); if ('maxLength' in draft && draft.maxLength !== undefined){ if (!Number.isInteger(draft.maxLength) || draft.maxLength <= 0){ throw new EngineError( EngineErrorCode.InvalidArg, `maxLength must be a positive integer, got ${ draft.maxLength} `, { details:{ field: 'maxLength'} } , ); } } const{ objectNumber, widgetObjectNumbers} = numbers; if (widgetObjectNumbers && widgetObjectNumbers.length !== placements.length){ throw new EngineError( EngineErrorCode.InvalidArg, `forms.create needs one widget object number per widget: ${ widgetObjectNumbers.length} for ${ placements.length} `, { details:{ field: 'widgetObjectNumbers'} } , ); } if (objectNumber !== undefined) this.session.claimObjectNumber(objectNumber); for (const number of widgetObjectNumbers ?? []) this.session.claimObjectNumber(number); throwIfAborted(signal); const fieldObjectNumber = this.createFieldNode(draft, objectNumber); this.configureNewField(draft, fieldObjectNumber); stampFieldCreation(this.runtime, docPtr, fieldObjectNumber, actor); if (draft.groupId !== undefined){ writeFieldGroup(this.runtime, docPtr, fieldObjectNumber, draft.groupId); } placements.forEach((placement, at) =>{ const widgetObjectNumber = createUnattachedWidget( this.runtime, docPtr, pageIndexes[at]!, placement, widgetObjectNumbers?.[at], fontWriteContext(this.runtime, this.session, this.fonts), ); if ( !fn.EPDFForm_AttachWidget(docPtr, fieldObjectNumber, widgetObjectNumber, onStates[at]!, 0) ){ throw new EngineError(EngineErrorCode.Unknown, 'widget adoption failed'); } } ); const calculationOrder = this.followCalculateScript( fieldObjectNumber, draft.actions?.calculate, ); this.session.invalidateDerived(); return{ field: this.readBackField(fieldObjectNumber), calculationOrder} ; } private nativeDeleteField(fieldObjectNumber: number): boolean{ const{ fn, mem} = this.runtime; return withScratchN(mem, [256 * 4, U64_BYTES], ([buf, countPtr]) =>{ pokeU64(mem, countPtr, 0); return fn.EPDFForm_DeleteField( this.session.requireDocPtr(), fieldObjectNumber, buf, 256, countPtr, ); } ); } private preflightPlacement(placement: PlacedWidget): number{ const record = this.session.resolvePageRef(placement.page); const{ left, bottom, right, top} = placement.rect; if (![left, bottom, right, top].every(Number.isFinite)){ throw new EngineError(EngineErrorCode.InvalidArg, 'widget rect must be finite numbers', { details:{ field: 'rect'} , } ); } return record.pageIndex; } private createFieldNode(draft: FormFieldDraft, objectNumber?: number): number{ const{ fn, mem} = this.runtime; const namePtr = mem.writeU16String(draft.name); let fieldObjectNumber: number; try{ fieldObjectNumber = fn.EPDFForm_CreateField( this.session.requireDocPtr(), FAMILY_CODE[draft.kind], namePtr, objectNumber ?? 0, ); } finally{ mem.free(namePtr); } if (fieldObjectNumber <= 0){ throw new EngineError( EngineErrorCode.InvalidArg, `cannot create field "${ draft.name} " (name conflict or invalid)`, ); } return fieldObjectNumber; } private configureNewField( draft: FormFieldDraft, fieldObjectNumber: number, ): void{ const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const{ setBits, clearBits} = flagMasks( draft as unknown as Record, ); if (setBits !== 0 || clearBits !== 0){ fn.EPDFForm_SetFieldFlags(docPtr, fieldObjectNumber, setBits, clearBits); } if ('options' in draft && draft.options){ this.applyOptions(fieldObjectNumber, draft.options); } this.writeDefault(fieldObjectNumber, { kind: 'none'} , defaultEntryOfDraft(draft)); if ('maxLength' in draft && draft.maxLength !== undefined){ if (!fn.EPDFForm_SetFieldMaxLen(docPtr, fieldObjectNumber, draft.maxLength)){ throw new EngineError(EngineErrorCode.InvalidArg, 'maxLength rejected'); } } if (draft.alternateName !== undefined){ this.applyWideSetter( fn.EPDFForm_SetFieldAlternateName, fieldObjectNumber, draft.alternateName, 'alternate name rejected', ); } if (draft.mappingName !== undefined){ this.applyWideSetter( fn.EPDFForm_SetFieldMappingName, fieldObjectNumber, draft.mappingName, 'mapping name rejected', ); } if (draft.actions){ writeFieldScripts(this.runtime, docPtr, fieldObjectNumber, undefined, draft.actions); } } setSignatureAppearance( ref: FormFieldRef, pdf: Uint8Array, signal: AbortSignal, ):{ field: FormField} { throwIfAborted(signal); const docPtr = this.session.requireDocPtr(); const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const before = readFieldAt(this.runtime, model, resolved.fieldIndex, docPtr); if (before.kind !== 'signature'){ throw new EngineError( EngineErrorCode.InvalidArg, `'${ before.name} ' is a ${ before.kind} field, not a signature field`, ); } const signed = withSignatureModel(this.runtime, docPtr, (signatures) => readSignaturesFromModel(this.runtime, signatures).some( (s) => s.signed && s.field.kind === 'objectNumber' && s.field.objectNumber === resolved.fieldObjectNumber, ), ); if (signed){ throw new EngineError( EngineErrorCode.ProtectedDocument, `'${ before.name} ' is signed; its appearance is sealed with the signature`, ); } if (before.widgets.length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, `'${ before.name} ' has no widget to draw into`, ); } for (const widget of before.widgets){ bakeWidgetAppearance(this.runtime, docPtr, widget, pdf, { recordFit: true} ); } this.session.invalidateDerived(); return{ field: this.readBackField(resolved.fieldObjectNumber)} ; } updateField( ref: FormFieldRef, patch: FormFieldPatch, signal: AbortSignal, ):{ field: FormField; calculationOrder: OrderChange | null} { throwIfAborted(signal); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const before = readFieldAt( this.runtime, model, resolved.fieldIndex, this.session.requireDocPtr(), ); assertPatchFitsFamily(patch, before.kind); if ('defaultValue' in patch && patch.defaultValue !== undefined){ formFieldAfter({ field: before, widgets: []} , patch); } const fieldObjectNumber = resolved.fieldObjectNumber; if (patch.name !== undefined){ this.applyWideSetter( fn.EPDFForm_SetFieldName, fieldObjectNumber, patch.name, `cannot rename to "${ patch.name} " (sibling conflict or invalid)`, ); } const{ setBits, clearBits} = flagMasks( patch as unknown as Record, ); if (setBits !== 0 || clearBits !== 0){ if (!fn.EPDFForm_SetFieldFlags(docPtr, fieldObjectNumber, setBits, clearBits)){ throw new EngineError(EngineErrorCode.InvalidArg, 'flag update rejected'); } } if ('maxLength' in patch && patch.maxLength !== undefined){ if (!fn.EPDFForm_SetFieldMaxLen(docPtr, fieldObjectNumber, patch.maxLength ?? 0)){ throw new EngineError( EngineErrorCode.InvalidArg, 'maxLength rejected (current value exceeds it)', ); } } if (patch.alternateName !== undefined){ this.applyWideSetter( fn.EPDFForm_SetFieldAlternateName, fieldObjectNumber, patch.alternateName ?? '', 'alternate name rejected', ); } if (patch.mappingName !== undefined){ this.applyWideSetter( fn.EPDFForm_SetFieldMappingName, fieldObjectNumber, patch.mappingName ?? '', 'mapping name rejected', ); } if (patch.groupId !== undefined && patch.groupId !== before.groupId){ writeFieldGroup(this.runtime, docPtr, fieldObjectNumber, patch.groupId); } const newOptions = 'options' in patch && patch.options !== undefined; const newDefault = 'defaultValue' in patch && patch.defaultValue !== undefined; if (newOptions || newDefault){ const after = formFieldAfter({ field: before, widgets: []} , patch).field; if ('options' in patch && patch.options) this.applyOptions(fieldObjectNumber, patch.options); this.writeDefault(fieldObjectNumber, before.defaultValueEntry, after.defaultValueEntry); if (newOptions) this.writeFieldAfter(fieldObjectNumber, before, after, true); } if (patch.actions){ writeFieldScripts(this.runtime, docPtr, fieldObjectNumber, before.actions, patch.actions); } const calculationOrder = this.followCalculateScript( fieldObjectNumber, patch.actions?.calculate, ); this.session.invalidateDerived(); return{ field: this.readBackField(fieldObjectNumber), calculationOrder} ; } reorderCalculations( fields: readonly FormFieldRef[], position: FieldPosition, signal: AbortSignal, ): OrderChange &{ moved: number[]} { throwIfAborted(signal); const model = acquireFormModel(this.runtime, this.session); const numberOf = (ref: FormFieldRef) => resolveFieldRef(this.runtime, model, ref).fieldObjectNumber; const before = readCalculationOrder(this.runtime, model); const moved = fields.map(numberOf); const at: ListPosition = position === 'start' || position === 'end' ? position : 'before' in position ?{ before: numberOf(position.before)} :{ after: numberOf(position.after)} ; const after = reorderedList(before, moved, at, String); throwIfAborted(signal); if (!sameOrder(before, after)){ writeCalculationOrder(this.runtime, this.session.requireDocPtr(), after); this.session.invalidateDerived(); } return{ before, after, moved} ; } private followCalculateScript( fieldObjectNumber: number, calculate: FieldScriptWrite | null | undefined, ): OrderChange | null{ if (calculate === undefined) return null; const before = readCalculationOrder(this.runtime, acquireFormModel(this.runtime, this.session)); const listed = before.includes(fieldObjectNumber); const after = calculate === null ? before.filter((objectNumber) => objectNumber !== fieldObjectNumber) : listed ? before : [...before, fieldObjectNumber]; if (sameOrder(before, after)) return null; writeCalculationOrder(this.runtime, this.session.requireDocPtr(), after); return{ before, after} ; } deleteField( ref: FormFieldRef, signal: AbortSignal, ):{ deleted: FormFieldRef; removedWidgets: FormWidget[]; calculationOrder: OrderChange | null; } { throwIfAborted(signal); const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const before = readFieldAt( this.runtime, model, resolved.fieldIndex, this.session.requireDocPtr(), ); const removedWidgets = before.widgets.map((w) => formWidget(w.objectNumber, w.page)); throwIfAborted(signal); const calculationOrder = this.followCalculateScript(resolved.fieldObjectNumber, null); if (!this.nativeDeleteField(resolved.fieldObjectNumber)){ throw new EngineError(EngineErrorCode.InvalidArg, 'field cannot be deleted'); } this.session.invalidateDerived(); const annotations = new AnnotationMutator(this.runtime, this.session); for (const widget of removedWidgets){ if (!widget.ref) continue; annotations.deleteReleasedWidget(widget.ref, resolved.fieldObjectNumber); } this.session.invalidateDerived(); return{ deleted: before.ref, removedWidgets, calculationOrder} ; } addWidget( ref: FormFieldRef, placement: WidgetPlacement, signal: AbortSignal, numbers:{ readonly objectNumber?: number; readonly splitObjectNumber?: number; } ={ } , ):{ field: FormField; widget: FormWidget} { throwIfAborted(signal); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const before = readFieldAt(this.runtime, model, resolved.fieldIndex, docPtr); const fitted = placedWidgetOf(fitWidgetToFamily(before.kind, placement)); const pageIndex = this.preflightPlacement(fitted); const onState = onStateOf(before.kind, fitted); const mergedPage = before.widgets.find((w) => w.objectNumber === resolved.fieldObjectNumber)?.page ?? null; if (numbers.objectNumber !== undefined) this.session.claimObjectNumber(numbers.objectNumber); const splitObjectNumber = mergedPage ? numbers.splitObjectNumber : undefined; if (splitObjectNumber !== undefined) this.session.claimObjectNumber(splitObjectNumber); throwIfAborted(signal); if (mergedPage) promoteInlineAnnotations(this.runtime, this.session, mergedPage.objectNumber); const widgetObjectNumber = createUnattachedWidget( this.runtime, docPtr, pageIndex, fitted, numbers.objectNumber, fontWriteContext(this.runtime, this.session, this.fonts), ); if ( !fn.EPDFForm_AttachWidget( docPtr, resolved.fieldObjectNumber, widgetObjectNumber, onState, splitObjectNumber ?? 0, ) ){ throw new EngineError(EngineErrorCode.InvalidArg, 'the widget could not join the field'); } this.session.invalidateDerived(); return{ field: this.readBackField(resolved.fieldObjectNumber), widget: formWidget(widgetObjectNumber, placement.page), } ; } detachWidget( ref: FormFieldRef, widget: AnnotationRef, signal: AbortSignal, ):{ field: FormField; widget: FormWidget} { throwIfAborted(signal); const{ fn} = this.runtime; const model = acquireFormModel(this.runtime, this.session); const resolved = resolveFieldRef(this.runtime, model, ref); this.assertWritable(resolved); const widgetNumber = widgetObjectNumber(widget); if (widgetNumber === resolved.fieldObjectNumber){ throw new EngineError( EngineErrorCode.InvalidArg, `widget ${ widgetNumber} is the field's own dictionary (a merged field/widget) and cannot be removed from it - delete the field with doc.forms.delete`, ); } if ( !fn.EPDFForm_DetachWidget( this.session.requireDocPtr(), resolved.fieldObjectNumber, widgetNumber, ) ){ throw new EngineError(EngineErrorCode.InvalidArg, 'widget is not attached to this field'); } this.session.invalidateDerived(); return{ field: this.readBackField(resolved.fieldObjectNumber), widget: formWidget(widgetObjectNumber(widget), widget.page), } ; } private applyOptions( fieldObjectNumber: number, options: ReadonlyArray<{ label: string; value: string} >, ): void{ const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const ok = withWideStringArray( this.runtime, options.map((o) => o.label), (labelsPtr) => withWideStringArray( this.runtime, options.map((o) => o.value), (exportsPtr, count) => fn.EPDFForm_SetFieldOptions(docPtr, fieldObjectNumber, labelsPtr, exportsPtr, count), ), ); if (!ok){ throw new EngineError(EngineErrorCode.InvalidArg, 'options rejected'); } } private applyWideSetter( setter: (docPtr: Ptr, fieldObjectNumber: number, valuePtr: Ptr) => boolean, fieldObjectNumber: number, value: string, errorMessage: string, ): void{ const{ mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const valuePtr = mem.writeU16String(value); try{ if (!setter(docPtr, fieldObjectNumber, valuePtr)){ throw new EngineError(EngineErrorCode.InvalidArg, errorMessage); } } finally{ mem.free(valuePtr); } } private writeDefault( fieldObjectNumber: number, before: FormValueEntry, after: FormValueEntry, ): void{ if (valueEntriesEqual(before, after)) return; const docPtr = this.session.requireDocPtr(); if (!writeFieldEntry(this.runtime, docPtr, fieldObjectNumber, after, 'default')){ throw new EngineError(EngineErrorCode.InvalidArg, 'default value rejected'); } } private readBackField(fieldObjectNumber: number): FormField{ const fresh = acquireFormModel(this.runtime, this.session); const fieldIndex = this.runtime.fn.EPDFForm_GetFieldIndexByObjNum(fresh, fieldObjectNumber); if (fieldIndex < 0){ throw new EngineError(EngineErrorCode.Unknown, 'form field vanished after write'); } return readFieldAt(this.runtime, fresh, fieldIndex, this.session.requireDocPtr()); } private assertWritable(resolved: ResolvedField): void{ if (resolved.fieldObjectNumber === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'form field is stored as a direct object and cannot be written', ); } this.assertNotLockedBySignature(resolved); } private assertNotLockedBySignature(resolved: ResolvedField): void{ const locks = readFieldLocks(this.runtime, this.session); if (!locks) return; const model = acquireFormModel(this.runtime, this.session); const name = readUtf16String(this.runtime.mem, (buf, cap) => this.runtime.fn.EPDFForm_GetFieldName(model, resolved.fieldIndex, buf, cap), ) ?? ''; assertFieldNotLocked(name, locks); } private writeFieldAfter( fieldObjectNumber: number, before: FormField, after: FormField, redraw = false, ): number[] | null{ const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const toggles = after.kind === 'checkbox' || after.kind === 'radio' ? after.widgets : null; const valueChanges = !valueEntriesEqual(before.valueEntry, after.valueEntry); const statesChange = toggles?.some( (widget, at) => widget.checked !== (before.widgets[at] as ToggleFieldWidget)?.checked, ) ?? false; if (!valueChanges && !statesChange && !redraw) return null; const refused = () => new EngineError(EngineErrorCode.InvalidArg, `'${ after.name} ' could not take the value`); if ( valueChanges && !writeFieldEntry(this.runtime, docPtr, fieldObjectNumber, after.valueEntry, 'value') ){ throw refused(); } if (after.kind === 'combobox' || after.kind === 'listbox'){ const selected = after.options.flatMap((option, at) => (option.selected ? [at] : [])); if (!writeSelectedIndices(this.runtime, docPtr, fieldObjectNumber, selected)){ throw refused(); } } if (toggles?.length === 0) return []; const changed = this.withChangedWidgets((buf, cap, countPtr) => toggles ? withI32Array( mem, toggles.map((widget) => (widget.checked ? 1 : 0)), (checkedPtr, count) => fn.EPDFForm_SetFieldWidgetsChecked( docPtr, fieldObjectNumber, checkedPtr, count, buf, cap, countPtr, ), ) : fn.EPDFForm_RedrawFieldWidgets(docPtr, fieldObjectNumber, buf, cap, countPtr), ); if (changed === null) throw refused(); return changed; } private withChangedWidgets( call: (buf: Ptr, cap: number, countPtr: Ptr) => boolean, ): number[] | null{ const{ mem} = this.runtime; return withScratchN(mem, [CHANGED_WIDGETS_CAPACITY * 4, U64_BYTES], ([buf, countPtr]) =>{ pokeU64(mem, countPtr, 0); if (!call(buf, CHANGED_WIDGETS_CAPACITY, countPtr)){ return null; } const total = Number(mem.peek(countPtr, 'i32')); const reported = Math.min(total, CHANGED_WIDGETS_CAPACITY); const changed: number[] = []; for (let i = 0; i < reported; i++){ changed.push(Number(mem.peek(buf, 'i32', i * 4))); } return changed; } ); } private readBack( fieldObjectNumber: number, changedObjNums: number[], redraws?: boolean, ): FieldWriteResult>{ this.session.invalidateDerived(); const fresh = acquireFormModel(this.runtime, this.session); const fieldIndex = this.runtime.fn.EPDFForm_GetFieldIndexByObjNum(fresh, fieldObjectNumber); if (fieldIndex < 0){ throw new EngineError(EngineErrorCode.Unknown, 'form field vanished after write'); } const field: FormField = readFieldAt( this.runtime, fresh, fieldIndex, this.session.requireDocPtr(), ); const changedSet = new Set(changedObjNums); const changedWidgets: FormWidget[] = field.widgets .filter((w) => changedSet.has(w.objectNumber)) .map((w) => formWidget(w.objectNumber, w.page)); return{ field, meta: formMutationMeta( this.session.writeStamp(), [field.ref], changedWidgets, redraws === undefined ? redrawnByValue(field.kind, changedWidgets) : redraws ? changedWidgets : [], ), } ; } } FormReader [ClassDeclaration] (from packages/engine/services/src/features/forms/FormReader.ts): export class FormReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } snapshot(signal: AbortSignal): FormSnapshot{ throwIfAborted(signal); return readForm(this.runtime, this.session, signal, this.fonts); } field(ref: FormFieldRef, signal: AbortSignal): FormField{ throwIfAborted(signal); const model = acquireFormModel(this.runtime, this.session); const{ fieldIndex} = resolveFieldRef(this.runtime, model, ref); return readFieldAt(this.runtime, model, fieldIndex, this.session.requireDocPtr()); } } KeptResult [TypeAliasDeclaration] (from packages/engine/services/src/features/changes/ChangeLedger.ts): export type KeptResult = ChangeResult | ChangeResult; LayerSource [TypeAliasDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export type LayerSource = |{ readonly kind: 'fresh'} |{ readonly kind: 'raw-delta'; readonly bytes: Uint8Array | ArrayBuffer} |{ readonly kind: 'artifact'; readonly bytes: Uint8Array | ArrayBuffer} |{ readonly kind: 'artifact-file'; readonly path: string} ; MetadataMutator [ClassDeclaration] (from packages/engine/services/src/features/metadata/MetadataMutator.ts): export class MetadataMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } update(patch: MetadataPatch, signal: AbortSignal): MetadataUpdateResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); applyMetadataPatch(fn, mem, docPtr, patch); syncXmp(fn, mem, docPtr, xmpEditsForMetadata(patch)); throwIfAborted(signal); const metadata = new MetadataReader(this.runtime, this.session).read(signal); return{ metadata, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } updateCustom(patch: CustomMetadataPatch, signal: AbortSignal): CustomMetadataUpdateResult{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); applyCustomMetadataPatch(fn, mem, docPtr, patch); syncXmp(fn, mem, docPtr, xmpEditsForCustomMetadata(patch)); throwIfAborted(signal); const custom = new MetadataReader(this.runtime, this.session).readCustom(signal); return{ custom, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } } MetadataReader [ClassDeclaration] (from packages/engine/services/src/features/metadata/MetadataReader.ts): export class MetadataReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } read(signal: AbortSignal): DocumentMetadata{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const doc = this.session.requireDocPtr(); const title = readMetaText(fn, mem, doc, 'Title'); throwIfAborted(signal); const author = readMetaText(fn, mem, doc, 'Author'); throwIfAborted(signal); const subject = readMetaText(fn, mem, doc, 'Subject'); throwIfAborted(signal); const keywords = readMetaText(fn, mem, doc, 'Keywords'); throwIfAborted(signal); const producer = readMetaText(fn, mem, doc, 'Producer'); throwIfAborted(signal); const creator = readMetaText(fn, mem, doc, 'Creator'); throwIfAborted(signal); const creationRaw = readMetaText(fn, mem, doc, 'CreationDate'); throwIfAborted(signal); const modRaw = readMetaText(fn, mem, doc, 'ModDate'); throwIfAborted(signal); const trapped = readTrapped(fn, doc); return{ title, author, subject, keywords, producer, creator, createdAt: creationRaw ? pdfDateToIso(creationRaw) : null, modifiedAt: modRaw ? pdfDateToIso(modRaw) : null, trapped, } ; } readCustom(signal: AbortSignal): CustomMetadata{ throwIfAborted(signal); const{ fn, mem} = this.runtime; return readAllCustomMeta(fn, mem, this.session.requireDocPtr()); } } OpenedPdfDocument [InterfaceDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export interface OpenedPdfDocument{ readonly kind: OpenedPdfDocumentKind; readonly docPtr: Ptr; readonly source: DocumentSource; close(): void; } OpenedPdfDocumentKind [TypeAliasDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export type OpenedPdfDocumentKind = 'fat-memory' | 'layer'; PackedChangeRecord [InterfaceDeclaration] (from packages/engine/services/src/features/changes/recordCodec.ts): export interface PackedChangeRecord{ readonly reverse: string; readonly capture: Uint8Array | null; } PageGeometryReader [ClassDeclaration] (from packages/engine/services/src/features/geometry/PageGeometryReader.ts): export class PageGeometryReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } async read( pageObjectNumber: PageObjectNumber, signal: AbortSignal, slices: Slices, ): Promise>{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const pool = this.session.pagePool(); const pagePtr = await pool.acquireInSlices(pageObjectNumber, signal, slices); try{ throwIfAborted(signal); const textPagePtr = fn.FPDFText_LoadPage(pagePtr); if (!textPagePtr){ throw new EngineError( EngineErrorCode.RuntimeUnavailable, `FPDFText_LoadPage returned null for page object ${ pageObjectNumber} `, ); } try{ throwIfAborted(signal); const glyphCount = Math.max(fn.FPDFText_CountChars(textPagePtr), 0); const records: RawGeometryGlyphRecord[] = []; const geometryPtr = mem.alloc(EPDF_CHAR_GEOMETRY_LAYOUT.bytes); try{ const timer = new SliceTimer(slices, signal); let prevObjectKey: number | bigint | null = null; for (let i = 0; i < glyphCount; i++){ if (timer.due) await timer.pause(); const objectKey = fn.FPDFText_GetTextObject(textPagePtr, i); const record: RawGeometryGlyphRecord ={ objectKey, ...this.readGlyphRaw(textPagePtr, i, geometryPtr), } ; if (objectKey !== prevObjectKey){ record.fontSize = fn.FPDFText_GetFontSize(textPagePtr, i); prevObjectKey = objectKey; } records.push(record); } } finally{ mem.free(geometryPtr); } return{ runs: buildRunsFromRawGlyphs(records)} ; } finally{ fn.FPDFText_ClosePage(textPagePtr); } } finally{ pool.release(pageObjectNumber); } } private readGlyphRaw( textPagePtr: Ptr, charIndex: number, geometryPtr: Ptr, ): Omit{ const{ fn, mem} = this.runtime; if (!fn.EPDFText_GetCharGeometry(textPagePtr, charIndex, geometryPtr)){ return emptyRawGlyph(); } const{ offsets, flags: bits} = EPDF_CHAR_GEOMETRY_LAYOUT; const native = readI32(mem, geometryPtr, offsets.flags) >>> 0; if (native & bits.empty){ return emptyRawGlyph(); } const upright = Boolean(native & bits.upright); const raw: Omit ={ flags: native & bits.space ? FLAG_SPACE : 0, looseBox: normalizePdfRect(readRectF(mem, geometryPtr, offsets.looseBox)), upright, baselineAngle: 0, ascentFlip: false, } ; if (native & bits.hasTightBox){ raw.tightBox = normalizePdfRect(readRectF(mem, geometryPtr, offsets.tightBox)); } if (native & bits.hasLooseQuad){ raw.looseQuad = readQuad(mem, geometryPtr, offsets.looseQuad); if (native & bits.hasTightQuad){ raw.tightQuad = readQuad(mem, geometryPtr, offsets.tightQuad); } if (!upright){ const a = readF32(mem, geometryPtr, offsets.matrix); const b = readF32(mem, geometryPtr, offsets.matrix + 4); const c = readF32(mem, geometryPtr, offsets.matrix + 8); const d = readF32(mem, geometryPtr, offsets.matrix + 12); raw.baselineAngle = Math.atan2(b, a); raw.ascentFlip = a * d - b * c < 0; } } return raw; } } PageLayoutReader [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesReader.ts): export class PagesReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } read(signal: AbortSignal): PageListSnapshot{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const records = this.session.allRecords(); const actionBudget = new ActionReadBudgetTracker(); const labels = readLabelSections(this.runtime, docPtr); return withScratchN( mem, [RECTF_BYTES, F32_BYTES, I32_BYTES], ([rectPtr, userUnitPtr, intPtr]) =>{ const pages: PageLayout[] = records.map((record) =>{ throwIfAborted(signal); const index = record.pageIndex; const actions = readPageActions(fn, mem, docPtr, record.pageObjectNumber, actionBudget); const viewports = readViewports(fn, mem, docPtr, index); const boxes = readBoxes(fn, mem, docPtr, index, rectPtr); return{ index, ref: toPageRef(record.pageObjectNumber), label: labelAt(labels, index), size: pdfRectSize(boxes.crop), rotation: readRotation(fn, mem, docPtr, index, intPtr), userUnit: readUserUnit(fn, mem, docPtr, index, userUnitPtr), tabOrder: readTabOrder(fn, mem, docPtr, index), boxes, pdfCropBox: boxes.crop, ...(actions ?{ actions} :{ } ), ...(viewports.length ?{ viewports} :{ } ), } ; } ); return{ pageCount: pages.length, pages, labels, namedPages: readNamedPages(fn, mem, docPtr), } ; } , ); } } PagePtrPool [ClassDeclaration] (from packages/engine/services/src/document-session/pages/PagePtrPool.ts): export class PagePtrPool{ private readonly residency: PageResidency; constructor( runtime: PdfRuntimeModule, private readonly docPtr: Ptr, residency: PageResidency | null = null, ){ this.residency = residency ?? new PageResidency(runtime, { budgetBytes: 0, idleMs: 0} ); } acquire(pageObjectNumber: PageObjectNumber): Ptr{ return this.residency.acquire(this, this.docPtr, pageObjectNumber); } acquireInSlices( pageObjectNumber: PageObjectNumber, signal: AbortSignal, slices: Slices, ): Promise{ return this.residency.acquireInSlices(this, this.docPtr, pageObjectNumber, signal, slices); } isHeld(pageObjectNumber: PageObjectNumber): boolean{ return this.residency.isHeld(this, pageObjectNumber); } isKept(pageObjectNumber: PageObjectNumber): boolean{ return this.residency.isKept(this, pageObjectNumber); } release(pageObjectNumber: PageObjectNumber): void{ this.residency.release(this, pageObjectNumber); } setWorkingSet( view: string, pages: Iterable<{ pageObjectNumber: PageObjectNumber} & Pick >, ): void{ this.residency.setWorkingSet(this, view, pages); } closeIdle(): void{ this.residency.closeIdleOf(this); } closeAll(): void{ this.residency.closeOwner(this); } } PageRasterReader [ClassDeclaration] (from packages/engine/services/src/features/render/PageRenderReader.ts): export class PageRenderReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } async render( pageObjectNumber: PageObjectNumber, options: PageRenderOptions, signal: AbortSignal, slices: Slices, ): Promise<{ raster: PageRaster; area: PdfRect} >{ throwIfAborted(signal); const{ fn} = this.runtime; const pool = this.session.pagePool(); const pagePtr = await pool.acquireInSlices(pageObjectNumber, signal, slices); try{ throwIfAborted(signal); checkRenderUsage(options, null); const print = options.usage === 'print'; const page = readPageBox(this.runtime, pagePtr); const target = resolveTarget(options.target, page); const rotation = options.rotation ?? 0; const viewport = options.viewport ??{ kind: 'scale', scale: 1} ; const layers = resolvePageLayers(options, { annotations: true, formFields: true} ); let flags = FPDF_REVERSE_BYTE_ORDER; if (layers.includeAnnotations) flags |= FPDF_RENDER_ANNOT; if (layers.includeFormFields) flags |= EPDF_RENDER_WIDGETS; if (print) flags |= FPDF_PRINTING; const raster = await rasterizeAsync(this.runtime, { rect: target, page, rotation, viewport, ...(options.maxOutputPixels !== undefined ?{ maxOutputPixels: options.maxOutputPixels} :{ } ), background: options.background === 'transparent' ? 'transparent' : 'white', draw: async (bitmapPtr, matrixPtr, clipPtr) =>{ throwIfAborted(signal); let status = fn.EPDF_RenderPageBitmapWithMatrix_Start( bitmapPtr, pagePtr, matrixPtr, clipPtr, flags, slices.budgetMs, ); try{ while (status === FPDF_RENDER_TOBECONTINUED){ await slices.between(); throwIfAborted(signal); status = fn.EPDF_RenderPage_Continue(pagePtr, slices.budgetMs); } } finally{ fn.FPDF_RenderPage_Close(pagePtr); } return status === FPDF_RENDER_DONE; } , } ); if (!raster){ throw new EngineError( EngineErrorCode.RuntimeUnavailable, `failed to render page object ${ pageObjectNumber} `, ); } return{ raster, area: target} ; } finally{ pool.release(pageObjectNumber); } } } PageRecord [InterfaceDeclaration] (from packages/engine/services/src/document-session/pages/PageRecord.ts): export interface PageRecord{ pageObjectNumber: PageObjectNumber; pageIndex: number; } PageRenderReader [ClassDeclaration] (from packages/engine/services/src/features/render/PageRenderReader.ts): export class PageRenderReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } async render( pageObjectNumber: PageObjectNumber, options: PageRenderOptions, signal: AbortSignal, slices: Slices, ): Promise<{ raster: PageRaster; area: PdfRect} >{ throwIfAborted(signal); const{ fn} = this.runtime; const pool = this.session.pagePool(); const pagePtr = await pool.acquireInSlices(pageObjectNumber, signal, slices); try{ throwIfAborted(signal); checkRenderUsage(options, null); const print = options.usage === 'print'; const page = readPageBox(this.runtime, pagePtr); const target = resolveTarget(options.target, page); const rotation = options.rotation ?? 0; const viewport = options.viewport ??{ kind: 'scale', scale: 1} ; const layers = resolvePageLayers(options, { annotations: true, formFields: true} ); let flags = FPDF_REVERSE_BYTE_ORDER; if (layers.includeAnnotations) flags |= FPDF_RENDER_ANNOT; if (layers.includeFormFields) flags |= EPDF_RENDER_WIDGETS; if (print) flags |= FPDF_PRINTING; const raster = await rasterizeAsync(this.runtime, { rect: target, page, rotation, viewport, ...(options.maxOutputPixels !== undefined ?{ maxOutputPixels: options.maxOutputPixels} :{ } ), background: options.background === 'transparent' ? 'transparent' : 'white', draw: async (bitmapPtr, matrixPtr, clipPtr) =>{ throwIfAborted(signal); let status = fn.EPDF_RenderPageBitmapWithMatrix_Start( bitmapPtr, pagePtr, matrixPtr, clipPtr, flags, slices.budgetMs, ); try{ while (status === FPDF_RENDER_TOBECONTINUED){ await slices.between(); throwIfAborted(signal); status = fn.EPDF_RenderPage_Continue(pagePtr, slices.budgetMs); } } finally{ fn.FPDF_RenderPage_Close(pagePtr); } return status === FPDF_RENDER_DONE; } , } ); if (!raster){ throw new EngineError( EngineErrorCode.RuntimeUnavailable, `failed to render page object ${ pageObjectNumber} `, ); } return{ raster, area: target} ; } finally{ pool.release(pageObjectNumber); } } } PageTextReader [ClassDeclaration] (from packages/engine/services/src/features/text/PageTextReader.ts): export class PageTextReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } async read( pageObjectNumber: PageObjectNumber, signal: AbortSignal, slices: Slices, ): Promise{ throwIfAborted(signal); const{ fn} = this.runtime; const pool = this.session.pagePool(); const pagePtr = await pool.acquireInSlices(pageObjectNumber, signal, slices); try{ throwIfAborted(signal); const textPagePtr = fn.FPDFText_LoadPage(pagePtr); if (!textPagePtr){ throw new EngineError( EngineErrorCode.RuntimeUnavailable, `FPDFText_LoadPage returned null for page object ${ pageObjectNumber} `, ); } try{ throwIfAborted(signal); const charCount = Math.max(fn.FPDFText_CountChars(textPagePtr), 0); const text = readTextFull(this.runtime, textPagePtr, charCount); const charMap = readCharMap(this.runtime, textPagePtr, pageObjectNumber); const violation = charMapViolation(charCount, text.length, charMap); if (violation !== null){ throw new EngineError( EngineErrorCode.RuntimeUnavailable, `char map invariant violated for page object ${ pageObjectNumber} : ${ violation} `, ); } return toPageText(charMap.length > 0 ?{ text, charCount, charMap} :{ text, charCount} ); } finally{ fn.FPDFText_ClosePage(textPagePtr); } } finally{ pool.release(pageObjectNumber); } } } PagesExtractor [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesExtractor.ts): export class PagesExtractor{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } extract( pages: PageRef[], flatten: PageExtractFlatten | undefined, signal: AbortSignal, ):{ bytes: ArrayBuffer; size: number} { throwIfAborted(signal); if (pages.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'pages.extract requires at least one page'); } const pageObjectNumbers = this.session.resolvePageRefs(pages); const seen = new Set(); for (const pageObjectNumber of pageObjectNumbers){ if (seen.has(pageObjectNumber)){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.extract was given duplicate page object number ${ pageObjectNumber} `, ); } seen.add(pageObjectNumber); } const indices = pageObjectNumbers.map( (pageObjectNumber) => this.session.recordByObjectNumber(pageObjectNumber).pageIndex, ); const{ fn, mem} = this.runtime; const srcPtr = this.session.requireDocPtr(); const idxPtr = mem.alloc(4 * indices.length); for (let i = 0; i < indices.length; i++){ mem.poke(idxPtr, 'i32', indices[i], 4 * i); } let destPtr: Ptr; try{ destPtr = flatten ? this.copyFlattened(srcPtr, idxPtr, indices, flatten) : this.copyPlain(srcPtr, idxPtr, indices); } catch (error){ mem.free(idxPtr); throw error; } const sizePtr = mem.alloc(U64_BYTES); let pdfPtr: Ptr | null = null; try{ const title = readMetaText(fn, mem, srcPtr, 'Title'); if (title !== null) writeMetaText(fn, mem, destPtr, 'Title', title); pokeU64(mem, sizePtr, 0); pdfPtr = fn.EPDF_SaveDocumentToOwnedBuffer(destPtr, FPDF_NO_INCREMENTAL, sizePtr); const size = Number(mem.peek(sizePtr, 'i32')); if (!pdfPtr || size <= 0){ throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save extracted pages'); } const bytes = mem.readBytes(pdfPtr, size); const buffer = new ArrayBuffer(bytes.byteLength); new Uint8Array(buffer).set(bytes); return{ bytes: buffer, size} ; } finally{ if (pdfPtr) fn.EPDF_FreeBuffer(pdfPtr); mem.free(sizePtr); mem.free(idxPtr); fn.FPDF_CloseDocument(destPtr); } } private copyPlain(srcPtr: Ptr, idxPtr: Ptr, indices: readonly number[]): Ptr{ const{ fn} = this.runtime; const destPtr = fn.FPDF_CreateNewDocument(); if (!destPtr){ throw new EngineError(EngineErrorCode.Unknown, 'FPDF_CreateNewDocument failed'); } if (!fn.EPDFDoc_ImportPages(destPtr, srcPtr, idxPtr, indices.length, 0, NULL_PTR)){ fn.FPDF_CloseDocument(destPtr); throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_ImportPages rejected the request (indices=[${ indices.join(', ')} ])`, ); } return destPtr; } private copyFlattened( srcPtr: Ptr, idxPtr: Ptr, indices: readonly number[], flatten: PageExtractFlatten, ): Ptr{ const flags = (flatten.includeAnnotations ? EXPORT_FLATTENED_ANNOTATIONS : 0) | (flatten.includeFormFields ? EXPORT_FLATTENED_FORM_FIELDS : 0); const destPtr = this.runtime.fn.EPDFDoc_ExportPagesFlattened( srcPtr, idxPtr, indices.length, flatten.usage === 'print' ? FLAT_PRINT : FLAT_NORMALDISPLAY, flags, ); if (!destPtr){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_ExportPagesFlattened rejected the request (indices=[${ indices.join(', ')} ])`, ); } return destPtr; } } PagesFlattener [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesFlattener.ts): export class PagesFlattener{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } flatten(pages: PageRef[], usage: PageFlattenUsage, signal: AbortSignal): PageFlattenResult{ throwIfAborted(signal); const pageObjectNumbers = this.session.resolvePageRefs(pages); requireUniquePages(pageObjectNumbers); const results: PageFlattenResult['results'] = []; const affected = new Set(); for (const pageObjectNumber of pageObjectNumbers){ throwIfAborted(signal); if (promoteInlineAnnotations(this.runtime, this.session, pageObjectNumber)){ affected.add(pageObjectNumber); } const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); let code: number; try{ code = this.runtime.fn.EPDFPage_Flatten(pagePtr, usage === 'print' ? 1 : 0); } finally{ pool.release(pageObjectNumber); } if (code === FLATTEN_NOTHING_TO_DO){ results.push({ page: toPageRef(pageObjectNumber), status: 'unchanged'} ); continue; } if (code !== FLATTEN_SUCCESS){ throw new EngineError( EngineErrorCode.Unknown, code === FLATTEN_FAIL ? 'native page flatten failed after preflight' : `native page flatten returned unexpected code ${ code} `, ); } affected.add(pageObjectNumber); results.push({ page: toPageRef(pageObjectNumber), status: 'applied'} ); } if (affected.size === 0){ return{ pages, usage, results, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } this.session.invalidateDerived(); const meta: MutationMeta ={ affectedPages: [...affected].map((pageObjectNumber) => toPageRef(pageObjectNumber)), cacheDelta: null, ...this.session.writeStamp(), } ; return{ pages, usage, results, meta} ; } } PagesInserter [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesInserter.ts): export class PagesInserter{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } insert( bytes: ArrayBuffer, position: PagePosition, signal: AbortSignal, objectNumbers?: readonly number[], ): PageInsertResult{ throwIfAborted(signal); if (bytes.byteLength === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'pages.insert requires non-empty bytes'); } const{ fn, mem} = this.runtime; const destPtr = this.session.requireDocPtr(); const at = pageIndexAt(this.session, position, fn.FPDF_GetPageCount(destPtr)); const dataPtr = mem.alloc(bytes.byteLength); let srcPtr: Ptr | null = null; try{ mem.writeBytes(dataPtr, new Uint8Array(bytes)); srcPtr = fn.FPDF_LoadMemDocument(dataPtr, bytes.byteLength, ''); if (!srcPtr){ throw loadFailure( fn, null, new EngineError( EngineErrorCode.MalformedPdf, 'pages.insert source PDF could not be opened', ), ); } const count = fn.FPDF_GetPageCount(srcPtr); if (count <= 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'pages.insert source PDF has no pages'); } keepFieldNamesApart(this.runtime, this.session, srcPtr); const result = this.importInto(srcPtr, at, count, objectNumbers, 'pages.insert', signal); const retainedSrc = srcPtr; this.session.retainUntilClose(() =>{ fn.FPDF_CloseDocument(retainedSrc); mem.free(dataPtr); } ); return result; } catch (error){ if (srcPtr) fn.FPDF_CloseDocument(srcPtr); mem.free(dataPtr); throw error; } } copy( refs: readonly PageRef[], position: PagePosition, signal: AbortSignal, objectNumbers?: readonly number[], ): PageInsertResult{ throwIfAborted(signal); if (refs.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'pages.copy requires at least one page'); } const indices = this.session .resolvePageRefs([...refs]) .map((pageObjectNumber) => this.session.recordByObjectNumber(pageObjectNumber).pageIndex); const{ fn} = this.runtime; const destPtr = this.session.requireDocPtr(); const at = pageIndexAt(this.session, position, fn.FPDF_GetPageCount(destPtr)); const scratchPtr = fn.FPDF_CreateNewDocument(); if (!scratchPtr){ throw new EngineError(EngineErrorCode.Unknown, 'FPDF_CreateNewDocument failed'); } try{ const copied = withI32Array(this.runtime.mem, indices, (indicesPtr, count) => fn.EPDFDoc_ImportPages(scratchPtr, destPtr, indicesPtr, count, 0, NULL_PTR), ); if (!copied){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_ImportPages rejected copying pages [${ indices.join(', ')} ] out`, ); } keepFieldNamesApart(this.runtime, this.session, scratchPtr); const result = this.importInto( scratchPtr, at, indices.length, objectNumbers, 'pages.copy', signal, ); this.session.retainUntilClose(() => fn.FPDF_CloseDocument(scratchPtr)); return result; } catch (error){ fn.FPDF_CloseDocument(scratchPtr); throw error; } } private importInto( srcPtr: Ptr, at: number, count: number, objectNumbers: readonly number[] | undefined, op: 'pages.insert' | 'pages.copy', signal: AbortSignal, ): PageInsertResult{ const{ fn, mem} = this.runtime; const destPtr = this.session.requireDocPtr(); if (objectNumbers && objectNumbers.length !== count){ throw new EngineError( EngineErrorCode.InvalidArg, `${ op} needs one object number per page: ${ objectNumbers.length} for ${ count} `, { details:{ field: 'objectNumbers'} } , ); } for (const objectNumber of objectNumbers ?? []) this.session.claimObjectNumber(objectNumber); const imported = objectNumbers ? withI32Array(mem, objectNumbers, (numbersPtr) => fn.EPDFDoc_ImportPages(destPtr, srcPtr, NULL_PTR, 0, at, numbersPtr), ) : fn.EPDFDoc_ImportPages(destPtr, srcPtr, NULL_PTR, 0, at, NULL_PTR); if (!imported){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_ImportPages rejected the ${ op} at index ${ at} `, ); } this.session.refreshPageRegistry(); const layout = new PagesReader(this.runtime, this.session).read(signal); const insertedPages: PageRef[] = layout.pages.slice(at, at + count).map((page) => page.ref); for (const page of insertedPages){ promoteInlineAnnotations(this.runtime, this.session, page.objectNumber); } return{ insertedPages, layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} , } ; } insertBlank( spec: PageInsertBlankSpec, position: PagePosition, signal: AbortSignal, objectNumbers?: readonly number[], ): PageInsertResult{ throwIfAborted(signal); const{ size} = spec; const count = spec.count ?? 1; if ( !Number.isFinite(size?.width) || !Number.isFinite(size?.height) || size.width <= 0 || size.height <= 0 ){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.insertBlank size must have positive finite dimensions, got ${ size?.width} x${ size?.height} `, ); } if (!Number.isInteger(count) || count < 1 || count > PAGE_INSERT_BLANK_MAX_COUNT){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.insertBlank count ${ count} out of range [1, ${ PAGE_INSERT_BLANK_MAX_COUNT} ]`, ); } const{ fn} = this.runtime; const destPtr = this.session.requireDocPtr(); const at = pageIndexAt(this.session, position, fn.FPDF_GetPageCount(destPtr)); if (objectNumbers && objectNumbers.length !== count){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.insertBlank needs one object number per page: ${ objectNumbers.length} for ${ count} `, { details:{ field: 'objectNumbers'} } , ); } for (const objectNumber of objectNumbers ?? []) this.session.claimObjectNumber(objectNumber); for (let i = 0; i < count; i++){ const objectNumber = objectNumbers?.[i]; if ( !fn.EPDFPage_InsertBlankRaw(destPtr, at + i, size.width, size.height, objectNumber ?? 0) ){ if (objectNumber !== undefined) throw objectNumberUnavailable(objectNumber, 'taken'); throw new EngineError( EngineErrorCode.Unknown, `EPDFPage_InsertBlankRaw rejected page ${ i + 1} /${ count} at index ${ at + i} `, ); } } this.session.refreshPageRegistry(); const layout = new PagesReader(this.runtime, this.session).read(signal); const insertedPages: PageRef[] = layout.pages.slice(at, at + count).map((page) => page.ref); return{ insertedPages, layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} , } ; } } PagesMutator [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesMutator.ts): export class PagesMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } reorder( pages: PageRef[], position: PagePosition, signal: AbortSignal, ): PageReorderResult{ const pageObjectNumbers = this.session.resolvePageRefs(pages); throwIfAborted(signal); this.requireUniquePageObjectNumbers('pages.reorder', pageObjectNumbers); const anchor = anchorOf(position); if (anchor && pageObjectNumbers.includes(anchor.objectNumber)){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.reorder: the neighbour page ${ anchor.objectNumber} is one of the pages that move`, { details:{ field: 'position'} } , ); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const fromIndices = pageObjectNumbers.map((pageObjectNumber) =>{ throwIfAborted(signal); return this.session.recordByObjectNumber(pageObjectNumber).pageIndex; } ); const at = pageIndexAt(this.session, position, fn.FPDF_GetPageCount(docPtr)); const toIndex = at - fromIndices.filter((index) => index < at).length; const arrPtr = mem.alloc(4 * fromIndices.length); let ok: boolean; try{ for (let i = 0; i < fromIndices.length; i++){ mem.poke(arrPtr, 'i32', fromIndices[i], 4 * i); } ok = fn.FPDF_MovePages(docPtr, arrPtr, fromIndices.length, toIndex); } finally{ mem.free(arrPtr); } if (!ok){ throw new EngineError( EngineErrorCode.InvalidArg, `FPDF_MovePages rejected the request (toIndex=${ toIndex} , fromIndices=[${ fromIndices.join( ', ', )} ])`, ); } this.session.refreshPageRegistry(); const layout = new PagesReader(this.runtime, this.session).read(signal); return{ pages: pageObjectNumbers.map(toPageRef), layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} , } ; } rotate( pages: PageRef[], rotation: PdfRotation, signal: AbortSignal, ): PageRotateResult{ const pageObjectNumbers = this.session.resolvePageRefs(pages); throwIfAborted(signal); this.requireUniquePageObjectNumbers('pages.rotate', pageObjectNumbers); if (rotation !== 0 && rotation !== 90 && rotation !== 180 && rotation !== 270){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.rotate rotation must be 0, 90, 180 or 270 (got ${ rotation} )`, ); } const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); for (const pageObjectNumber of pageObjectNumbers){ this.session.recordByObjectNumber(pageObjectNumber); } const quarterTurns = rotation / 90; for (const pageObjectNumber of pageObjectNumbers){ if (!fn.EPDFDoc_SetPageRotationByObjectNumber(docPtr, pageObjectNumber, quarterTurns)){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_SetPageRotationByObjectNumber rejected page ${ pageObjectNumber} after validation`, ); } } const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } delete(pages: PageRef[], signal: AbortSignal): PageDeleteResult{ const pageObjectNumbers = this.session.resolvePageRefs(pages); throwIfAborted(signal); this.requireUniquePageObjectNumbers('pages.delete', pageObjectNumbers); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const totalPages = fn.FPDF_GetPageCount(docPtr); if (pageObjectNumbers.length >= totalPages){ throw new EngineError( EngineErrorCode.InvalidArg, `pages.delete would remove every page (${ pageObjectNumbers.length} of ${ totalPages} ); a document must keep at least one`, ); } const pool = this.session.pagePool(); for (const pageObjectNumber of pageObjectNumbers){ this.session.recordByObjectNumber(pageObjectNumber); if (pool.isHeld(pageObjectNumber)){ throw new EngineError( EngineErrorCode.Unknown, `internal invariant violation: pagePtr for page ${ pageObjectNumber} is still held during pages.delete`, ); } } for (const pageObjectNumber of pageObjectNumbers){ if (!fn.EPDFDoc_DeletePageByObjectNumber(docPtr, pageObjectNumber)){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_DeletePageByObjectNumber rejected page ${ pageObjectNumber} after validation`, ); } } this.session.refreshPageRegistry(); const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } setName(input: PageNameInput, signal: AbortSignal): PageNameResult{ throwIfAborted(signal); if (input.name.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'pages.setName requires a non-empty name'); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const pageObjectNumber = this.session.resolvePageRef(input.page).pageObjectNumber; if (input.replace !== undefined && input.replace !== input.name && input.replace.length > 0){ writeUtf16String(mem, input.replace, (ptr) => fn.EPDFDoc_RemoveNamedPage(docPtr, ptr)); } const ok = writeUtf16String(mem, input.name, (ptr) => fn.EPDFDoc_SetNamedPage(docPtr, ptr, pageObjectNumber), ); if (!ok){ throw new EngineError( EngineErrorCode.Unknown, `EPDFDoc_SetNamedPage rejected '${ input.name} ' for page ${ pageObjectNumber} `, ); } const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } removeName(input: PageRemoveNameInput, signal: AbortSignal): PageNameResult{ throwIfAborted(signal); if (input.name.length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'pages.removeName requires a non-empty name', ); } const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const removed = writeUtf16String(mem, input.name, (ptr) => fn.EPDFDoc_RemoveNamedPage(docPtr, ptr), ); if (!removed){ throw new EngineError( EngineErrorCode.NotFound, `pages.removeName: no /Names /Pages registration '${ input.name} '`, ); } const layout = new PagesReader(this.runtime, this.session).read(signal); return{ layout, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} } ; } private requireUniquePageObjectNumbers(op: string, pageObjectNumbers: PageObjectNumber[]): void{ if (pageObjectNumbers.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, `${ op} requires at least one page`); } const seen = new Set(); for (const pageObjectNumber of pageObjectNumbers){ if (seen.has(pageObjectNumber)){ throw new EngineError( EngineErrorCode.InvalidArg, `${ op} was given duplicate page object number ${ pageObjectNumber} `, ); } seen.add(pageObjectNumber); } } } PagesReader [ClassDeclaration] (from packages/engine/services/src/features/pages/PagesReader.ts): export class PagesReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } read(signal: AbortSignal): PageListSnapshot{ throwIfAborted(signal); const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const records = this.session.allRecords(); const actionBudget = new ActionReadBudgetTracker(); const labels = readLabelSections(this.runtime, docPtr); return withScratchN( mem, [RECTF_BYTES, F32_BYTES, I32_BYTES], ([rectPtr, userUnitPtr, intPtr]) =>{ const pages: PageLayout[] = records.map((record) =>{ throwIfAborted(signal); const index = record.pageIndex; const actions = readPageActions(fn, mem, docPtr, record.pageObjectNumber, actionBudget); const viewports = readViewports(fn, mem, docPtr, index); const boxes = readBoxes(fn, mem, docPtr, index, rectPtr); return{ index, ref: toPageRef(record.pageObjectNumber), label: labelAt(labels, index), size: pdfRectSize(boxes.crop), rotation: readRotation(fn, mem, docPtr, index, intPtr), userUnit: readUserUnit(fn, mem, docPtr, index, userUnitPtr), tabOrder: readTabOrder(fn, mem, docPtr, index), boxes, pdfCropBox: boxes.crop, ...(actions ?{ actions} :{ } ), ...(viewports.length ?{ viewports} :{ } ), } ; } ); return{ pageCount: pages.length, pages, labels, namedPages: readNamedPages(fn, mem, docPtr), } ; } , ); } } RawAnnotationReader [ClassDeclaration] (from packages/engine/services/src/features/annotations/RawAnnotationReader.ts): export class RawAnnotationReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly fonts?: FontRegistrar, ){ } list( pages: readonly PageObjectNumber[] | undefined, signal: AbortSignal, family?: AnnotationFamily, ): AnnotationList{ throwIfAborted(signal); if (pages === undefined){ this.session.ensureFullPageRegistry(); pages = this.session.allRecords().map((record) => record.pageObjectNumber); } const lists: AnnotationList[] = []; for (const pageObjectNumber of pages){ throwIfAborted(signal); lists.push(this.listOne(pageObjectNumber, signal, family)); } return concatAnnotationLists(lists); } listOne( pageObjectNumber: PageObjectNumber, signal: AbortSignal, family?: AnnotationFamily, ): AnnotationList{ throwIfAborted(signal); const{ fn} = this.runtime; const docPtr = this.session.requireDocPtr(); const record = this.session.recordByObjectNumber(pageObjectNumber); const count = fn.EPDFPage_GetAnnotCountRaw(docPtr, record.pageIndex); if (count < 0){ throw new EngineError( EngineErrorCode.Unknown, `EPDFPage_GetAnnotCountRaw returned ${ count} for page ${ pageObjectNumber} `, ); } return collectPageAnnotations({ runtime: this.runtime, session: this.session, pageObjectNumber, count, getAnnotPtrAt: (i) => fn.EPDFPage_GetAnnotRaw(docPtr, record.pageIndex, i), signal, ...(this.fonts ?{ fonts: this.fonts} :{ } ), ...(family ?{ family} :{ } ), } ); } } RawGeometryGlyphRecord [InterfaceDeclaration] (from packages/engine/services/src/features/geometry/PageGeometryReader.ts): export interface RawGeometryGlyphRecord{ objectKey: number | bigint; fontSize?: number; flags: number; looseBox: PdfRect; tightBox?: PdfRect; looseQuad?: PdfQuad; tightQuad?: PdfQuad; upright: boolean; baselineAngle: number; ascentFlip: boolean; } RedactionApplier [ClassDeclaration] (from packages/engine/services/src/features/redaction/RedactionApplier.ts): export class RedactionApplier{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } apply(scope: RedactionApplyScope, signal: AbortSignal): RedactionApplyResult{ throwIfAborted(signal); const plan = this.buildPlan(scope); for (const pageObjectNumber of plan.keys()){ this.session.recordByObjectNumber(pageObjectNumber); } this.preflight(plan, signal); const{ fn} = this.runtime; const results: RedactionApplyResult['results'] = []; const affected = new Set(); let totalRemoved = 0; for (const [pageObjectNumber, refs] of plan){ throwIfAborted(signal); if (promoteInlineAnnotations(this.runtime, this.session, pageObjectNumber)){ affected.add(pageObjectNumber); } const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); try{ const outcome = refs === null ? this.applyAllOnPage(pagePtr) : this.applyRefsOnPage(pagePtr, refs); if (outcome.status === 'applied'){ fn.FPDFPage_GenerateContent(pagePtr); affected.add(pageObjectNumber); totalRemoved += outcome.removed; } results.push({ page: toPageRef(pageObjectNumber), status: outcome.status, removedAnnotationCount: outcome.removed, } ); } finally{ pool.release(pageObjectNumber); } } if (affected.size === 0){ const meta: MutationMeta ={ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} ; return{ scope, results, removedAnnotationCount: totalRemoved, meta} ; } this.session.invalidateDerived(); const meta: MutationMeta ={ affectedPages: [...affected].map((pageObjectNumber) => toPageRef(pageObjectNumber)), cacheDelta: null, ...this.session.writeStamp(), } ; return{ scope, results, removedAnnotationCount: totalRemoved, meta} ; } private buildPlan(scope: RedactionApplyScope): Map{ const plan = new Map(); if ('pages' in scope){ if (this.session.resolvePageRefs(scope.pages).length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'redaction.apply requires at least one page', ); } for (const pageObjectNumber of this.session.resolvePageRefs(scope.pages)){ if (plan.has(pageObjectNumber)){ throw new EngineError( EngineErrorCode.InvalidArg, `redaction.apply was given duplicate page object number ${ pageObjectNumber} `, ); } plan.set(pageObjectNumber, null); } return plan; } if (scope.annotations.length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'redaction.apply requires at least one annotation ref', ); } for (const ref of scope.annotations){ const existing = plan.get(ref.page.objectNumber); if (existing === null){ throw new EngineError(EngineErrorCode.InvalidArg, 'mixed redaction scopes on one page'); } if (existing) existing.push(ref); else plan.set(ref.page.objectNumber, [ref]); } return plan; } private preflight( plan: Map, signal: AbortSignal, ): void{ const{ fn} = this.runtime; for (const [pageObjectNumber, refs] of plan){ if (refs === null) continue; throwIfAborted(signal); const pool = this.session.pagePool(); const pagePtr = pool.acquire(pageObjectNumber); try{ for (const ref of refs){ const annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref); try{ const subtype = subtypeFromCode(fn.FPDFAnnot_GetSubtype(annotPtr)); if (subtype !== 'redact'){ throw new EngineError( EngineErrorCode.InvalidArg, `redaction.apply ref on page ${ pageObjectNumber} resolves to a '${ subtype} ' annotation, not a redact annotation`, ); } } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } } } finally{ pool.release(pageObjectNumber); } } } private applyAllOnPage(pagePtr: Ptr):{ status: 'applied' | 'unchanged'; removed: number} { const{ fn, mem} = this.runtime; const hasRedactions = this.pageHasRedactAnnotations(pagePtr); return withScratch(mem, I32_BYTES, (countPtr) =>{ const ok = fn.EPDFPage_ApplyRedactions(pagePtr, NULL_PTR, 0, countPtr); if (!ok){ if (hasRedactions){ throw new EngineError(EngineErrorCode.Unknown, 'native page redaction apply failed'); } return{ status: 'unchanged' as const, removed: 0} ; } return{ status: 'applied' as const, removed: readI32(mem, countPtr) >>> 0} ; } ); } private pageHasRedactAnnotations(pagePtr: Ptr): boolean{ const{ fn} = this.runtime; const count = fn.FPDFPage_GetAnnotCount(pagePtr); for (let index = 0; index < count; index++){ const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, index); if (!annotPtr) continue; try{ if (subtypeFromCode(fn.FPDFAnnot_GetSubtype(annotPtr)) === 'redact') return true; } finally{ fn.FPDFPage_CloseAnnot(annotPtr); } } return false; } private applyRefsOnPage( pagePtr: Ptr, refs: AnnotationRef[], ):{ status: 'applied'; removed: number} { const{ fn, mem} = this.runtime; const annotPtrs: Ptr[] = []; let removed = 0; try{ for (const ref of refs){ annotPtrs.push(resolveAnnotPtr(this.runtime, this.session, pagePtr, ref)); } const ok = withPointerTable(this.runtime, annotPtrs, (table, count) => withScratch(mem, I32_BYTES, (countPtr) =>{ const applied = fn.EPDFPage_ApplyRedactions(pagePtr, table, count, countPtr); if (applied) removed = readI32(mem, countPtr) >>> 0; return applied; } ), ); if (!ok){ throw new EngineError(EngineErrorCode.Unknown, 'native redaction apply failed after preflight'); } } finally{ for (const annotPtr of annotPtrs){ fn.FPDFPage_CloseAnnot(annotPtr); } } return{ status: 'applied', removed} ; } } ReverseStep [TypeAliasDeclaration] (from packages/engine/services/src/features/changes/ChangeRecord.ts): export type ReverseStep = | ObjectsRevertStep | AnnotationRemoveStep | AnnotationRestoreStep | AnnotationReorderStep | FieldRemoveStep | FieldRestoreStep | WidgetRestoreStep | WidgetDeleteStep | CalculationOrderStep | MetadataRevertStep | OutlineRemoveStep | OutlineRestoreStep | OutlineMoveStep | OutlineReopenStep | PageRotateStep | PageScaleStep | PageReorderStep | PageRestoreStep | PageRemoveStep | AttachmentRemoveStep | AttachmentRestoreStep; SearchReader [ClassDeclaration] (from packages/engine/services/src/features/search/SearchReader.ts): export class SearchReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } async query( request: SearchScanRequest, signal: AbortSignal, slices: Slices, ): Promise>{ throwIfAborted(signal); const query = searchQueryOf(request); const snippets = request.snippets ?? false; const valid = validateSearchQuery(query); if (!valid.ok){ throw new EngineError( EngineErrorCode.InvalidArg, `invalid search query (${ valid.issue} ): ${ valid.message} `, ); } const records = this.session.allRecords(); const pageCount = records.length; if (!query.regex && foldText(query.text).folded.trim().length === 0){ return{ matches: [], nextCursor: null, pagesSearched: 0, pageCount} ; } const seq = this.session.cacheSeq(); const key = searchQueryKey(query, snippets); let start = 0; let scanned = 0; if (request.cursor !== undefined){ const state = decodeSearchCursor(request, request.cursor, seq, key); start = state.start; scanned = state.scanned; } else{ if (request.from !== undefined){ start = this.session.resolvePageRef(request.from).pageObjectNumber; } if (request.skip !== undefined){ scanned = Math.min(Math.max(0, Math.floor(request.skip)), pageCount); } } let order = records; if (start !== 0){ const at = records.findIndex((r) => r.pageObjectNumber === start); order = records.slice(at).concat(records.slice(0, at)); } const maxPages = clamp(request.limit?.pages, DEFAULT_MAX_PAGES, CEILING_MAX_PAGES); const maxMatches = clamp(request.limit?.matches, DEFAULT_MAX_MATCHES, CEILING_MAX_MATCHES); const matches: SearchMatch[] = []; let pagesThisSlice = 0; const timer = new SliceTimer(slices, signal); while (scanned < order.length && pagesThisSlice < maxPages && matches.length < maxMatches){ if (timer.due) await timer.pause(); throwIfAborted(signal); const pageObjectNumber = order[scanned].pageObjectNumber; const corpus = await acquirePageCorpus( this.runtime, this.session, pageObjectNumber, signal, slices, ); const text = corpus.snapshot.text; let ranges: TextRange[]; if (query.regex){ ranges = matchRegex(text, query); } else if (query.matchCase || query.matchDiacritics || query.ignoreWhitespace){ ranges = matchLiteral(foldText(text, foldOptionsFor(query)), query); } else{ ranges = matchLiteral(corpus.folded, query); } if (ranges.length > 0){ const geometry = await new PageGeometryReader(this.runtime, this.session).read( pageObjectNumber, signal, slices, ); const layout = createPdfTextLayout(geometry); for (const range of ranges){ const chars = charRangeForTextOffsets(corpus.snapshot, range); matches.push({ page: toPageRef(pageObjectNumber), start: chars.start, count: chars.count, segments: layout.segments(chars), ...(snippets ?{ snippet: buildSnippet(text, range)} :{ } ), } ); } } scanned++; pagesThisSlice++; } return{ matches, nextCursor: scanned < order.length ? encodeSearchCursor({ v: 1, seq, key, start, scanned} ) : null, pagesSearched: scanned, pageCount, } ; } } SecurityReader [ClassDeclaration] (from packages/engine/services/src/features/security/SecurityReader.ts): export class SecurityReader{ constructor(private readonly runtime: PdfRuntimeModule){ ensureInitialized(this.runtime); } probeFile(path: string, password: string | null = null): DocumentSecurityProbeInfo{ const now = Date.now(); let access: ReturnType | null = null; let docPtr: Ptr | null = null; try{ access = this.runtime.fileAccess.fromNodeFile(path); docPtr = this.runtime.fn.FPDF_LoadCustomDocument(access.ptr, password ?? ''); if (!docPtr){ const err = this.runtime.fn.FPDF_GetLastError(); if (err === FPDF_ERR_PASSWORD){ return{ encryptionState: 'encrypted', encryptionRequiresPassword: true, securityHandlerRevision: null, pdfPermissionsBits: null, pdfPermissionsAllAllowed: null, pdfOpenedAs: null, securityProbedAt: now, } ; } if (err === FPDF_ERR_SECURITY){ return{ encryptionState: 'unsupported', encryptionRequiresPassword: null, securityHandlerRevision: null, pdfPermissionsBits: null, pdfPermissionsAllAllowed: null, pdfOpenedAs: null, securityProbedAt: now, } ; } return unknownSecurity(now); } const encrypted = this.runtime.fn.EPDF_IsEncrypted(docPtr); const bits = normalizeU32(this.runtime.fn.FPDF_GetDocPermissions(docPtr)); const openedAs = !encrypted ? 'none' : this.runtime.fn.EPDF_IsOwnerUnlocked(docPtr) ? 'owner' : 'user'; return buildSecurityInfo({ openedAs, permissionsBits: bits, securityHandlerRevision: encrypted ? this.runtime.fn.FPDF_GetSecurityHandlerRevision(docPtr) : null, probedAt: now, } ); } finally{ if (docPtr) this.runtime.fn.FPDF_CloseDocument(docPtr); access?.close(); } } readLiveSecurityInfo(session: DocumentSession): DocumentSecurityProbeInfo{ const{ fn} = this.runtime; const docPtr = session.requireDocPtr(); const encrypted = fn.EPDF_IsEncrypted(docPtr); const bits = normalizeU32(fn.FPDF_GetDocUserPermissions(docPtr)); const openedAs = !encrypted ? 'none' : fn.EPDF_IsOwnerUnlocked(docPtr) ? 'owner' : 'user'; return buildSecurityInfo({ openedAs, permissionsBits: bits, securityHandlerRevision: encrypted ? fn.FPDF_GetSecurityHandlerRevision(docPtr) : null, probedAt: Date.now(), } ); } checkPasswordPermissions( session: DocumentSession, password: string, mode: 'any' | 'owner' = 'any', ): DocumentSecurityProbeInfo{ const docPtr = session.requireDocPtr(); const{ mem, fn} = this.runtime; const kindPtr = mem.alloc(4); const userPermissionsPtr = mem.alloc(4); const effectivePermissionsPtr = mem.alloc(4); const revisionPtr = mem.alloc(4); try{ mem.poke(kindPtr, 'i32', 0); mem.poke(userPermissionsPtr, 'i32', 0); mem.poke(effectivePermissionsPtr, 'i32', 0); mem.poke(revisionPtr, 'i32', 0); const ok = fn.EPDF_CheckPasswordPermissions( docPtr, password, kindPtr, userPermissionsPtr, effectivePermissionsPtr, revisionPtr, ); if (!ok){ throw new EngineError(EngineErrorCode.DocPasswordIncorrect, 'incorrect document password'); } const openedAs = openedAsFromCode(Number(mem.peek(kindPtr, 'i32'))); if (mode === 'owner' && openedAs !== 'owner'){ throw new EngineError(EngineErrorCode.DocPasswordIncorrect, 'owner password required'); } return buildSecurityInfo({ openedAs, permissionsBits: normalizeU32(Number(mem.peek(effectivePermissionsPtr, 'i32'))), securityHandlerRevision: Number(mem.peek(revisionPtr, 'i32')), probedAt: Date.now(), } ); } finally{ mem.free(revisionPtr); mem.free(effectivePermissionsPtr); mem.free(userPermissionsPtr); mem.free(kindPtr); } } } SignatureAnalyzer [ClassDeclaration] (from packages/engine/services/src/features/signature/SignatureAnalyzer.ts): export class SignatureAnalyzer{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } readWorkingCopySnapshot(): SignatureSnapshot{ const stack = new CloseStack(); try{ const copy = this.openWorkingCopy(stack); if (copy.source === 'loaded'){ return new SignatureReader(this.runtime, this.session).readSnapshot(); } const target = copy.target; return withSignatureModel(this.runtime, target, (model) =>{ const chainValid = this.runtime.fn.EPDFSig_IsRevisionChainValid(model); const signatures = readSignaturesFromModel(this.runtime, model); const revisions = chainValid ? readRevisions(this.runtime, target, signatures) : []; return{ chainValid, revisions, signatures, protection: deriveProtection(signatures)} ; } ); } finally{ stack.close(); } } analyze(input: AnalyzeInput): ChangeAnalysis{ const reader = new SignatureReader(this.runtime, this.session); const snapshot = reader.readSnapshot(); const version = reader.version(); const mode = input.exploratoryLevel ? 'exploratory' : 'authoritative'; const detail = input.detail ?? 'summary'; let basisSource: 'persisted' | 'working-copy' = 'persisted'; const editsVersion = this.session.editsSeq(); let sinceRevision: number; let sinceSignature: number | null = null; if ('signatureIndex' in input.since){ const sig = snapshot.signatures[input.since.signatureIndex]; if (!sig){ throw new EngineError( EngineErrorCode.NotFound, `no signature ${ input.since.signatureIndex} `, ); } if (!sig.signed || sig.revisionIndex === null){ throw new EngineError( EngineErrorCode.InvalidArg, `signature ${ input.since.signatureIndex} seals no whole revision; nothing to analyze from`, ); } sinceRevision = sig.revisionIndex; sinceSignature = sig.index; } else{ sinceRevision = input.since.revisionIndex; } if (!snapshot.chainValid){ const current ={ verdict: 'indeterminate' as const, complete: false, findings: [{ rule: 'revision-chain', verdict: 'incomplete' as const, objectNumber: 0, detail: 'the cross-reference chain is broken or was rebuilt: no revision can be told from another', } , ], method: 'net-state' as const, } ; return{ mode, policyVersion: SIGNATURE_POLICY_VERSION, basis:{ version, editsVersion, source: 'persisted'} , since:{ revisionIndex: sinceRevision, signatureIndex: sinceSignature} , until:{ revisionIndex: sinceRevision} , restrictions: [], current:{ ...current, primary: current.findings[0]} , later:{ revisionCount: 0, undoneObjectNumbers: []} , verdict: 'indeterminate', steps: [], } ; } if ( !Number.isInteger(sinceRevision) || sinceRevision < 0 || sinceRevision >= snapshot.revisions.length ){ throw new EngineError(EngineErrorCode.InvalidArg, `no revision ${ sinceRevision} `); } const stack = new CloseStack(); try{ let target = this.session.requireDocPtr(); let revisions: PdfRevision[] = snapshot.revisions; const copy = input.until === 'working-copy' ? this.openWorkingCopy(stack) : null; if (copy && copy.source === 'working-copy'){ basisSource = 'working-copy'; target = copy.target; const signatures = withSignatureModel(this.runtime, target, (m) => readSignaturesFromModel(this.runtime, m), ); revisions = readRevisions(this.runtime, target, signatures); if (revisions.length === 0){ throw new EngineError( EngineErrorCode.MalformedPdf, 'the working copy has no valid revision chain', ); } } let untilRevision = revisions.length - 1; if (typeof input.until === 'object'){ untilRevision = input.until.revisionIndex; if ( !Number.isInteger(untilRevision) || untilRevision < sinceRevision || untilRevision >= revisions.length ){ throw new EngineError( EngineErrorCode.InvalidArg, `no revision ${ untilRevision} at or after ${ sinceRevision} `, ); } } const pair = new CloseStack(); let before: RevisionStructure; let after: RevisionStructure; let changes: ObjectChange[] = []; let unwritten: UnwrittenObject[] = []; let health:{ old: RevisionHealth; new: RevisionHealth} | undefined; try{ const sealed = this.openPrefix(target, revisions, sinceRevision, pair); const judged = untilRevision === revisions.length - 1 ? target : this.openPrefix(target, revisions, untilRevision, pair); before = readStructure(this.runtime, sealed); after = untilRevision === sinceRevision ? before : readStructure(this.runtime, judged); if (untilRevision > sinceRevision){ ({ changes, unwritten, health} = this.compare(sealed, judged, before, after)); } } finally{ pair.close(); } const judgedSignature = sinceSignature === null ? null : (before.signatures[sinceSignature] ?? null); const restrictions = restrictionsFor(before, judgedSignature); const levelOverride = input.exploratoryLevel as ModificationLevel | undefined; const net = evaluateStep({ older: sinceRevision, newer: untilRevision, changes, unwritten, before, after, health, restrictions:{ level: restrictions.level, locks: restrictions.locks} , levelOverride, } ); const certifies = restrictions.anchors.some((r) => r.source === 'docmdp' && r.own); const intermediate = untilRevision - sinceRevision; let steps: RevisionAnalysis[]; if (intermediate <= 1){ steps = intermediate === 1 ? [net] : []; } else if (certifies || detail === 'full'){ steps = this.walkSteps(target, revisions, sinceRevision, untilRevision, before, { level: restrictions.level, locks: restrictions.locks, levelOverride, } ); } else{ steps = []; } const current = certifies ?{ ...combine(net, steps), method: 'net-state+replay' as const} :{ ...assessmentOf(net), method: 'net-state' as const} ; return{ mode, policyVersion: SIGNATURE_POLICY_VERSION, basis:{ version, editsVersion, source: basisSource} , since:{ revisionIndex: sinceRevision, signatureIndex: sinceSignature} , until:{ revisionIndex: untilRevision} , restrictions: restrictions.anchors, current, later:{ revisionCount: intermediate, undoneObjectNumbers: changes.filter(sameEffectiveValue).map((c) => c.objectNumber), } , verdict: current.verdict, steps, } ; } finally{ stack.close(); } } private openPrefix(target: Ptr, revisions: PdfRevision[], index: number, stack: CloseStack): Ptr{ const prefix = this.runtime.fn.EPDFDoc_OpenRevision(target, BigInt(revisions[index].end)); if (prefix === NULL_PTR){ throw new EngineError( EngineErrorCode.MalformedPdf, `revision ${ index} does not open as a document`, ); } stack.push(() => this.runtime.fn.FPDF_CloseDocument(prefix)); return prefix; } private walkSteps( target: Ptr, revisions: PdfRevision[], since: number, until: number, sealedStructure: RevisionStructure, restrictions:{ level: ModificationLevel; locks: DocumentFieldLock[]; levelOverride?: ModificationLevel; } , ): RevisionAnalysis[]{ const{ fn} = this.runtime; const steps: RevisionAnalysis[] = []; let older = this.openPrefix(target, revisions, since, new CloseStack()); let olderStructure = sealedStructure; try{ for (let r = since + 1; r <= until; r++){ const newer = r === revisions.length - 1 ? target : this.openPrefix(target, revisions, r, new CloseStack()); try{ const newerStructure = readStructure(this.runtime, newer); const{ changes, unwritten, health} = this.compare( older, newer, olderStructure, newerStructure, ); steps.push( evaluateStep({ older: r - 1, newer: r, changes, unwritten, before: olderStructure, after: newerStructure, health, restrictions:{ level: restrictions.level, locks: restrictions.locks} , levelOverride: restrictions.levelOverride, } ), ); olderStructure = newerStructure; } finally{ fn.FPDF_CloseDocument(older); older = newer; } } } finally{ if (older !== target) fn.FPDF_CloseDocument(older); } return steps; } private openWorkingCopy(stack: CloseStack):{ target: Ptr; source: 'loaded' | 'working-copy'} { const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); if (!this.session.hasUnsavedEdits()) return{ target: docPtr, source: 'loaded'} ; const saver = new DocumentSaver(this.runtime, this.session); if (this.session.kind === 'layer'){ const base = this.session.source.base; if (saver.canWriteScratchFiles() && base?.kind === 'file'){ const path = scratchPath(base.path, 'working-copy', generateUuid(), 'delta'); stack.push(() => this.runtime.fileWrite.removeFile(path)); const delta = saver.saveLayerDeltaToFileEx(path); if (!delta.changedSinceLoad) return{ target: docPtr, source: 'loaded'} ; if (this.runtime.fileAccess.sizeOf(path) === 0) return this.freshLayerOverBase(stack); const overlay = withUtf8CString(mem, path, (pathPtr) => fn.EPDFDoc_OpenBaseOverlayFromPath(docPtr, pathPtr), ); if (overlay === NULL_PTR){ throw new EngineError( EngineErrorCode.MalformedPdf, 'the working copy does not compose with its base', ); } stack.push(() => fn.FPDF_CloseDocument(overlay)); return{ target: overlay, source: 'working-copy'} ; } const delta = saver.saveLayerDeltaEx(); if (!delta.changedSinceLoad) return{ target: docPtr, source: 'loaded'} ; if (delta.size === 0) return this.freshLayerOverBase(stack); const bytes = new Uint8Array(delta.bytes); const ptr = mem.alloc(bytes.byteLength); try{ mem.writeBytes(ptr, bytes); const overlay = fn.EPDFDoc_OpenBaseOverlay(docPtr, ptr, bytes.byteLength); if (overlay === NULL_PTR){ throw new EngineError( EngineErrorCode.MalformedPdf, 'the working copy does not compose with its base', ); } stack.push(() => fn.FPDF_CloseDocument(overlay)); return{ target: overlay, source: 'working-copy'} ; } finally{ mem.free(ptr); } } const saved = saver.saveStandaloneToBufferEx('incremental'); if (saved.unchangedSinceLoad) return{ target: docPtr, source: 'loaded'} ; const opened = openFatMemoryDocument( this.runtime, new Uint8Array(saved.bytes), this.session.password, ); stack.push(() => opened.close()); return{ target: opened.docPtr, source: 'working-copy'} ; } private freshLayerOverBase(stack: CloseStack):{ target: Ptr; source: 'working-copy'} { const{ fn, mem} = this.runtime; const base = fn.EPDFLayer_GetBaseDocument(this.session.requireDocPtr()); const statusPtr = mem.alloc(4); try{ mem.poke(statusPtr, 'i32', -1); const fresh = fn.EPDFLayer_OpenLayer(base, NULL_PTR, this.session.password ?? '', statusPtr); if (fresh === NULL_PTR || Number(mem.peek(statusPtr, 'i32')) !== 0){ throw new EngineError( EngineErrorCode.MalformedPdf, 'the working copy could not be opened over its base', ); } stack.push(() => fn.FPDF_CloseDocument(fresh)); return{ target: fresh, source: 'working-copy'} ; } finally{ mem.free(statusPtr); } } private compare( older: Ptr, newer: Ptr, before: RevisionStructure, after: RevisionStructure, ):{ changes: ObjectChange[]; unwritten: UnwrittenObject[]; health:{ old: RevisionHealth; new: RevisionHealth} ; } { const{ fn, mem} = this.runtime; const diff = fn.EPDFDoc_CompareRevisions(older, newer); if (diff === NULL_PTR){ throw new EngineError( EngineErrorCode.MalformedPdf, 'the revisions do not share a byte history', ); } try{ const count = fn.EPDFObjectDiff_GetCount(diff); const changes: ObjectChange[] = []; withScratchN( mem, [4, 4, 4, 4, 4, 4], ([numPtr, changePtr, kindPtr, oldGenPtr, newGenPtr, streamPtr]) =>{ for (let i = 0; i < count; i++){ for (const p of [numPtr, changePtr, kindPtr, oldGenPtr, newGenPtr, streamPtr]) mem.poke(p, 'i32', 0); if ( !fn.EPDFObjectDiff_GetEntry( diff, i, numPtr, changePtr, kindPtr, oldGenPtr, newGenPtr, streamPtr, ) ){ throw new EngineError(EngineErrorCode.Unknown, `failed to read diff entry ${ i} `); } const objectNumber = Number(mem.peek(numPtr, 'i32')) >>> 0; const oldGen = Number(mem.peek(oldGenPtr, 'i32')); const newGen = Number(mem.peek(newGenPtr, 'i32')); const oldValue = this.readValue(diff, i, DIFF_OLD); const newValue = this.readValue(diff, i, DIFF_NEW); let truncated = oldValue.truncated || newValue.truncated; let oldParsed = null; let newParsed = null; try{ oldParsed = oldValue.text === null || oldValue.truncated ? null : parsePdfValue(oldValue.text); newParsed = newValue.text === null || newValue.truncated ? null : parsePdfValue(newValue.text); } catch{ truncated = true; } const change = CHANGE_BY_CODE[Number(mem.peek(changePtr, 'i32'))] ?? 'modified'; changes.push({ objectNumber, change, kind: KIND_BY_CODE[Number(mem.peek(kindPtr, 'i32'))] ?? 'scalar', present:{ old: change !== 'added', new: change !== 'freed'} , generation:{ old: oldGen < 0 ? null : oldGen, new: newGen < 0 ? null : newGen} , value:{ old: oldParsed, new: newParsed, truncated} , raw:{ old: oldValue.text, new: newValue.text} , read:{ old: READ_BY_CODE[fn.EPDFObjectDiff_GetReadStatus(diff, i, DIFF_OLD)] ?? 'failed', new: READ_BY_CODE[fn.EPDFObjectDiff_GetReadStatus(diff, i, DIFF_NEW)] ?? 'failed', } , streamDataChanged: Number(mem.peek(streamPtr, 'i32')) !== 0, usage:{ old: [], new: []} , } ); } } , ); return{ changes: this.withAnchoredUsage(diff, changes, before, after), unwritten: unwrittenObjectsToRead({ changes, before, after} ).map((objectNumber) => this.readUnwritten(older, objectNumber), ), health:{ old: this.readHealth(diff, DIFF_OLD), new: this.readHealth(diff, DIFF_NEW)} , } ; } finally{ fn.EPDFObjectDiff_Close(diff); } } private readHealth(diff: Ptr, which: number): RevisionHealth{ const{ fn, mem} = this.runtime; return withScratchN(mem, [4, 4, 4], ([sparsePtr, barePtr, completePtr]) =>{ for (const p of [sparsePtr, barePtr, completePtr]) mem.poke(p, 'i32', 0); if (!fn.EPDFObjectDiff_GetRevisionHealth(diff, which, sparsePtr, barePtr, completePtr)){ throw new EngineError(EngineErrorCode.Unknown, 'failed to read revision health'); } return{ sparseXref: Number(mem.peek(sparsePtr, 'i32')) !== 0, bareReferences: Number(mem.peek(barePtr, 'i32')) >>> 0, referrersComplete: Number(mem.peek(completePtr, 'i32')) !== 0, } ; } ); } private withAnchoredUsage( diff: Ptr, changes: ObjectChange[], before: RevisionStructure, after: RevisionStructure, ): ObjectChange[]{ const changed = new Set(changes.map((c) => c.objectNumber)); const resolvers ={ old: new EdgeResolver( (n) => this.readReferrers(diff, DIFF_OLD, n), anchorSet(before, changed), ), new: new EdgeResolver( (n) => this.readReferrers(diff, DIFF_NEW, n), anchorSet(after, changed), ), } ; return changes.map((c) =>{ const old = c.present.old ? resolvers.old.resolve(c.objectNumber) : []; const now = c.present.new ? resolvers.new.resolve(c.objectNumber) : []; const incomplete = old === USAGE_INCOMPLETE || now === USAGE_INCOMPLETE; return{ ...c, usage:{ old: old === USAGE_INCOMPLETE ? [] : old, new: now === USAGE_INCOMPLETE ? [] : now, } , ...(incomplete ?{ usageIncomplete: true} :{ } ), } ; } ); } private readUnwritten(revision: Ptr, objectNumber: number): UnwrittenObject{ const{ fn, mem} = this.runtime; return withScratchN(mem, [4, 4], ([statusPtr, truncPtr]) =>{ const call = (buffer: Ptr, capacity: number): number =>{ mem.poke(statusPtr, 'i32', -1); mem.poke(truncPtr, 'i32', 0); return fn.EPDFDoc_GetLoadedObjectValue( revision, objectNumber, buffer, capacity, statusPtr, truncPtr, ); } ; const gap = (read: ObjectReadStatus): UnwrittenObject => ({ objectNumber, value: null, read, } ); const length = call(NULL_PTR, 0); const read = READ_BY_CODE[Number(mem.peek(statusPtr, 'i32'))] ?? 'failed'; const truncated = Number(mem.peek(truncPtr, 'i32')) !== 0; if (read !== 'ok' || truncated || length <= 0) return gap(read); return withScratch(mem, length, (buffer) =>{ const written = call(buffer, length); if (written <= 0 || Number(mem.peek(truncPtr, 'i32')) !== 0) return gap(read); const bytes = mem.readBytes(buffer, written - 1); let text = ''; for (const b of bytes) text += String.fromCharCode(b); try{ return{ objectNumber, value: parsePdfValue(text), read} ; } catch{ return gap(read); } } ); } ); } private readValue( diff: Ptr, index: number, which: number, ):{ text: string | null; truncated: boolean} { const{ fn, mem} = this.runtime; return withScratch(mem, 4, (truncPtr) =>{ mem.poke(truncPtr, 'i32', 0); const length = fn.EPDFObjectDiff_GetValue(diff, index, which, NULL_PTR, 0, truncPtr); const truncatedProbe = Number(mem.peek(truncPtr, 'i32')) !== 0; if (length <= 0) return{ text: null, truncated: truncatedProbe} ; return withScratch(mem, length, (buf) =>{ mem.poke(truncPtr, 'i32', 0); const written = fn.EPDFObjectDiff_GetValue(diff, index, which, buf, length, truncPtr); const truncated = Number(mem.peek(truncPtr, 'i32')) !== 0; if (written <= 0) return{ text: null, truncated} ; const bytes = mem.readBytes(buf, written - 1); let text = ''; for (const b of bytes) text += String.fromCharCode(b); return{ text, truncated} ; } ); } ); } private readReferrers(diff: Ptr, which: number, objectNumber: number): ObjectReferrer[]{ const{ fn, mem} = this.runtime; const count = fn.EPDFObjectDiff_GetReferrerCount(diff, which, objectNumber); const out: ObjectReferrer[] = []; if (count <= 0) return out; withScratch(mem, 4, (parentPtr) =>{ for (let k = 0; k < count; k++){ mem.poke(parentPtr, 'i32', 0); const length = fn.EPDFObjectDiff_GetReferrer( diff, which, objectNumber, k, parentPtr, NULL_PTR, 0, ); const label = length <= 0 ? '' : withScratch(mem, length, (buf) =>{ const written = fn.EPDFObjectDiff_GetReferrer( diff, which, objectNumber, k, parentPtr, buf, length, ); if (written <= 0) return ''; const bytes = mem.readBytes(buf, written - 1); let text = ''; for (const b of bytes) text += String.fromCharCode(b); return text; } ); out.push({ parent: Number(mem.peek(parentPtr, 'i32')) >>> 0, label} ); } } ); return out; } } SignatureMutator [ClassDeclaration] (from packages/engine/services/src/features/signature/SignatureMutator.ts): export class SignatureMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, private readonly baseDocuments: BaseDocumentRegistry, private readonly candidatePath?: (basePath: string, signingId: string) => string, ){ } prepare(input: SignaturePrepareInput, authority: ChangeAuthority): SignaturePrepared{ if (this.session.pendingSigning){ throw new EngineError( EngineErrorCode.SigningPending, `a signing is pending (${ this.session.pendingSigning.prepared.signingId} ); complete or cancel it first`, ); } if (!input.field && (input.kind ?? 'signature') !== 'timestamp'){ throw new EngineError( EngineErrorCode.InvalidArg, "a signature needs a `field`: only a document timestamp (`kind: 'timestamp'`) can be given one by the engine", { details:{ field: 'field'} } , ); } const reader = new SignatureReader(this.runtime, this.session); const field = input.field ? reader.resolveField(input.field) : null; const groupId = field ? groupOfField(this.runtime, this.session, field.fieldObjectNumber) : null; if (field) authorizeFieldWrite(authority, groupId, 'sign'); else authorizeCapability(authority, 'doc.sign'); const lock: FieldLockSpec | undefined = input.lock ?? (groupId !== null ?{ action: 'include', fields: groupLockFields(this.runtime, this.session, groupId), } : undefined); if (field?.signed){ throw new EngineError( EngineErrorCode.SignatureRefused, 'the signature field is already signed', ); } if (input.appearance && !field?.widget){ throw new EngineError( EngineErrorCode.SignatureRefused, field ? 'the signature field has no widget to carry an appearance' : 'a timestamp with a field of its own shows nowhere, so it carries no appearance', ); } const algorithm: Exclude = input.digest ?? 'sha256'; if (!(algorithm in DIGEST_CODE) || algorithm === ('sha1' as string)){ throw new EngineError(EngineErrorCode.SignatureRefused, `unsupported digest '${ algorithm} '`); } const kind = input.kind ?? 'signature'; const subFilter: keyof typeof SUBFILTER_CODE = kind === 'timestamp' ? 'ETSI.RFC3161' : (input.subFilter ?? 'ETSI.CAdES.detached'); if (!(subFilter in SUBFILTER_CODE)){ throw new EngineError( EngineErrorCode.SignatureRefused, `unsupported subFilter '${ subFilter} '`, ); } const contentsSize = input.contentsSizeBytes ?? DEFAULT_CONTENTS_SIZE; if ( !Number.isInteger(contentsSize) || contentsSize < MIN_CONTENTS_SIZE || contentsSize > MAX_CONTENTS_SIZE ){ throw new EngineError( EngineErrorCode.SignatureRefused, `contentsSize must be an integer in [${ MIN_CONTENTS_SIZE} , ${ MAX_CONTENTS_SIZE} ]`, ); } const expectedVersion = this.session.versionRef(reader.version().sha256); const signingId = generateUuid(); const stack = new CloseStack(); try{ const candidate = this.openCandidate(signingId, stack); stack.push(() => candidate.close()); const made = field ? null : createTimestampField(this.runtime, candidate.docPtr); const fieldObjectNumber = field ? field.fieldObjectNumber : made!.fieldObjectNumber; const signer = input.signer; const valueObjNum = this.callPrepare(candidate.docPtr, fieldObjectNumber, { subfilter: SUBFILTER_CODE[subFilter], digest: DIGEST_CODE[algorithm], contentsSize, name: signer?.name ?? null, reason: signer?.reason ?? null, location: signer?.location ?? null, contactInfo: signer?.contactInfo ?? null, signingTime: signer?.signedAt !== undefined ? formatPdfDate(signer.signedAt) : null, docmdpPermission: input.certify?.permission ?? 0, fieldmdpAction: lock ? FIELD_ACTION_CODE[lock.action] : 0, fieldmdpFields: lock?.action === 'all' ? [] : (lock?.fields ?? []), lockPermission: lock?.permission ?? 0, } ); if (valueObjNum === 0){ throw new EngineError( EngineErrorCode.SignatureRefused, 'the engine refused to author the signature (the field is signed, read-only or locked, a certification is not allowed here, the seed value requires what is not implemented, or the request is inconsistent)', ); } if (input.appearance && field?.widget){ bakeWidgetAppearance(this.runtime, candidate.docPtr, field.widget, input.appearance.pdf, { recordFit: false, } ); } const store = this.storeFor(); const saved = store.save(candidate.docPtr, valueObjNum, signingId); let sealed; try{ sealed = store.seal(saved, algorithm); } catch (error){ store.discard(saved); throw error; } const prepared: SignaturePrepared ={ signingId, digest: sealed.digest, algorithm, byteRange: sealed.byteRange, contentsSizeBytes: contentsSize, subFilter, expectedVersion, expiresAt: null, ...(made ?{ field:{ kind: 'fqn', name: made.name} } :{ } ), } ; this.session.pendingSigning ={ prepared, fieldObjectNumber, madeField: made !== null, saved, contentsOffset: sealed.contentsOffset, contentsHexLength: sealed.contentsHexLength, } ; return prepared; } finally{ stack.close(); } } complete( input: SignatureCompleteInput, opId: string, authority: ChangeAuthority, ): SignatureCompleteResult{ const pending = this.session.pendingSigning; if (!pending || pending.prepared.signingId !== input.signingId){ const last = this.session.lastCompletion; if (last && last.signingId === input.signingId){ if (!bytesEqual(last.cms, input.cms)){ throw new EngineError( EngineErrorCode.SignatureRefused, 'this signing already completed with a different CMS', ); } return{ ...last.result, status: 'already-completed'} ; } throw new EngineError(EngineErrorCode.NotFound, `no pending signing '${ input.signingId} '`); } if (pending.madeField){ authorizeCapability(authority, 'doc.sign'); } else{ authorizeFieldWrite( authority, groupOfField(this.runtime, this.session, pending.fieldObjectNumber), 'sign', ); } if (!sameVersion(pending.prepared.expectedVersion, input.expectedVersion)){ throw new EngineError( EngineErrorCode.SigningVersionMismatch, 'expectedVersion is not the version the candidate was prepared on', ); } if (input.cms.byteLength === 0 || input.cms[0] !== 0x30){ throw new EngineError(EngineErrorCode.SignatureRefused, 'the CMS is not a DER SEQUENCE'); } if (input.cms.byteLength > pending.prepared.contentsSizeBytes){ throw new EngineError( EngineErrorCode.SignatureRefused, `the CMS (${ input.cms.byteLength} bytes) does not fit the reserved ${ pending.prepared.contentsSizeBytes} bytes`, ); } const store = this.storeFor(); const sealed ={ byteRange: pending.prepared.byteRange, contentsOffset: pending.contentsOffset, contentsHexLength: pending.contentsHexLength, digest: pending.prepared.digest, } ; store.writeContents(pending.saved, sealed, input.cms); const handle = store.openSealed(pending.saved, this.session.password); this.verifySealed(handle, { fieldObjectNumber: pending.fieldObjectNumber, byteRange: pending.prepared.byteRange, cms: input.cms, } ); this.session.install(handle); disposeFormModel(this.runtime, this.session); disposeSignatureModel(this.runtime, this.session); const reader = new SignatureReader(this.runtime, this.session); const snapshot = reader.readSnapshot(); const signature = snapshot.signatures.find( (s) => s.field.kind === 'objectNumber' && s.field.objectNumber === pending.fieldObjectNumber, ); if (!signature){ throw new EngineError( EngineErrorCode.Unknown, 'the installed document lost the signature field', ); } const result: SignatureCompleteResult ={ status: 'completed', signature, version: reader.version(), previous: pending.prepared.expectedVersion, protection: snapshot.protection, meta:{ affectedPages: this.session.allRecords().map((r) => toPageRef(r.pageObjectNumber)), cacheDelta: null, opId, undoable: false, } , } ; this.session.lastCompletion ={ signingId: input.signingId, cms: input.cms.slice(), result} ; return result; } cancel(signingId: string): SignatureCancelResult{ const pending = this.session.pendingSigning; if (pending && pending.prepared.signingId === signingId){ this.session.pendingSigning = null; this.storeFor().discard(pending.saved); return{ status: 'cancelled'} ; } if (this.session.lastCompletion?.signingId === signingId){ return{ status: 'already-completed'} ; } return{ status: 'unknown'} ; } private callPrepare( docPtr: Ptr, fieldObjectNumber: number, opts:{ subfilter: number; digest: number; contentsSize: number; name: string | null; reason: string | null; location: string | null; contactInfo: string | null; signingTime: string | null; docmdpPermission: number; fieldmdpAction: number; fieldmdpFields: string[]; lockPermission: number; } , ): number{ const{ mem, fn} = this.runtime; const layout = this.runtime.kind === 'wasm' ? PREPARE_ILP32 : PREPARE_LP64; const owned: Ptr[] = []; const wide = (value: string | null): Ptr =>{ if (value === null) return NULL_PTR; const ptr = mem.writeU16String(value); owned.push(ptr); return ptr; } ; const utf8 = (value: string | null): Ptr =>{ if (value === null) return NULL_PTR; const ptr = mem.writeU8String(value); owned.push(ptr); return ptr; } ; try{ return withWideStringArray(this.runtime, opts.fieldmdpFields, (fieldsPtr, fieldCount) => withScratch(mem, layout.bytes, (structPtr) =>{ for (let off = 0; off < layout.bytes; off += 4) mem.poke(structPtr, 'i32', 0, off); const pokePtr = (offset: number, ptr: Ptr) =>{ if (layout.ptrBytes === 4) mem.poke(structPtr, 'i32', Number(ptr), offset); else mem.poke(structPtr, 'i64', ptr, offset); } ; mem.poke(structPtr, 'i32', opts.subfilter, layout.subfilter); mem.poke(structPtr, 'i32', opts.digest, layout.digest); mem.poke(structPtr, 'i32', opts.contentsSize, layout.contentsSize); pokePtr(layout.name, wide(opts.name)); pokePtr(layout.reason, wide(opts.reason)); pokePtr(layout.location, wide(opts.location)); pokePtr(layout.contactInfo, wide(opts.contactInfo)); pokePtr(layout.signingTime, utf8(opts.signingTime)); mem.poke(structPtr, 'i32', opts.docmdpPermission, layout.docmdpPermission); mem.poke(structPtr, 'i32', opts.fieldmdpAction, layout.fieldmdpAction); pokePtr(layout.fieldmdpFields, fieldCount > 0 ? fieldsPtr : NULL_PTR); mem.poke(structPtr, 'i32', fieldCount, layout.fieldmdpFieldCount); mem.poke(structPtr, 'i32', opts.lockPermission, layout.lockPermission); return fn.EPDFSig_Prepare(docPtr, fieldObjectNumber, structPtr); } ), ); } finally{ for (let i = owned.length - 1; i >= 0; i--) mem.free(owned[i]); } } private storeFor(): CandidateStore{ const base = this.session.source.base; if (base?.kind === 'file'){ return new FileCandidateStore( this.runtime, this.baseDocuments, base.path, this.candidatePath, ); } return new MemoryCandidateStore(this.runtime, this.baseDocuments); } private verifySealed(handle: OpenedPdfDocument, expected: SealExpectation): void{ const{ fn} = this.runtime; try{ const model = fn.EPDFSig_LoadModel(handle.docPtr); if (!model){ throw new EngineError(EngineErrorCode.Unknown, 'the sealed bytes have no signature model'); } try{ assertSealedSignature(this.runtime, handle.docPtr, model, expected); } finally{ fn.EPDFSig_CloseModel(model); } if (this.session.kind !== 'layer'){ this.session.persistLayerArtifact = false; } } catch (error){ handle.close(); throw error; } } private openCandidate(signingId: string, stack: CloseStack): OpenedPdfDocument{ const password = this.session.password; const source = this.session.source; const saver = new DocumentSaver(this.runtime, this.session); const scratch = saver.canWriteScratchFiles() && source.base?.kind === 'file' ? source.base.path : null; if (this.session.kind === 'layer' && source.base && !this.loadedDeltaHoldsSignedBytes()){ const base = this.baseDocuments.retainByKey(source.base.key); if (base){ let layer: LayerSource = source.layer ??{ kind: 'fresh'} ; if (this.session.hasUnsavedEdits()){ if (scratch){ const path = scratchPath(scratch, 'signing', signingId, 'layer'); stack.push(() => this.runtime.fileWrite.removeFile(path)); const saved = saver.saveLayerArtifactToFileEx(path); if (saved.changedSinceLoad){ layer ={ kind: 'artifact-file', path} ; } } else{ const artifact = saver.saveLayerArtifactEx(); if (artifact.changedSinceLoad){ layer ={ kind: 'artifact', bytes: artifact.bytes} ; } } } return openLayerDocument(this.runtime, base, layer, password); } } if (scratch){ const path = scratchPath(scratch, 'signing', signingId, 'base.pdf'); stack.push(() => this.runtime.fileWrite.removeFile(path)); saver.snapshotToFile(path); const base = this.baseDocuments.acquireFileBase({ key: `candidate:${ signingId} `, path, password, } ); return openLayerDocument(this.runtime, base, { kind: 'fresh'} , password); } const candidateBytes = saver.snapshot().bytes; const base = this.baseDocuments.acquireMemoryBase({ key: `candidate:${ signingId} `, bytes: new Uint8Array(candidateBytes), password, } ); return openLayerDocument(this.runtime, base, { kind: 'fresh'} , password); } private loadedDeltaHoldsSignedBytes(): boolean{ const layer = this.session.source.layer; if (!layer || layer.kind === 'fresh') return false; const baseSize = Number(this.runtime.fn.EPDFDoc_GetBaseBytesSize(this.session.requireDocPtr())); const snapshot = new SignatureReader(this.runtime, this.session).readSnapshot(); return snapshot.signatures.some( (s) => s.signed && s.byteRange !== null && s.byteRange[2] + s.byteRange[3] > baseSize, ); } } SignatureReader [ClassDeclaration] (from packages/engine/services/src/features/signature/SignatureReader.ts): export class SignatureReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } readSnapshot(): SignatureSnapshot{ const model = acquireSignatureModel(this.runtime, this.session); const chainValid = this.runtime.fn.EPDFSig_IsRevisionChainValid(model); const signatures = readSignaturesFromModel(this.runtime, model); const revisions = chainValid ? readRevisions(this.runtime, this.session.requireDocPtr(), signatures) : []; return{ chainValid, revisions, signatures, protection: deriveProtection(signatures)} ; } readProtection(): DocumentProtection{ const model = acquireSignatureModel(this.runtime, this.session); return deriveProtection(readSignaturesFromModel(this.runtime, model)); } readContents(ref: FormFieldRef): ArrayBuffer{ const model = acquireSignatureModel(this.runtime, this.session); const index = this.requireSignedIndex(model, ref); return readContentsAt(this.runtime, model, index).buffer as ArrayBuffer; } digest(ref: FormFieldRef, algorithm: DigestAlgorithm): ArrayBuffer{ const model = acquireSignatureModel(this.runtime, this.session); const index = this.requireSignedIndex(model, ref); const range = readByteRange(this.runtime, model, index); if (!range){ throw new EngineError(EngineErrorCode.NotFound, 'signature has no usable /ByteRange'); } return this.digestRange(range, algorithm); } revisionBytes(revisionIndex: number): ArrayBuffer{ const snapshot = this.readSnapshot(); if (!snapshot.chainValid){ throw new EngineError(EngineErrorCode.MalformedPdf, 'revision chain is not valid'); } const revision = snapshot.revisions[revisionIndex]; if (!revision){ throw new EngineError(EngineErrorCode.NotFound, `no revision ${ revisionIndex} `); } return this.readLoadedBytes(0, revision.end); } resolveField(ref: FormFieldRef):{ index: number; fieldObjectNumber: number; signed: boolean; widget: FormWidget | null; } { const{ fn} = this.runtime; const model = acquireSignatureModel(this.runtime, this.session); const index = this.indexOf(model, ref); if (index < 0){ throw new EngineError( EngineErrorCode.NotFound, ref.kind === 'objectNumber' ? `signature field not found: object ${ ref.objectNumber} ` : `signature field not found: "${ ref.name} "`, ); } const widgetObjNum = fn.EPDFSig_GetWidgetObjNum(model, index); return{ index, fieldObjectNumber: fn.EPDFSig_GetFieldObjNum(model, index), signed: fn.EPDFSig_IsSigned(model, index), widget: widgetObjNum > 0 ? formWidget(widgetObjNum, widgetPageRef(fn.EPDFSig_GetWidgetPageObjNum(model, index))) : null, } ; } readSignatureByObjectNumber(fieldObjectNumber: number): Signature{ const snapshot = this.readSnapshot(); const found = snapshot.signatures.find( (s) => s.field.kind === 'objectNumber' && s.field.objectNumber === fieldObjectNumber, ); if (!found){ throw new EngineError( EngineErrorCode.NotFound, `signature field not found: object ${ fieldObjectNumber} `, ); } return found; } loadedBytes(): ArrayBuffer{ const size = Number(this.runtime.fn.EPDFDoc_GetLoadedBytesSize(this.session.requireDocPtr())); return this.readLoadedBytes(0, size); } version(): BaseVersionInfo{ const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const byteLength = Number(fn.EPDFDoc_GetBaseBytesSize(docPtr)); if (byteLength <= 0){ throw new EngineError(EngineErrorCode.DocNotOpen, 'document has no loaded bytes'); } if (this.session.kind === 'layer'){ const sha256 = withScratch(mem, 32, (out) =>{ if (!fn.EPDFLayer_GetBaseSha256(docPtr, out)){ throw new EngineError(EngineErrorCode.Unknown, 'failed to read the base hash'); } return toHex(mem.readBytes(out, 32)); } ); return{ sha256, sizeBytes: byteLength} ; } const cached = this.session.cachedPlainSha256(); if (cached) return{ sha256: cached, sizeBytes: byteLength} ; const digest = new Uint8Array(this.digestRange([0, byteLength, byteLength, 0], 'sha256')); const sha256 = toHex(digest); this.session.rememberPlainSha256(sha256); return{ sha256, sizeBytes: byteLength} ; } private digestRange( range: [number, number, number, number], algorithm: DigestAlgorithm, ): ArrayBuffer{ const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); const outLength = DIGEST_LENGTH[algorithm]; return withScratchN( mem, [4 * U64_BYTES, outLength, U64_BYTES], ([rangePtr, outPtr, lenPtr]) =>{ for (let k = 0; k < 4; k++) pokeU64(mem, rangePtr, range[k], k * U64_BYTES); pokeU64(mem, lenPtr, outLength); const ok = fn.EPDFSig_DigestByteRange( docPtr, rangePtr, DIGEST_CODE[algorithm], outPtr, lenPtr, ); if (!ok){ throw new EngineError( EngineErrorCode.InvalidArg, 'byte range is not within the loaded bytes', ); } const written = Number(mem.peek(lenPtr, 'i32')); return copyOut(mem.readBytes(outPtr, written)); } , ); } readLoadedBytes(offset: number, length: number): ArrayBuffer{ const{ fn, mem} = this.runtime; const docPtr = this.session.requireDocPtr(); if (length === 0) return new ArrayBuffer(0); return withScratch(mem, length, (ptr) =>{ const read = fn.EPDFDoc_ReadLoadedBytes(docPtr, BigInt(offset), ptr, length); if (read !== length){ throw new EngineError(EngineErrorCode.Unknown, 'failed to read the loaded bytes'); } return copyOut(mem.readBytes(ptr, length)); } ); } private indexOf(model: Ptr, ref: FormFieldRef): number{ const{ fn} = this.runtime; if (ref.kind === 'objectNumber'){ return fn.EPDFSig_GetIndexByFieldObjNum(model, ref.objectNumber); } const count = fn.EPDFSig_Count(model); for (let i = 0; i < count; i++){ const name = this.readWide((buf, cap) => fn.EPDFSig_GetFieldName(model, i, buf, cap)); if (name === ref.name) return i; } return -1; } private requireSignedIndex(model: Ptr, ref: FormFieldRef): number{ const{ fn} = this.runtime; const index = this.indexOf(model, ref); if (index < 0){ throw new EngineError( EngineErrorCode.NotFound, ref.kind === 'objectNumber' ? `signature field not found: object ${ ref.objectNumber} ` : `signature field not found: "${ ref.name} "`, ); } if (!fn.EPDFSig_IsSigned(model, index)){ throw new EngineError(EngineErrorCode.NotFound, 'signature field is not signed'); } return index; } private readString(model: Ptr, index: number, key: number): string | null{ return this.readWide((buf, cap) => this.runtime.fn.EPDFSig_GetString(model, index, key, buf, cap), ); } private readWide(call: (buf: Ptr, capacity: number) => number): string | null{ return readUtf16String(this.runtime.mem, call, ''); } } StartupFontSpec [InterfaceDeclaration] (from packages/engine/services/src/features/fonts/FontRegistrar.ts): export interface StartupFontSpec{ key: string; path: string; familyName?: string; weight?: number; italic?: boolean; fallback?: boolean; tier?: FallbackTier; serve?: boolean; builtIn?: boolean; } UndoUnavailableReason [TypeAliasDeclaration] (from packages/engine/services/src/features/changes/ChangeLedger.ts): export type UndoUnavailableReason = 'final-change' | 'expired'; ValidationInfoMutator [ClassDeclaration] (from packages/engine/services/src/features/signature/ValidationInfoMutator.ts): export class ValidationInfoMutator{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } add(input: Partial, signal: AbortSignal): ValidationInfoAddResult{ throwIfAborted(signal); for (const kind of VALIDATION_INFO_KINDS){ (input[kind] ?? []).forEach((entry, index) =>{ const problem = validationInfoEntryProblem(entry); if (problem){ throw new EngineError(EngineErrorCode.InvalidArg, `${ kind} [${ index} ]: ${ problem} `, { details:{ field: `${ kind} [${ index} ]`} , } ); } } ); } const docPtr = this.session.requireDocPtr(); const held = readValidationStore(this.runtime, docPtr); const added: ValidationInfoCounts ={ certificates: 0, ocspResponses: 0, crls: 0} ; for (const kind of VALIDATION_INFO_KINDS){ for (const entry of input[kind] ?? []){ throwIfAborted(signal); if (holds(held, kind, entry)) continue; addToValidationStore(this.runtime, docPtr, kind, entry); held[kind].push(entry); added[kind] += 1; } } return{ added, meta:{ affectedPages: [], cacheDelta: null, ...this.session.writeStamp()} , } ; } } ValidationInfoReader [ClassDeclaration] (from packages/engine/services/src/features/signature/ValidationInfoReader.ts): export class ValidationInfoReader{ constructor( private readonly runtime: PdfRuntimeModule, private readonly session: DocumentSession, ){ } read(): ValidationInfo{ return readValidationStore(this.runtime, this.session.requireDocPtr()); } } WorkerEncodedImage [InterfaceDeclaration] (from packages/engine/services/src/worker-host/WorkerHost.ts): export interface WorkerEncodedImage{ mimeType: string; bytes: Uint8Array; } WorkerHost [ClassDeclaration] (from packages/engine/services/src/worker-host/WorkerHost.ts): export class WorkerHost{ private readonly sessions = new Map(); private readonly baseDocuments: BaseDocumentRegistry; private readonly aborts = new Map(); private readonly fontIds = new Map(); private readonly fonts: FontRegistrar; private readonly residency: PageResidency; private readonly decodedImages: DecodedImageStore; private readonly slices: Slices; private busy = false; private readonly held: PageSpaceJob[] = []; private destroyed = false; constructor( private readonly runtime: PdfRuntimeModule, private readonly post: (pack: WirePack) => void, private readonly options: WorkerHostOptions ={ } , ){ ensureInitialized(this.runtime); this.baseDocuments = new BaseDocumentRegistry(this.runtime); this.fonts = new FontRegistrar(this.runtime, this.fontIds); this.residency = new PageResidency( this.runtime, { ...DEFAULT_PAGE_RESIDENCY_POLICY, budgetBytes: this.options.parsedPageBudgetBytes ?? DEFAULT_PAGE_RESIDENCY_POLICY.budgetBytes, } , () => this.busy, ); this.decodedImages = new DecodedImageStore(this.runtime, this.options.decodedImageBudgetBytes); this.slices ={ budgetMs: this.options.sliceMs ?? DEFAULT_SLICE_MS, between: createEventLoopYield(), } ; } registerStartupFonts(specs: readonly StartupFontSpec[]): void{ this.fonts.registerStartup(specs); } receive(msg: WorkerRequest): void{ if (msg.kind === 'abort'){ this.abort(msg.jobId); return; } if (msg.kind === 'pages.workingSet'){ this.setWorkingSet(msg); return; } if (this.busy || this.held.length > 0){ this.held.push(msg); return; } this.run(msg); } private setWorkingSet(msg: PagesWorkingSetWorkerRequest): void{ const session = this.sessions.get(sessionKey(msg.docId, msg.layerName)); if (!session?.isOpen()) return; session.pagePool().setWorkingSet( msg.view, msg.pages.map(({ page, role, pixels} ) => ({ pageObjectNumber: page.objectNumber, role, pixels, } )), ); } private abort(jobId: WorkerJobId): void{ const index = this.held.findIndex((msg) => msg.jobId === jobId); if (index < 0){ this.aborts.get(jobId)?.abort(); return; } this.held.splice(index, 1); const error = serializeError(new AbortError('aborted before it ran')); this.post(wirePack({ kind: 'reject', jobId, error} , EMPTY_TRANSFER)); } private drain(): void{ while (!this.busy){ const next = this.takeHeld(); if (!next) return; this.run(next); } } private takeHeld(): PageSpaceJob | undefined{ const first = this.held[0]; if (!first || !isPageRender(first)) return this.held.shift(); let next = 0; let best = first; for (let i = 1; i < this.held.length; i++){ const candidate = this.held[i]!; if (!isPageRender(candidate)) break; if (this.pageIsKept(candidate) && !this.pageIsKept(best)){ next = i; best = candidate; } } this.held.splice(next, 1); return best; } private pageIsKept(msg: HeldPageRender): boolean{ if (!('docId' in msg)) return false; const session = this.sessions.get(sessionKey(msg.docId, msg.layerName)); if (!session) return false; try{ return session.pagePool().isKept(session.resolvePageRef(msg.page).pageObjectNumber); } catch{ return false; } } private run(job: PageSpaceJob): void{ const effect = pageEffectOf(job); this.closePagesChangedBy(job, effect); this.decodedImages.beginJob(effect === 'none'); let msg: FileSpaceJob; try{ msg = requestInFileSpace(job, this.visibleBoxesFor(job)); } catch (err){ this.post( wirePack({ kind: 'reject', jobId: job.jobId, error: serializeError(err)} , EMPTY_TRANSFER), ); return; } const sliced = this.slicedWork(msg); if (sliced){ void this.runSliced(job, msg, effect, sliced); return; } const ctrl = new AbortController(); this.aborts.set(msg.jobId, ctrl); let resultPack: WirePack>; const transacted = this.transactedSession(msg); try{ this.assertNoPendingSigning(msg); if (this.options.reportEveryFontChange){ const written = this.sessionWrittenBy(msg); if (written) trackFontChanges(this.runtime, written); } if (transacted && writesDocument(msg)) transacted.beginTransaction(msg.opId); this.writingSession(msg)?.clearMissingCharacters(); if (transacted && 'objectNumberFloor' in msg && msg.objectNumberFloor !== undefined){ transacted.raiseLastObjectNumber(msg.objectNumberFloor - 1); } switch (msg.kind){ case 'open.fatMem': case 'open.layerMemBase': case 'open.layerFileBase': resultPack = this.handleOpen(msg); break; case 'metadata.read': resultPack = this.handleMetadataRead(msg, ctrl.signal); break; case 'metadata.update': resultPack = this.handleMetadataUpdate(msg, ctrl.signal); break; case 'metadata.readCustom': resultPack = this.handleMetadataReadCustom(msg, ctrl.signal); break; case 'metadata.updateCustom': resultPack = this.handleMetadataUpdateCustom(msg, ctrl.signal); break; case 'actions.read': resultPack = this.handleActionsRead(msg, ctrl.signal); break; case 'outline.read': resultPack = this.handleOutlineRead(msg, ctrl.signal); break; case 'annotations.list': resultPack = this.handleAnnotationsList(msg, ctrl.signal); break; case 'annotations.create': resultPack = this.handleAnnotationsCreate(msg, ctrl.signal); break; case 'annotations.update': resultPack = this.handleAnnotationsUpdate(msg, ctrl.signal); break; case 'annotations.delete': resultPack = this.handleAnnotationsDelete(msg, ctrl.signal); break; case 'annotations.reorder': resultPack = this.handleAnnotationsReorder(msg, ctrl.signal); break; case 'document.apply': resultPack = this.handleDocumentApply(msg, ctrl.signal); break; case 'document.applyChanges': resultPack = this.handleDocumentApplyChanges(msg, ctrl.signal); break; case 'signatures.list': resultPack = this.handleSignaturesList(msg); break; case 'signatures.contents': resultPack = this.handleSignaturesContents(msg); break; case 'signatures.digest': resultPack = this.handleSignaturesDigest(msg); break; case 'signatures.revisionBytes': resultPack = this.handleSignaturesRevisionBytes(msg); break; case 'document.version': resultPack = this.handleDocumentVersion(msg); break; case 'signatures.prepare': resultPack = this.handleSignaturesPrepare(msg); break; case 'signatures.complete': resultPack = this.handleSignaturesComplete(msg); break; case 'signatures.cancel': resultPack = this.handleSignaturesCancel(msg); break; case 'signatures.validationInfo': resultPack = this.handleSignaturesValidationInfo(msg); break; case 'signatures.addValidationInfo': resultPack = this.handleSignaturesAddValidationInfo(msg, ctrl.signal); break; case 'signatures.analyze': resultPack = this.handleSignaturesAnalyze(msg); break; case 'signatures.finalizeCandidate': resultPack = this.handleSignaturesFinalizeCandidate(msg); break; case 'forms.list': resultPack = this.handleFormsList(msg, ctrl.signal); break; case 'forms.setValue': resultPack = this.handleFormsSetValue(msg, ctrl.signal); break; case 'forms.reset': resultPack = this.handleFormsReset(msg, ctrl.signal); break; case 'forms.export': resultPack = this.handleFormsExport(msg, ctrl.signal); break; case 'forms.import': resultPack = this.handleFormsImport(msg, ctrl.signal); break; case 'forms.importValues': resultPack = this.handleFormsImportValues(msg, ctrl.signal); break; case 'forms.repair': resultPack = this.handleFormsRepair(msg, ctrl.signal); break; case 'forms.createField': resultPack = this.handleFormsCreateField(msg, ctrl.signal); break; case 'forms.updateField': resultPack = this.handleFormsUpdateField(msg, ctrl.signal); break; case 'forms.setSignatureAppearance': resultPack = this.handleFormsSetSignatureAppearance(msg, ctrl.signal); break; case 'forms.deleteField': resultPack = this.handleFormsDeleteField(msg, ctrl.signal); break; case 'forms.addWidget': resultPack = this.handleFormsAddWidget(msg, ctrl.signal); break; case 'forms.detachWidget': resultPack = this.handleFormsDetachWidget(msg, ctrl.signal); break; case 'forms.updateWidget': resultPack = this.handleFormsUpdateWidget(msg, ctrl.signal); break; case 'forms.deleteWidget': resultPack = this.handleFormsDeleteWidget(msg, ctrl.signal); break; case 'forms.reorderWidgets': resultPack = this.handleFormsReorderWidgets(msg, ctrl.signal); break; case 'forms.reorderCalculations': resultPack = this.handleFormsReorderCalculations(msg, ctrl.signal); break; case 'pages.list': resultPack = this.handlePagesList(msg, ctrl.signal); break; case 'pages.setName': resultPack = this.handlePagesSetName(msg, ctrl.signal); break; case 'annotations.flatten': resultPack = this.handleAnnotationsFlatten(msg, ctrl.signal); break; case 'annotations.exportAppearance': resultPack = this.handleAnnotationsExportAppearance(msg, ctrl.signal); break; case 'annotations.readAppearance': resultPack = this.handleAnnotationsReadAppearance(msg, ctrl.signal); break; case 'annotations.export': resultPack = this.handleAnnotationsExport(msg, ctrl.signal); break; case 'annotations.import': resultPack = this.handleAnnotationsImport(msg, ctrl.signal); break; case 'pages.removeName': resultPack = this.handlePagesRemoveName(msg, ctrl.signal); break; case 'pages.flatten': resultPack = this.handlePagesFlatten(msg, ctrl.signal); break; case 'redaction.apply': resultPack = this.handleRedactionApply(msg, ctrl.signal); break; case 'pages.extract': resultPack = this.handlePagesExtract(msg, ctrl.signal); break; case 'attachments.list': resultPack = this.handleAttachmentsList(msg, ctrl.signal); break; case 'attachments.readFile': resultPack = this.handleAttachmentsReadFile(msg, ctrl.signal); break; case 'measure.setScale': resultPack = this.handleMeasureSetScale(msg, ctrl.signal); break; case 'pieceInfo.read': resultPack = this.handlePieceInfoRead(msg, ctrl.signal); break; case 'pieceInfo.update': resultPack = this.handlePieceInfoUpdate(msg, ctrl.signal); break; case 'pieceInfo.applications': resultPack = this.handlePieceInfoApplications(msg, ctrl.signal); break; case 'pieceInfo.delete': resultPack = this.handlePieceInfoDelete(msg, ctrl.signal); break; case 'document.saveBuffer': resultPack = this.handleDocumentSaveBuffer(msg); break; case 'document.saveLayerBuffer': resultPack = this.handleDocumentSaveLayerBuffer(msg); break; case 'document.saveFile': resultPack = this.handleDocumentSaveFile(msg); break; case 'document.probeSecurityFile': resultPack = this.handleDocumentProbeSecurityFile(msg); break; case 'document.checkPasswordPermissions': resultPack = this.handleDocumentCheckPasswordPermissions(msg); break; case 'fonts.register': resultPack = this.handleFontsRegister(msg); break; case 'fonts.addFallback': resultPack = this.handleFontsAddFallback(msg); break; case 'fonts.clearFallbacks': resultPack = this.handleFontsClearFallbacks(msg); break; case 'fonts.clear': resultPack = this.handleFontsClear(msg); break; case 'fonts.authorizeEditing': resultPack = this.handleFontsAuthorizeEditing(msg); break; case 'fonts.list': resultPack = wirePack({ tag: 'fonts.list', engineFonts: this.fonts.engineFontFacts(), fallbacks: this.fonts.fallbackKeys(), } ); break; case 'fonts.program': resultPack = this.handleFontsProgram(msg); break; case 'document.setFontSettings': resultPack = this.handleDocumentSetFontSettings(msg); break; case 'document.fonts.list': resultPack = this.handleDocumentFontsList(msg); break; case 'document.fonts.resolve': resultPack = this.handleDocumentFontsResolve(msg); break; case 'document.fonts.program': resultPack = this.handleDocumentFontsProgram(msg); break; case 'objectNumbers.reserve': resultPack = wirePack({ tag: 'objectNumbers.reserve', range: this.requireSession(msg).reserveObjectNumbers(msg.count), } ); break; case 'layer.close': resultPack = this.handleLayerClose(msg); break; case 'close': resultPack = this.handleClose(msg); break; case 'shutdown': resultPack = this.handleShutdown(msg); break; default: throw new EngineError( EngineErrorCode.InvalidArg, `unknown request kind: ${ (msg as WorkerRequest).kind} `, ); } if (transacted?.inTransaction()) transacted.commitTransaction(); this.resolve(msg, resultPack); } catch (err){ if (transacted?.inTransaction()) transacted.abortTransaction(); const error: SerializedEngineError = serializeError(err); this.post(wirePack({ kind: 'reject', jobId: msg.jobId, error} , EMPTY_TRANSFER)); } finally{ this.aborts.delete(msg.jobId); this.closePagesChangedBy(job, effect); } } private writingSession(msg: FileSpaceJob): DocumentSession | undefined{ if (!writesDocument(msg) || !('docId' in msg)) return undefined; const layerName = 'layerName' in msg ? msg.layerName : undefined; const session = this.sessions.get(sessionKey(msg.docId, layerName)); return session?.isOpen() ? session : undefined; } private sessionWrittenBy(msg: FileSpaceJob): DocumentSession | undefined{ if (!('docId' in msg) || (msg.effect !== 'write' && msg.effect !== 'contentWrite')){ return undefined; } const layerName = 'layerName' in msg ? msg.layerName : undefined; const session = this.sessions.get(sessionKey(msg.docId, layerName)); return session?.isOpen() ? session : undefined; } private transactedSession(msg: FileSpaceJob): DocumentSession | undefined{ if (!writesDocument(msg)) return undefined; const layerName = 'layerName' in msg ? msg.layerName : undefined; const session = this.sessions.get(sessionKey(msg.docId, layerName)); if (!session?.isOpen() || session.kind !== 'layer') return undefined; session.assertUsable(); return session; } private closePagesChangedBy(job: PageSpaceJob, effect: PageEffect): void{ if (effect === 'runtime'){ this.residency.closeIdle(); return; } if (effect !== 'document' || !('docId' in job)) return; const layerName = 'layerName' in job ? job.layerName : undefined; this.sessions.get(sessionKey(job.docId, layerName))?.pagePool().closeIdle(); } private resolve(msg: FileSpaceJob, pack: WirePack>): void{ const result = resultInPageSpace(pack.payload, this.visibleBoxesFor(msg)); this.post(wirePack({ kind: 'resolve', jobId: msg.jobId, result} , pack.transfer)); } private visibleBoxesFor(msg: PageSpaceJob | FileSpaceJob): VisibleBoxOf{ let read: VisibleBoxOf | null = null; return (page) =>{ if (!('docId' in msg)){ throw new EngineError(EngineErrorCode.InvalidArg, `${ msg.kind} has no document`); } read ??= visibleBoxReader(this.runtime, this.requireSession(msg)); return read(page); } ; } private handleOpen(req: OpenWorkerRequest): WirePack>{ const key = sessionKey(req.docId, req.kind === 'open.fatMem' ? undefined : req.layerName); if (this.sessions.has(key)){ throw new EngineError(EngineErrorCode.InvalidArg, `document session already open: ${ key} `); } const session = new DocumentSession(this.runtime); session.residency = this.residency; session.signedDocumentPolicy = req.signedDocumentPolicy ?? 'protect'; session.password = req.password; session.objectNumberAuthority = req.objectNumbers ?? 'session'; let load: (password: string | null) => void; if (req.kind === 'open.fatMem'){ const bytes = new Uint8Array(req.bytes); load = (password) => this.openBytesAsLayer(session, bytes, password); } else if (req.kind === 'open.layerMemBase'){ const baseBytes = new Uint8Array(req.baseBytes); load = (password) =>{ const base = this.baseDocuments.acquireMemoryBase({ key: req.baseKey, bytes: baseBytes, password, knownSha256: req.baseSha256, } ); session.openFromHandle(openLayerDocument(this.runtime, base, req.layer, password)); } ; } else{ if (this.runtime.kind !== 'native'){ throw new EngineError( EngineErrorCode.NotImplemented, "'layerFile' needs the native Node runtime; open the file's bytes instead", ); } load = (password) =>{ const base = this.baseDocuments.acquireFileBase({ key: req.baseKey, path: req.basePath, password, knownSha256: req.baseSha256, } ); session.openFromHandle(openLayerDocument(this.runtime, base, req.layer, password)); } ; } try{ load(req.password); } catch (error){ if (!isPasswordOpenError(error)) throw error; session.parkLocked(load); this.sessions.set(key, session); return wirePack({ tag: 'open', docId: req.docId, security: passwordRequiredProbe(), ...(req.password ?{ passwordRejected: true} :{ } ), } ); } this.sessions.set(key, session); return wirePack({ tag: 'open', docId: req.docId, security: new SecurityReader(this.runtime).checkPasswordPermissions( session, req.password ?? '', ), protection: this.probeProtection(session), ...(req.reserveObjectNumbers ?{ objectNumbers: session.reserveObjectNumbers(req.reserveObjectNumbers)} :{ } ), lastObjectNumber: session.lastObjectNumber(), } ); } private openBytesAsLayer( session: DocumentSession, bytes: Uint8Array, password: string | null, ): void{ const base = this.baseDocuments.acquireMemoryBase({ key: `bytes-open:${ generateUuid()} `, bytes, password, } ); session.openFromHandle(openLayerDocument(this.runtime, base, { kind: 'fresh'} , password)); session.persistLayerArtifact = false; } private probeProtection(session: DocumentSession): DocumentProtection | null{ try{ return new SignatureReader(this.runtime, session).readProtection(); } catch{ return null; } } private handleSignaturesList( req: SignaturesListWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const snapshot = req.workingCopy ? new SignatureAnalyzer(this.runtime, session).readWorkingCopySnapshot() : new SignatureReader(this.runtime, session).readSnapshot(); return wirePack({ tag: 'signatures.list', snapshot} ); } private handleSignaturesContents( req: SignaturesContentsWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const bytes = new SignatureReader(this.runtime, session).readContents(req.ref); return wirePack({ tag: 'signatures.contents', bytes} , [bytes]); } private handleSignaturesDigest( req: SignaturesDigestWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const digest = new SignatureReader(this.runtime, session).digest(req.ref, req.algorithm); return wirePack({ tag: 'signatures.digest', digest} , [digest]); } private handleSignaturesRevisionBytes( req: SignaturesRevisionBytesWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const bytes = new SignatureReader(this.runtime, session).revisionBytes(req.revisionIndex); return wirePack({ tag: 'signatures.revisionBytes', bytes, size: bytes.byteLength} , [bytes]); } private handleDocumentVersion( req: DocumentVersionWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const version = new SignatureReader(this.runtime, session).version(); return wirePack({ tag: 'document.version', version} ); } private handleSignaturesPrepare( req: SignaturesPrepareWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const result = new SignatureMutator( this.runtime, session, this.baseDocuments, this.options.signingCandidatePath, ).prepare(req.input, req.authority); return wirePack({ tag: 'signatures.prepare', result, fieldObjectNumber: session.pendingSigning!.fieldObjectNumber, } ); } private handleSignaturesComplete( req: SignaturesCompleteWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const result = new SignatureMutator( this.runtime, session, this.baseDocuments, this.options.signingCandidatePath, ).complete(req.input, req.opId, req.authority); if (result.status === 'already-completed'){ return wirePack({ tag: 'signatures.complete', result} ); } return this.finishMutation(session, { tag: 'signatures.complete', result} , req.artifactPath); } private handleSignaturesValidationInfo( req: SignaturesValidationInfoWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const info = new ValidationInfoReader(this.runtime, session).read(); const ownBuffer = (entry: Uint8Array) => entry.buffer as ArrayBuffer; const certificates = info.certificates.map(ownBuffer); const ocspResponses = info.ocspResponses.map(ownBuffer); const crls = info.crls.map(ownBuffer); return wirePack({ tag: 'signatures.validationInfo', certificates, ocspResponses, crls} , [ ...certificates, ...ocspResponses, ...crls, ]); } private handleSignaturesAddValidationInfo( req: SignaturesAddValidationInfoWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const result = new ValidationInfoMutator(this.runtime, session).add({ certificates: req.certificates.map((entry) => new Uint8Array(entry)), ocspResponses: req.ocspResponses.map((entry) => new Uint8Array(entry)), crls: req.crls.map((entry) => new Uint8Array(entry)), } , signal, ); const payload ={ tag: 'signatures.addValidationInfo' as const, result} ; const wrote = Object.values(result.added).some((count) => count > 0); if (!wrote) return wirePack(payload); return this.finishMutation(session, payload, req.artifactPath); } private handleSignaturesAnalyze( req: SignaturesAnalyzeWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const analysis = new SignatureAnalyzer(this.runtime, session).analyze(req.input); return wirePack({ tag: 'signatures.analyze', analysis} ); } private handleSignaturesFinalizeCandidate( req: SignaturesFinalizeCandidateWorkerRequest, ): WirePack>{ const finalized = new CandidateFinalizer(this.runtime, this.baseDocuments).finalize({ path: req.path, byteRange: req.byteRange, contentsSizeBytes: req.contentsSizeBytes, fieldObjectNumber: req.fieldObjectNumber, cms: new Uint8Array(req.cms), password: req.password ?? null, } ); return wirePack({ tag: 'signatures.finalizeCandidate', ...finalized} ); } private handleSignaturesCancel( req: SignaturesCancelWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const result = new SignatureMutator( this.runtime, session, this.baseDocuments, this.options.signingCandidatePath, ).cancel(req.signingId); return wirePack({ tag: 'signatures.cancel', result} ); } private assertNoPendingSigning(msg: FileSpaceJob): void{ if (!writesDocument(msg)) return; const layerName = 'layerName' in msg ? msg.layerName : undefined; const session = this.sessions.get(sessionKey(msg.docId, layerName)); if (session?.pendingSigning){ throw new EngineError( EngineErrorCode.SigningPending, `a signing is pending (${ session.pendingSigning.prepared.signingId} ); complete or cancel it before mutating the document`, ); } } private handleMetadataRead( req: MetadataReadWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const metadata = new MetadataReader(this.runtime, session).read(signal); return wirePack({ tag: 'metadata.read', metadata} ); } private handleMetadataUpdate( req: MetadataUpdateWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, skipped: _skipped, ...result} = this.applyOne( session, req.opId, { type: 'metadata.update', patch: req.patch} , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'metadata.update', result} , req.artifactPath); } private handleMetadataReadCustom( req: MetadataReadCustomWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const custom = new MetadataReader(this.runtime, session).readCustom(signal); return wirePack({ tag: 'metadata.readCustom', custom} ); } private handleMetadataUpdateCustom( req: MetadataUpdateCustomWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, skipped: _skipped, ...result} = this.applyOne( session, req.opId, { type: 'metadata.updateCustom', patch: req.patch} , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'metadata.updateCustom', result} , req.artifactPath); } private handleActionsRead( req: ActionsReadWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const snapshot = new DocumentActionsReader(this.runtime, session).read(signal); return wirePack({ tag: 'actions.read', snapshot} ); } private handleOutlineRead( req: OutlineReadWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const outline = new OutlineReader(this.runtime, session).read(signal); return wirePack({ tag: 'outline.read', outline} ); } private handleAnnotationsList( req: AnnotationsListWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const pages = req.pages?.map((page) => session.resolvePageRef(page).pageObjectNumber); const reader = new RawAnnotationReader(this.runtime, session, this.fonts); return wirePack({ tag: 'annotations.list', list: reader.list(pages, signal, 'annotations')} ); } private async handleAnnotationsRenderAppearances( req: AnnotationsRenderAppearancesWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const pageObjectNumber = session.resolvePageRef(req.page).pageObjectNumber; const reader = new AnnotationAppearanceReader(this.runtime, session); const result = await reader.render( pageObjectNumber, req.family, req.options ??{ } , signal, this.slices, ); const transfer = result.appearances.map((a) => a.raster.data); return wirePack({ tag: 'annotations.renderAppearances', page: req.page, result} , transfer); } private handleAnnotationsCreate( req: AnnotationsCreateWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, page: _page, ...result} = this.applyOne( session, req.opId, { type: 'annotations.create', page: req.page, data: req.draft, ...(req.resources ?{ resources: req.resources} :{ } ), ...(req.objectNumber !== undefined ?{ objectNumber: req.objectNumber} :{ } ), } , checkedAuthority(req.actor), signal, ); return this.finishMutation(session, { tag: 'annotations.create', result} , req.artifactPath); } private handleAnnotationsUpdate( req: AnnotationsUpdateWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, page: _page, skipped: _skipped, ...result} = this.applyOne( session, req.opId, { type: 'annotations.update', ref: req.ref, patch: req.patch, ...(req.resources ?{ resources: req.resources} :{ } ), } , { ...req.authority, protection: null} , signal, ); return this.finishMutation(session, { tag: 'annotations.update', result} , req.artifactPath); } private handleAnnotationsDelete( req: AnnotationsDeleteWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, page: _page, ...result} = this.applyOne( session, req.opId, { type: 'annotations.delete', ref: req.ref} , { ...req.authority, protection: null} , signal, ); return this.finishMutation(session, { tag: 'annotations.delete', result} , req.artifactPath); } private handleAnnotationsFlatten( req: AnnotationsFlattenWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const pageObjectNumber = session.resolvePageRef(req.page).pageObjectNumber; const result = new AnnotationFlattener(this.runtime, session).flatten( pageObjectNumber, req.refs, req.usage, signal, ); const wrote = result.meta.affectedPages.length > 0; if (!wrote) return wirePack({ tag: 'annotations.flatten', result, wrote} ); return this.finishMutation( session, { tag: 'annotations.flatten', result, wrote} , req.artifactPath, ); } private handleAnnotationsExportAppearance( req: AnnotationsExportAppearanceWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const pageObjectNumber = session.resolvePageRef(req.page).pageObjectNumber; const exported = new AnnotationFlattener(this.runtime, session).exportAppearance( pageObjectNumber, req.refs, signal, ); return wirePack({ tag: 'annotations.exportAppearance', bytes: exported.bytes, size: exported.size} , [exported.bytes], ); } private handleAnnotationsExport( req: AnnotationsExportWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const bundle = new AnnotationExporter(this.runtime, session, this.fonts).export( req.selection, req.limits ?? DEFAULT_BUNDLE_LIMITS, signal, ); return wirePack({ tag: 'annotations.export', bundle} , Object.values(bundle.resources)); } private handleAnnotationsImport( req: AnnotationsImportWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'annotations.import', bundle: req.bundle, ...(req.pages !== undefined ?{ pages: req.pages} :{ } ), attribution: req.attribution, ...(req.actor ?{ actor: req.actor} :{ } ), limits: req.limits ?? DEFAULT_BUNDLE_LIMITS, } , checkedAuthority(req.actor), signal, ); if (result.annotations.length === 0) return wirePack({ tag: 'annotations.import', result} ); return this.finishMutation(session, { tag: 'annotations.import', result} , req.artifactPath); } private handleAnnotationsReadAppearance( req: AnnotationsReadAppearanceWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const pageObjectNumber = session.resolvePageRef(req.page).pageObjectNumber; const drawing = new AnnotationFlattener(this.runtime, session).readAppearance( pageObjectNumber, req.ref, signal, ); return wirePack({ tag: 'annotations.readAppearance', bytes: drawing.bytes, size: drawing.size} , [drawing.bytes], ); } private handleAnnotationsReorder( req: AnnotationsReorderWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, page: _page, ...result} = this.applyOne( session, req.opId, { type: 'annotations.reorder', page: req.page, refs: req.refs, position: req.position} , { ...req.authority, protection: null} , signal, ); return this.finishMutation(session, { tag: 'annotations.reorder', result} , req.artifactPath); } private handleDocumentApply( req: DocumentApplyWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); assertNoImport(req.change); const fingerprint = changeFingerprint(req.change); const prior = changeLedgerOf(session).outcome(req.opId); if (prior){ const result = this.replayed(prior, fingerprint, req.opId); return wirePack({ tag: 'document.apply', result, replayed: true} ); } const result = this.recorded(session, req.opId, fingerprint, () => this.runChange(session, req, signal), ); const payload ={ tag: 'document.apply' as const, result, replayed: false} ; if (!result.items.some(itemWrote)) return wirePack(payload); return this.finishMutation(session, payload, req.artifactPath); } private applyOne>( session: DocumentSession, opId: string, op: Op, authority: ChangeAuthority, signal: AbortSignal, ): Extract, { type: Op['type']} >{ const change ={ ops: [op]} ; const ledger = changeLedgerOf(session); const fingerprint = changeFingerprint(change); const prior = ledger.outcome(opId); let result: ChangeResult; if (prior){ result = this.replayed(prior, fingerprint, opId); } else{ result = this.recorded(session, opId, fingerprint, () => new ChangeApplier(this.runtime, session, this.fonts).apply( change.ops, authority, signal, FILE_SPACE, ), ); } const item = result.items[0]; if (!item || isSkippedItem(item)){ throw new EngineError(EngineErrorCode.Unknown, `${ op.type} wrote nothing`); } return item as Extract, { type: Op['type']} >; } private replayed( prior: ChangeOutcome, fingerprint: string, opId: string, ): ChangeResult{ if (prior.fingerprint !== fingerprint){ throw new EngineError( EngineErrorCode.IdempotencyKeyReused, `opId ${ opId} already answered a different change`, ); } if (prior.kind === 'refused') throw deserializeError(prior.error); return prior.result as ChangeResult; } private recorded( session: DocumentSession, opId: string, fingerprint: string, run: () => AppliedChange, ): ChangeResult{ const ledger = changeLedgerOf(session); try{ const applied = run(); const result = resultOf(session, applied); ledger.keepApplied( opId, fingerprint, result as KeptResult, result.meta.undoable ? applied.record : null, ); return result; } catch (err){ if (EngineError.is(err) && isKeptRefusal(err.code)){ ledger.keepRefused(opId, fingerprint, serializeError(err)); } throw err; } } private handleDocumentApplyChanges( req: DocumentApplyChangesWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); session.assertUsable(); if (req.objectNumberFloor !== undefined){ session.raiseLastObjectNumber(req.objectNumberFloor - 1); } const applier = new ChangeApplier(this.runtime, session, this.fonts, req.limits); const space = this.pageSpaceOf(session); const records = new Map(); const outcomes: ServerChangeOutcome[] = []; for (const entry of req.changes){ session.beginTransaction(entry.opId); try{ const applied = runServerChange(applier, entry, records, signal, space); const result = resultOf(session, applied); session.commitTransaction(); const record = result.meta.undoable ? applied.record : null; records.set(entry.opId, record); outcomes.push({ opId: entry.opId, status: 'applied', result, record} ); } catch (err){ if (session.inTransaction()) session.abortTransaction(); if (!EngineError.is(err) || !isKeptRefusal(err.code)) throw err; records.set(entry.opId, null); outcomes.push({ opId: entry.opId, status: 'refused', error: serializeError(err)} ); } } const payload ={ tag: 'document.applyChanges' as const, outcomes} ; const wrote = outcomes.some( (outcome) => outcome.status === 'applied' && outcome.result.items.some(itemWrote), ); if (!wrote) return wirePack(payload); return this.finishMutation(session, payload, req.artifactPath); } private pageSpaceOf(session: DocumentSession): ChangeSpace{ return{ opInFileSpace: (op) => opInFileSpace(op, visibleBoxReader(this.runtime, session)), itemOut: (item) => itemInPageSpace(item, visibleBoxReader(this.runtime, session)), } ; } private runChange( session: DocumentSession, req: DocumentApplyWorkerRequest, signal: AbortSignal, ): AppliedChange{ const applier = new ChangeApplier(this.runtime, session, this.fonts); const space = this.pageSpaceOf(session); const userId = req.authority.identity.userId ?? null; if (!isUndoChange(req.change)){ return applier.apply(req.change.ops, req.authority, signal, space); } const kept = changeLedgerOf(session).record(req.change.undoOf); if (!kept || 'unavailable' in kept){ throw new EngineError( EngineErrorCode.UndoUnavailable, `change ${ req.change.undoOf} can no longer be undone`, { details:{ reason: kept ? kept.unavailable : 'expired'} } , ); } if (!kept.record) return{ items: [], record:{ userId, steps: []} } ; if (kept.record.userId !== null && kept.record.userId !== userId){ throw new PermissionDenied('changes:undo', 'target'); } return applier.undo(kept.record, req.authority, signal, space); } private handlePagesList( req: PagesListWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const reader = new PagesReader(this.runtime, session); const snapshot = reader.read(signal); return wirePack({ tag: 'pages.list', snapshot} ); } private handlePagesSetName( req: PagesSetNameWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const mutator = new PagesMutator(this.runtime, session); const result = mutator.setName({ name: req.name, page: req.page, ...(req.replace !== undefined ?{ replace: req.replace} :{ } ), } , signal, ); return this.finishMutation(session, { tag: 'pages.setName', result} , req.artifactPath); } private handlePagesRemoveName( req: PagesRemoveNameWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const mutator = new PagesMutator(this.runtime, session); const result = mutator.removeName({ name: req.name} , signal); return this.finishMutation(session, { tag: 'pages.removeName', result} , req.artifactPath); } private handlePagesFlatten( req: PagesFlattenWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const result = new PagesFlattener(this.runtime, session).flatten(req.pages, req.usage, signal); const wrote = result.meta.affectedPages.length > 0; if (!wrote) return wirePack({ tag: 'pages.flatten', result, wrote} ); return this.finishMutation(session, { tag: 'pages.flatten', result, wrote} , req.artifactPath); } private handleRedactionApply( req: RedactionApplyWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const result = new RedactionApplier(this.runtime, session).apply(req.scope, signal); const wrote = result.meta.affectedPages.length > 0; if (!wrote) return wirePack({ tag: 'redaction.apply', result, wrote} ); return this.finishMutation( session, { tag: 'redaction.apply', result, wrote} , req.artifactPath, ); } private handlePagesExtract( req: PagesExtractWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const extracted = new PagesExtractor(this.runtime, session).extract( req.pages, req.flatten, signal, ); return wirePack({ tag: 'pages.extract', bytes: extracted.bytes, size: extracted.size} , [ extracted.bytes, ]); } private handleDocumentFontsList( req: DocumentFontsListWorkerRequest, ): WirePack>{ const session = this.requireSession(req); trackFontChanges(this.runtime, session); const reader = new DocumentFontReader(this.runtime, session, this.fonts); return wirePack({ tag: 'document.fonts.list', facts: reader.facts()} ); } private handleDocumentFontsResolve( req: DocumentFontsResolveWorkerRequest, ): WirePack>{ const reader = new DocumentFontReader(this.runtime, this.requireSession(req), this.fonts); const facts = reader.facts(); const{ runs, missingCharacters} = reader.resolve(req.annotation, req.runs, facts); return wirePack({ tag: 'document.fonts.resolve', runs, missingCharacters, facts} ); } private handleDocumentFontsProgram( req: DocumentFontsProgramWorkerRequest, ): WirePack>{ const reader = new DocumentFontReader(this.runtime, this.requireSession(req), this.fonts); const program = reader.program(req.displaySha256, req.part === 'data'); const bytes = program.bytes ? (program.bytes.buffer.slice( program.bytes.byteOffset, program.bytes.byteOffset + program.bytes.byteLength, ) as ArrayBuffer) : null; return wirePack({ tag: 'document.fonts.program', covers: program.covers, ascent: program.ascent, descent: program.descent, bytes, } , bytes ? [bytes] : [], ); } private handleAttachmentsList( req: AttachmentsListWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const attachments = new AttachmentReader(this.runtime, session).list(signal); return wirePack({ tag: 'attachments.list', attachments} ); } private handleAttachmentsReadFile( req: AttachmentsReadFileWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const content = new AttachmentReader(this.runtime, session).readFile( req.ref, req.path, req.maxDecodedBytes, signal, ); return wirePack({ tag: 'attachments.readFile', content} , content.bytes !== undefined ? [content.bytes] : [], ); } private async handleAnnotationsReadFile( req: AnnotationsReadFileWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const content = await new AttachmentReader(this.runtime, session).readAnnotationFile( session.resolvePageRef(req.page).pageObjectNumber, req.ref, req.path, req.maxDecodedBytes, signal, this.slices, ); return wirePack({ tag: 'annotations.readFile', content} , content.bytes !== undefined ? [content.bytes] : [], ); } private async handleMeasureViewports( req: MeasureViewportsWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const viewports = new MeasureReader(this.runtime, session).viewports( session.resolvePageRef(req.page).pageObjectNumber, signal, ); return wirePack({ tag: 'measure.viewports', page: req.page, viewports} ); } private handleMeasureSetScale( req: MeasureSetScaleWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); new MeasureMutator(this.runtime, session).setScale( session.resolvePageRef(req.page).pageObjectNumber, req.measure, signal, ); return this.finishMutation( session, { tag: 'measure.setScale', result:{ page: req.page, layout: new PagesReader(this.runtime, session).read(signal), meta:{ affectedPages: [], cacheDelta: null, ...session.writeStamp()} , } , } , req.artifactPath, ); } private handlePieceInfoRead( req: PieceInfoReadWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const accessor = new PieceInfoAccessor( this.runtime, session, req.page ? session.resolvePageRef(req.page).pageObjectNumber : undefined, ); const snapshot = accessor.read(req.application, signal); return wirePack({ tag: 'pieceInfo.read', snapshot} ); } private handlePieceInfoUpdate( req: PieceInfoUpdateWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const accessor = new PieceInfoAccessor( this.runtime, session, req.page ? session.resolvePageRef(req.page).pageObjectNumber : undefined, ); accessor.update(req.application, req.patch, signal); const result ={ pieceInfo: accessor.read(req.application, signal), meta:{ affectedPages: [], cacheDelta: null, ...session.writeStamp()} , } ; return this.finishMutation(session, { tag: 'pieceInfo.update', result} , req.artifactPath); } private handlePieceInfoApplications( req: PieceInfoApplicationsWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const accessor = new PieceInfoAccessor( this.runtime, session, req.page ? session.resolvePageRef(req.page).pageObjectNumber : undefined, ); const applications = accessor.applications(signal); return wirePack({ tag: 'pieceInfo.applications', applications} ); } private handlePieceInfoDelete( req: PieceInfoDeleteWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const accessor = new PieceInfoAccessor( this.runtime, session, req.page ? session.resolvePageRef(req.page).pageObjectNumber : undefined, ); accessor.delete(req.application, signal); const result ={ meta:{ affectedPages: [], cacheDelta: null, ...session.writeStamp()} } ; return this.finishMutation(session, { tag: 'pieceInfo.delete', result} , req.artifactPath); } private async handlePagesText( req: PagesTextWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const reader = new PageTextReader(this.runtime, session); const pageObjectNumber = session.resolvePageRef(req.page).pageObjectNumber; const snapshot = await reader.read(pageObjectNumber, signal, this.slices); return wirePack({ tag: 'pages.text', snapshot} ); } private async handlePagesGeometry( req: PagesGeometryWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const reader = new PageGeometryReader(this.runtime, session); const pageObjectNumber = session.resolvePageRef(req.page).pageObjectNumber; const snapshot = await reader.read(pageObjectNumber, signal, this.slices); return wirePack({ tag: 'pages.geometry', page: req.page, snapshot} ); } private async handleSearchQuery( req: SearchQueryWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const reader = new SearchReader(this.runtime, session); const slice = await reader.query(req.request, signal, this.slices); return wirePack({ tag: 'search.query', slice} ); } private async handlePagesRender( req: PagesRenderWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = this.requireSession(req); const reader = new PageRenderReader(this.runtime, session); const{ raster, area} = await reader.render( session.resolvePageRef(req.page).pageObjectNumber, req.options ??{ } , signal, this.slices, ); return wirePack({ tag: 'pages.render', page: req.page, area, raster} , [raster.data]); } private slicedWork(msg: FileSpaceJob): SlicedWork | null{ switch (msg.kind){ case 'pages.render': return{ pdfium: (signal) => this.handlePagesRender(msg, signal)} ; case 'pages.renderEncoded': return{ pdfium: (signal) => this.handlePagesRender({ ...msg, kind: 'pages.render'} , signal), encode: (rendered, signal) => this.encodeRendered(rendered, msg.encode, signal), } ; case 'document.renderPageFile': return{ pdfium: (signal) => this.handleDocumentRenderPageFile(msg, signal)} ; case 'document.renderPageFileEncoded': return{ pdfium: (signal) => this.handleDocumentRenderPageFile({ ...msg, kind: 'document.renderPageFile'} , signal), encode: (rendered, signal) => this.encodeRendered(rendered, msg.encode, signal), } ; case 'annotations.renderAppearances': return{ pdfium: (signal) => this.handleAnnotationsRenderAppearances(msg, signal)} ; case 'annotations.renderAppearancesEncoded': return{ pdfium: (signal) => this.handleAnnotationsRenderAppearances({ ...msg, kind: 'annotations.renderAppearances'} , signal, ), encode: (rendered, signal) => this.encodeAppearances(rendered, msg.page, msg.encode, signal), } ; case 'pages.text': return{ pdfium: (signal) => this.handlePagesText(msg, signal)} ; case 'pages.geometry': return{ pdfium: (signal) => this.handlePagesGeometry(msg, signal)} ; case 'measure.viewports': return{ pdfium: (signal) => this.handleMeasureViewports(msg, signal)} ; case 'annotations.readFile': return{ pdfium: (signal) => this.handleAnnotationsReadFile(msg, signal)} ; case 'search.query': return{ pdfium: (signal) => this.handleSearchQuery(msg, signal)} ; default: return null; } } private async runSliced( job: PageSpaceJob, msg: FileSpaceJob, effect: PageEffect, work: SlicedWork, ): Promise{ if (work.encode && !this.options.imageEncoder){ this.post( wirePack({ kind: 'reject', jobId: msg.jobId, error: noEncoderError()} , EMPTY_TRANSFER), ); return; } const ctrl = new AbortController(); this.aborts.set(msg.jobId, ctrl); this.busy = true; try{ let pdfium: WirePack>; try{ pdfium = await work.pdfium(ctrl.signal); } finally{ this.busy = false; queueMicrotask(() => this.drain()); } this.resolve(msg, work.encode ? await work.encode(pdfium, ctrl.signal) : pdfium); } catch (err){ this.post( wirePack({ kind: 'reject', jobId: msg.jobId, error: serializeError(err)} , EMPTY_TRANSFER), ); } finally{ this.aborts.delete(msg.jobId); this.closePagesChangedBy(job, effect); } } private async encodeRaster( raster: PageRaster, encode: RenderEncode, signal: AbortSignal, ): Promise{ const encoder = this.options.imageEncoder; if (!encoder){ throw new EngineError(EngineErrorCode.NotImplemented, NO_ENCODER_MESSAGE); } const{ bytes, mimeType} = await encoder.encode(raster, encode); if (signal.aborted){ throw new EngineError(EngineErrorCode.Aborted, 'aborted during image encode'); } return{ mimeType, width: raster.width, height: raster.height, bytes} ; } private async encodeRendered( rendered: WirePack>, encode: RenderEncode, signal: AbortSignal, ): Promise>>{ const{ payload} = rendered; if (payload.tag === 'pages.render'){ const image = await this.encodeRaster(payload.raster, encode, signal); return wirePack({ tag: 'pages.renderEncoded', image} , [image.bytes.buffer]); } if (payload.tag === 'document.renderPageFile'){ const image = await this.encodeRaster(payload.raster, encode, signal); return wirePack({ tag: 'document.renderPageFileEncoded', page: payload.page, pageCount: payload.pageCount, image, } , [image.bytes.buffer], ); } throw new EngineError(EngineErrorCode.WireFormat, `unexpected ${ payload.tag} `); } private async encodeAppearances( rendered: WirePack>, page: PageRef, encode: RenderEncode, signal: AbortSignal, ): Promise>>{ if (rendered.payload.tag !== 'annotations.renderAppearances'){ throw new EngineError(EngineErrorCode.WireFormat, `unexpected ${ rendered.payload.tag} `); } const{ appearances} = rendered.payload.result; const encoded: EncodedAppearanceWire[] = []; for (const a of appearances){ encoded.push({ ref: a.ref, mode: a.mode, state: a.state, rect: a.rect, image: await this.encodeRaster(a.raster, encode, signal), } ); } return wirePack({ tag: 'annotations.renderAppearancesEncoded', page, result:{ page: rendered.payload.result.page, appearances: encoded} , } , encoded.map((e) => e.image.bytes.buffer), ); } private assertRewriteKeepsSignatures(session: DocumentSession, mode: PdfSaveMode): void{ if (mode !== 'rewrite' || session.signedDocumentPolicy !== 'protect') return; const protection = this.probeProtection(session); if (protection && protection.judged !== null){ throw new EngineError( EngineErrorCode.ProtectedDocument, 'the document is signed: a rewrite save would void every signature (use an incremental save)', ); } } private handleDocumentSaveBuffer( req: DocumentSaveBufferWorkerRequest, ): WirePack>{ const session = this.requireSession(req); this.assertRewriteKeepsSignatures(session, req.mode); if (req.mode === 'incremental'){ const snap = new DocumentSaver(this.runtime, session).snapshot(); return wirePack({ tag: 'document.saveBuffer', bytes: snap.bytes, size: snap.bytes.byteLength} , [snap.bytes], ); } const saved = new DocumentSaver(this.runtime, session).saveStandaloneToBuffer(req.mode); return wirePack({ tag: 'document.saveBuffer', bytes: saved.bytes, size: saved.size} , [ saved.bytes, ]); } private handleDocumentSaveFile( req: DocumentSaveFileWorkerRequest, ): WirePack>{ const session = this.requireSession(req); this.assertRewriteKeepsSignatures(session, req.mode); const unchanged = req.mode === 'incremental' && (!session.hasUnsavedEdits() || new DocumentSaver(this.runtime, session).saveStandaloneToFileEx(req.path, req.mode) .unchangedSinceLoad); if (unchanged){ new DocumentSaver(this.runtime, session).copyLoadedBytesToFile(req.path); return wirePack({ tag: 'document.saveFile', path: req.path} ); } if (req.mode === 'incremental'){ return wirePack({ tag: 'document.saveFile', path: req.path} ); } const saved = new DocumentSaver(this.runtime, session).saveStandaloneToFile(req.path, req.mode); return wirePack({ tag: 'document.saveFile', path: saved.path} ); } private handleDocumentSaveLayerBuffer( req: DocumentSaveLayerBufferWorkerRequest, ): WirePack>{ const session = this.requireSession(req); if (session.kind !== 'layer'){ throw new EngineError( EngineErrorCode.InvalidArg, 'document has no layer to export (opened without a layer)', ); } const artifact = new DocumentSaver(this.runtime, session).saveLayerArtifact(); return wirePack({ tag: 'document.saveLayerBuffer', bytes: artifact.bytes, size: artifact.size} , [artifact.bytes], ); } private handleDocumentProbeSecurityFile( req: DocumentProbeSecurityFileWorkerRequest, ): WirePack>{ const reader = new SecurityReader(this.runtime); const security = reader.probeFile(req.path, req.password); return wirePack({ tag: 'document.probeSecurityFile', security} ); } private async handleDocumentRenderPageFile( req: DocumentRenderPageFileWorkerRequest, signal: AbortSignal, ): Promise>>{ const session = new DocumentSession(this.runtime); const base = this.baseDocuments.acquireFileBase({ key: `adhoc-file:${ req.path} `, path: req.path, password: req.password, } ); try{ session.openFromHandle( openLayerDocument(this.runtime, base, { kind: 'fresh'} , req.password), ); const layout = new PagesReader(this.runtime, session).read(signal); const page = layout.pages[req.pageIndex]; if (!page){ throw new EngineError( EngineErrorCode.NotFound, `renderPageFile: no page at index ${ req.pageIndex} (pageCount=${ layout.pageCount} )`, ); } const{ raster} = await new PageRenderReader(this.runtime, session).render( page.ref.objectNumber, renderOptionsInFileSpace(req.options ??{ } , () => page.pdfCropBox), signal, this.slices, ); return wirePack({ tag: 'document.renderPageFile', page: page.ref, pageCount: layout.pageCount, raster, } , [raster.data], ); } finally{ session.close(); } } private handleDocumentCheckPasswordPermissions( req: DocumentCheckPasswordPermissionsWorkerRequest, ): WirePack>{ const parked = this.sessions.get(sessionKey(req.docId)); let session: DocumentSession; if (parked?.isLocked()){ parked.unlockWith(req.password); parked.password = req.password; session = parked; } else{ session = this.requireSession(req); } const security = new SecurityReader(this.runtime).checkPasswordPermissions( session, req.password, req.mode ?? 'any', ); return wirePack({ tag: 'document.checkPasswordPermissions', security, protection: this.probeProtection(session), } ); } private handleFontsRegister( req: FontsRegisterWorkerRequest, ): WirePack>{ this.fonts.register( req.fontKey, req.familyName, req.weight, req.italic, new Uint8Array(req.data), req.builtIn ?? false, ); return wirePack({ tag: 'fonts.register', fontKey: req.fontKey, identity: this.fonts.describe(req.fontKey), } ); } private handleFontsAuthorizeEditing( req: FontsAuthorizeEditingWorkerRequest, ): WirePack>{ return wirePack({ tag: 'fonts.authorizeEditing', identity: this.fonts.authorizeEditing(req.fontKey), } ); } private handleDocumentSetFontSettings( req: DocumentSetFontSettingsWorkerRequest, ): WirePack>{ const session = this.requireSession(req); const docPtr = session.requireDocPtr(); const{ fn} = this.runtime; if (req.embeddingPolicy !== undefined){ const code ={ default: 0, subset: 1, full: 2} [req.embeddingPolicy]; if (!fn.EPDFDoc_SetFontEmbeddingPolicy(docPtr, code)){ throw new EngineError(EngineErrorCode.InvalidArg, 'EPDFDoc_SetFontEmbeddingPolicy failed'); } } if (req.typographicFeatures !== undefined){ if (!fn.EPDFDoc_SetTypographicFeatures(docPtr, req.typographicFeatures)){ throw new EngineError(EngineErrorCode.InvalidArg, 'EPDFDoc_SetTypographicFeatures failed'); } } return wirePack({ tag: 'document.setFontSettings'} ); } private handleFontsAddFallback( req: FontsAddFallbackWorkerRequest, ): WirePack>{ this.fonts.addFallback(req.fontKey, req.tier); return wirePack({ tag: 'fonts.addFallback'} ); } private handleFontsClearFallbacks( _req: FontsClearFallbacksWorkerRequest, ): WirePack>{ this.fonts.clearFallbacks(); return wirePack({ tag: 'fonts.clearFallbacks'} ); } private handleFontsProgram( req: FontsProgramWorkerRequest, ): WirePack>{ const served = this.fonts .engineFontFacts() .some((font) => font.sha256 === req.sha256 && font.served); const program = served ? this.fonts.programFor(req.sha256) : undefined; if (!program){ throw new EngineError( EngineErrorCode.NotFound, `no served font has the program ${ req.sha256} `, ); } const bytes = program.bytes(); const buffer = bytes.buffer.slice( bytes.byteOffset, bytes.byteOffset + bytes.byteLength, ) as ArrayBuffer; return wirePack({ tag: 'fonts.program', bytes: buffer} , [buffer]); } private handleFontsClear( _req: FontsClearWorkerRequest, ): WirePack>{ this.fonts.clear(); return wirePack({ tag: 'fonts.clear'} ); } private handleLayerClose( req: LayerCloseWorkerRequest, ): WirePack>{ const key = sessionKey(req.docId, req.layerName); const session = this.sessions.get(key); if (session){ disposeFormModel(this.runtime, session); disposeSignatureModel(this.runtime, session); session.close(); this.sessions.delete(key); } return wirePack({ tag: 'close'} ); } private handleClose(req: CloseWorkerRequest): WirePack>{ for (const [key, session] of Array.from(this.sessions.entries())){ if (!sessionKeyBelongsToDoc(key, req.docId)) continue; disposeFormModel(this.runtime, session); disposeSignatureModel(this.runtime, session); session.close(); this.sessions.delete(key); } return wirePack({ tag: 'close'} ); } private handleShutdown( _req: ShutdownWorkerRequest, ): WirePack>{ if (!this.destroyed){ this.destroyed = true; for (const session of this.sessions.values()){ disposeFormModel(this.runtime, session); disposeSignatureModel(this.runtime, session); session.close(); } this.sessions.clear(); this.residency.closeIdle(); this.baseDocuments.releaseAll(); destroyLibrary(this.runtime); } return wirePack({ tag: 'shutdown'} ); } private requireSession(req:{ docId: string; layerName?: string} ): DocumentSession{ const key = sessionKey(req.docId, req.layerName); const session = this.sessions.get(key); if (session?.isLocked()){ throw new EngineError( EngineErrorCode.DocPasswordRequired, `document session is password-locked: ${ key} `, ); } if (!session || !session.isOpen()){ throw new EngineError(EngineErrorCode.DocNotOpen, `document session not open: ${ key} `); } session.assertUsable(); return session; } private handleFormsList( req: FormsListWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const reader = new FormReader(this.runtime, session, this.fonts); return wirePack({ tag: 'forms.list', snapshot: reader.snapshot(signal)} ); } private handleFormsSetValue( req: FormsSetValueWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.setValue', field: req.ref, value: req.value} , req.authority, signal, ); return this.finishMutation(session, { tag: 'forms.setValue', result} , req.artifactPath); } private handleFormsReset( req: FormsResetWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, skipped: _skipped, ...result} = this.applyOne( session, req.opId, { type: 'forms.reset', ...(req.refs ?{ fields: req.refs} :{ } )} , req.authority, signal, ); return this.finishMutation(session, { tag: 'forms.reset', result} , req.artifactPath); } private handleFormsExport( req: FormsExportWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const bundle = new FormExporter(this.runtime, session, this.fonts).export( req.selection, req.limits ?? DEFAULT_BUNDLE_LIMITS, signal, ); return wirePack({ tag: 'forms.export', bundle} , Object.values(bundle.resources)); } private handleFormsImport( req: FormsImportWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.import', bundle: req.bundle, ...(req.pages !== undefined ?{ pages: req.pages} :{ } ), attribution: req.attribution, values: req.values, actor: actorOf(req.authority), limits: req.limits ?? DEFAULT_BUNDLE_LIMITS, mayScript: req.mayScript, } , req.authority, signal, ); if (result.fields.length === 0) return wirePack({ tag: 'forms.import', result} ); return this.finishMutation(session, { tag: 'forms.import', result} , req.artifactPath); } private handleFormsImportValues( req: FormsImportValuesWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.importValues', bundle: req.bundle, attribution: req.attribution, actor: actorOf(req.authority), limits: req.limits ?? DEFAULT_BUNDLE_LIMITS, } , req.authority, signal, ); if (result.fields.length === 0) return wirePack({ tag: 'forms.importValues', result} ); return this.finishMutation(session, { tag: 'forms.importValues', result} , req.artifactPath); } private handleFormsRepair( req: FormsRepairWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const mutator = new FormMutator(this.runtime, session, this.fonts); const result = mutator.repair(req.bakeAppearances ?? false, signal); return this.finishMutation(session, { tag: 'forms.repair', result} , req.artifactPath); } private handleFormsCreateField( req: FormsCreateFieldWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.create', draft: req.draft, ...(req.objectNumber !== undefined ?{ objectNumber: req.objectNumber} :{ } ), ...(req.widgetObjectNumbers ?{ widgetObjectNumbers: req.widgetObjectNumbers} :{ } ), } , req.authority, signal, ); return this.finishMutation(session, { tag: 'forms.createField', result} , req.artifactPath); } private handleFormsUpdateField( req: FormsUpdateFieldWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, skipped: _skipped, ...result} = this.applyOne( session, req.opId, { type: 'forms.update', field: req.ref, patch: req.patch} , req.authority, signal, ); return this.finishMutation(session, { tag: 'forms.updateField', result} , req.artifactPath); } private handleFormsSetSignatureAppearance( req: FormsSetSignatureAppearanceWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.setSignatureAppearance', field: req.ref, appearance:{ pdf: new Uint8Array(req.pdf)} , } , req.authority, signal, ); return this.finishMutation( session, { tag: 'forms.setSignatureAppearance', result} , req.artifactPath, ); } private handleFormsDeleteField( req: FormsDeleteFieldWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.delete', field: req.ref} , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'forms.deleteField', result} , req.artifactPath); } private handleFormsAddWidget( req: FormsAddWidgetWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.addWidget', field: req.ref, placement: req.placement, ...(req.objectNumber !== undefined ?{ objectNumber: req.objectNumber} :{ } ), ...(req.splitObjectNumber !== undefined ?{ splitObjectNumber: req.splitObjectNumber} :{ } ), } , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'forms.addWidget', result} , req.artifactPath); } private handleFormsDetachWidget( req: FormsDetachWidgetWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.removeWidget', field: req.ref, widget: req.widget} , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'forms.detachWidget', result} , req.artifactPath); } private handleFormsUpdateWidget( req: FormsUpdateWidgetWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, skipped: _skipped, ...result} = this.applyOne( session, req.opId, { type: 'forms.updateWidget', widget: req.widget, patch: req.patch} , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'forms.updateWidget', result} , req.artifactPath); } private handleFormsDeleteWidget( req: FormsDeleteWidgetWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.deleteWidget', widget: req.widget} , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'forms.deleteWidget', result} , req.artifactPath); } private handleFormsReorderCalculations( req: FormsReorderCalculationsWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.reorderCalculations', fields: req.fields, position: req.position} , checkedAuthority(), signal, ); return this.finishMutation( session, { tag: 'forms.reorderCalculations', result} , req.artifactPath, ); } private handleFormsReorderWidgets( req: FormsReorderWidgetsWorkerRequest, signal: AbortSignal, ): WirePack>{ const session = this.requireSession(req); const{ type: _type, ...result} = this.applyOne( session, req.opId, { type: 'forms.reorderWidgets', page: req.page, widgets: req.widgets, position: req.position, } , checkedAuthority(), signal, ); return this.finishMutation(session, { tag: 'forms.reorderWidgets', result} , req.artifactPath); } private finishMutation

>( session: DocumentSession, payload: P, artifactPath?: string, ): WirePack>{ if (session.inTransaction()) session.commitTransaction(); if (FINAL_CHANGES.has(payload.tag)) changeLedgerOf(session).endUndo(); if ( !payload.tag.startsWith('forms.') && payload.tag !== 'pages.flatten' && payload.tag !== 'redaction.apply' && payload.tag !== 'signatures.complete' ){ session.invalidateDerived(); } if (payload.tag !== 'signatures.complete') session.noteEdit(); const written = withMissingCharacters(payload, session.missingCharacters()); const reported = fontsChangedSince(this.runtime, session) ?{ ...written, fontsChanged: true as const} : written; if (session.kind !== 'layer' || !session.persistLayerArtifact){ return wirePack(reported); } const saved = this.saveLayerArtifact(session, artifactPath); return wirePack({ ...reported, ...saved.payload} , saved.transfer); } private saveLayerArtifact(session: DocumentSession, artifactPath?: string): LayerArtifactSave{ const saver = new DocumentSaver(this.runtime, session); const lastObjectNumber = session.lastObjectNumber(); if (artifactPath){ const artifactFile ={ ...saver.saveLayerArtifactToFile(artifactPath), lastObjectNumber} ; return{ payload:{ artifactFile} , transfer: []} ; } const artifact ={ ...saver.saveLayerArtifact(), lastObjectNumber} ; return{ payload:{ artifact} , transfer: [artifact.bytes]} ; } } WorkerHostOptions [InterfaceDeclaration] (from packages/engine/services/src/worker-host/WorkerHost.ts): export interface WorkerHostOptions{ imageEncoder?: WorkerImageEncoder; signingCandidatePath?: (basePath: string, signingId: string) => string; decodedImageBudgetBytes?: number; parsedPageBudgetBytes?: number; sliceMs?: number; reportEveryFontChange?: boolean; } WorkerImageEncoder [InterfaceDeclaration] (from packages/engine/services/src/worker-host/WorkerHost.ts): export interface WorkerImageEncoder{ encode( raster: PageRaster, opts:{ format: PageNetworkRenderFormat; quality?: number} , ): Promise; } acquireSignatureModel [FunctionDeclaration] (from packages/engine/services/src/features/signature/internal/signatureModelCache.ts): export function acquireSignatureModel(runtime: PdfRuntimeModule, session: DocumentSession): Ptr{ const seq = session.cacheSeq(); const hit = cache.get(session); if (hit && hit.seq === seq){ return hit.ptr; } if (hit){ runtime.fn.EPDFSig_CloseModel(hit.ptr); cache.delete(session); } const ptr = runtime.fn.EPDFSig_LoadModel(session.requireDocPtr()); if (ptr === NULL_PTR){ throw new EngineError(EngineErrorCode.Unknown, 'failed to build signature model'); } cache.set(session, { seq, ptr} ); return ptr; } buildRunsFromRawGlyphs [FunctionDeclaration] (from packages/engine/services/src/features/geometry/PageGeometryReader.ts): export function buildRunsFromRawGlyphs( records: RawGeometryGlyphRecord[], ): PageGeometryRun[]{ const runs: PageGeometryRun[] = []; let buffer: RawGeometryGlyphRecord[] = []; let charStart = 0; let fontSize: number | undefined; let objectKey: number | bigint | null = null; let cls: RunClass | undefined; const flush = (nextStart: number) =>{ if (buffer.length > 0){ runs.push(materializeRun(buffer, charStart, fontSize, cls)); buffer = []; cls = undefined; } charStart = nextStart; } ; for (let i = 0; i < records.length; i++){ const record = records[i]; if (record.objectKey !== objectKey){ flush(i); objectKey = record.objectKey; fontSize = record.fontSize; } const recordClass = classOf(record); if (recordClass){ if (cls && !sameClass(cls, recordClass)) flush(i); if (!cls) cls = recordClass; } buffer.push(record); } flush(records.length); return runs; } changeLedgerOf [FunctionDeclaration] (from packages/engine/services/src/features/changes/ChangeLedger.ts): export function changeLedgerOf(session: DocumentSession): ChangeLedger{ let ledger = ledgers.get(session); if (!ledger){ ledger = new ChangeLedger(); ledgers.set(session, ledger); } return ledger; } destroyLibrary [FunctionDeclaration] (from packages/engine/services/src/runtime/lifecycle/bootstrap.ts): export function destroyLibrary(runtime: PdfRuntimeModule): void{ if (!initialized.has(runtime)) return; runtime.fn.EPDF_ShutdownThread(); initialized.delete(runtime); } disposeFormModel [FunctionDeclaration] (from packages/engine/services/src/features/forms/internal/formModelCache.ts): export function disposeFormModel(runtime: PdfRuntimeModule, session: DocumentSession): void{ const hit = cache.get(session); if (!hit){ return; } runtime.fn.EPDFForm_CloseModel(hit.ptr); cache.delete(session); } disposeSignatureModel [FunctionDeclaration] (from packages/engine/services/src/features/signature/internal/signatureModelCache.ts): export function disposeSignatureModel(runtime: PdfRuntimeModule, session: DocumentSession): void{ const hit = cache.get(session); if (!hit){ return; } runtime.fn.EPDFSig_CloseModel(hit.ptr); cache.delete(session); } documentFontChoice [FunctionDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export function documentFontChoice( runtime: PdfRuntimeModule, session: DocumentSession, name: string, ): DocumentFontChoice | undefined{ return documentProgramForName({ faces: readDocumentFaces(runtime, session), engineFonts: [], fallbacks: []} , name, ); } ensureInitialized [FunctionDeclaration] (from packages/engine/services/src/runtime/lifecycle/bootstrap.ts): export function ensureInitialized(runtime: PdfRuntimeModule): void{ if (initialized.has(runtime)) return; runtime.fn.EPDF_InitThread(); initialized.add(runtime); } fontWriteContext [FunctionDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export function fontWriteContext( runtime: PdfRuntimeModule, session: DocumentSession, fonts: FontRegistrar | undefined, ): Pick< AnnotationWriteContext, | 'resolveRegisteredFontId' | 'describeRegisteredFont' | 'describeFont' | 'documentProgramOf' | 'resolveDocumentFont' >{ let documentFonts: DocumentFontFacts[] | undefined; const documentFontNamed = (name: string) => (documentFonts ??= documentFontsOf(readDocumentFaces(runtime, session))).find( (font) => font.name === name, ); return{ ...(fonts ?{ resolveRegisteredFontId: (key: string) => fonts.idFor(key), describeRegisteredFont: (key: string) => fonts.describeOrUndefined(key), } :{ } ), describeFont: (name: string) =>{ const registered = fonts?.describeOrUndefined(name); if (registered) return registered; const face = documentFontNamed(name)?.face; return face &&{ familyName: face.familyName, weight: face.weight, italic: face.italic} ; } , documentProgramOf: (name: string) =>{ if (isStandardFontName(name) || fonts?.describeOrUndefined(name)) return undefined; const program = documentFontNamed(name)?.programs[0]; return program && canChooseProgram(program) && program.objectNumber > 0 ? program.objectNumber : undefined; } , resolveDocumentFont: (name: string) => documentFontChoice(runtime, session, name), } ; } fontsChangedSince [FunctionDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export function fontsChangedSince(runtime: PdfRuntimeModule, session: DocumentSession): boolean{ const before = fontsSeen.get(session); if (!before) return false; const fingerprint = fontsFingerprintOf(runtime, session); if (fingerprint === before.fingerprint) return false; const documentFonts = listedDocumentFontsOf(runtime, session); fontsSeen.set(session, { fingerprint, documentFonts} ); return documentFonts !== before.documentFonts; } formatPdfDate [FunctionDeclaration] (from packages/engine/services/src/shared/pdf-date.ts): export function formatPdfDate(value: DateInput = new Date()): string{ if (value instanceof Date){ if (Number.isNaN(value.getTime())) throw new RangeError('Cannot format an invalid Date'); const iso = value.toISOString(); return formatPdfDate(`${ iso.slice(0, 19)} Z`); } const match = /^(\d{ 4} )-(\d{ 2} )-(\d{ 2} )T(\d{ 2} ):(\d{ 2} )(?::(\d{ 2} )(?:\.\d+)?)?(?:([Zz])|([+-])(\d{ 2} ):(\d{ 2} ))?$/.exec( value, ); const fields = match &&{ year: match[1]!, month: match[2]!, day: match[3]!, hour: match[4]!, minute: match[5]!, second: match[6] ?? '00', } ; if (!match || !fields || !validClock(fields)){ throw new EngineError(EngineErrorCode.InvalidArg, `not an ISO 8601 date and time: '${ value} '`); } const [, , , , , , , zulu, sign, offsetHours, offsetMinutes] = match; const offset = zulu ? "+00'00'" : sign ? `${ sign} ${ offsetHours} '${ offsetMinutes} '` : ''; const{ year, month, day, hour, minute, second} = fields; return `D:${ year} ${ month} ${ day} ${ hour} ${ minute} ${ second} ${ offset} `; } generateUuid [FunctionDeclaration] (from packages/engine/core/src/identity/uuid.ts): export function generateUuid(): string{ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16)); bytes[6] = (bytes[6]! & 0x0f) | 0x40; bytes[8] = (bytes[8]! & 0x3f) | 0x80; return formatUuid(bytes); } hasAllStandardSecurityPermissions [FunctionDeclaration] (from packages/engine/services/src/shared/securityPermissions.ts): export function hasAllStandardSecurityPermissions(bits: number): boolean{ return ( (u32(bits) & ALL_STANDARD_SECURITY_PERMISSIONS) >>> 0 === ALL_STANDARD_SECURITY_PERMISSIONS ); } hasSignedSignature [FunctionDeclaration] (from packages/engine/services/src/features/signature/internal/readSignatureModel.ts): export function hasSignedSignature(runtime: PdfRuntimeModule, docPtr: Ptr): boolean{ const{ fn} = runtime; return withSignatureModel(runtime, docPtr, (model) =>{ const count = fn.EPDFSig_Count(model); for (let i = 0; i < count; i++) if (fn.EPDFSig_IsSigned(model, i)) return true; return false; } ); } normalizeU32 [VariableDeclaration] (from packages/engine/services/src/shared/securityPermissions.ts): normalizeU32 = u32 openFatMemoryDocument [FunctionDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export function openFatMemoryDocument( runtime: PdfRuntimeModule, bytes: Uint8Array, password: string | null = null, ): OpenedPdfDocument{ const{ mem, fn} = runtime; const stack = new CloseStack(); const dataPtr = mem.alloc(bytes.byteLength); stack.push(() => mem.free(dataPtr)); try{ mem.writeBytes(dataPtr, bytes); const docPtr = fn.FPDF_LoadMemDocument64(dataPtr, bytes.byteLength, password ?? ''); if (!docPtr){ throw loadFailure( fn, password, new EngineError(EngineErrorCode.DocOpenFailed, 'failed to open document'), ); } setRuntimeOwnerPermissionsIfEncrypted(runtime, docPtr); stack.push(() => fn.FPDF_CloseDocument(docPtr)); return{ kind: 'fat-memory', docPtr, source:{ base: null, layer: null, password} , close: () => stack.close(), } ; } catch (error){ stack.close(); throw error; } } openLayerDocument [FunctionDeclaration] (from packages/engine/services/src/document-session/lifecycle/PdfDocumentOpener.ts): export function openLayerDocument( runtime: PdfRuntimeModule, base: AcquiredBaseDocument, layer: LayerSource ={ kind: 'fresh'} , password: string | null = null, ): OpenedPdfDocument{ const{ mem, fn} = runtime; const stack = new CloseStack(); stack.push(() => base.release()); let layerAccess: PdfFileAccessHandle | null = null; const statusPtr = mem.alloc(4); try{ mem.poke(statusPtr, 'i32', -1); let docPtr: Ptr; if (layer.kind === 'fresh'){ docPtr = fn.EPDFLayer_OpenLayer(base.basePtr, NULL_PTR, password ?? '', statusPtr); } else if (layer.kind === 'artifact-file' && runtime.kind === 'native'){ docPtr = withUtf8CString(mem, layer.path, (pathPtr) => fn.EPDFLayer_OpenLayerArtifactFromPath(base.basePtr, pathPtr, password ?? '', statusPtr), ); } else{ layerAccess = layer.kind === 'artifact-file' ? runtime.fileAccess.fromNodeFile(layer.path) : runtime.fileAccess.fromMemory(layer.bytes); stack.push(() => layerAccess?.close()); docPtr = layer.kind === 'artifact' || layer.kind === 'artifact-file' ? fn.EPDFLayer_OpenLayerArtifact(base.basePtr, layerAccess.ptr, password ?? '', statusPtr) : fn.EPDFLayer_OpenLayer(base.basePtr, layerAccess.ptr, password ?? '', statusPtr); } const status = Number(mem.peek(statusPtr, 'i32')); if (!docPtr || status !== 0){ throw layerOpenError(status); } setRuntimeOwnerPermissionsIfEncrypted(runtime, docPtr); stack.push(() => fn.FPDF_CloseDocument(docPtr)); const baseSource: BaseSource = base.kind === 'file' && base.path !== undefined ?{ kind: 'file', key: base.key, path: base.path} :{ kind: 'memory', key: base.key} ; return{ kind: 'layer', docPtr, source:{ base: baseSource, layer, password} , close: () => stack.close(), } ; } catch (error){ stack.close(); throw error; } finally{ mem.free(statusPtr); } } packChangeRecord [FunctionDeclaration] (from packages/engine/services/src/features/changes/recordCodec.ts): export function packChangeRecord(record: ChangeRecordPayload): PackedChangeRecord{ const parts: Uint8Array[] = []; let length = 0; const reverse = JSON.stringify(record, (_key, value: unknown) =>{ if (!(value instanceof Uint8Array)) return value; const at = length; parts.push(value); length += value.byteLength; return{ $capture: [at, value.byteLength]} ; } ); if (parts.length === 0) return{ reverse, capture: null} ; const capture = new Uint8Array(length); let at = 0; for (const part of parts){ capture.set(part, at); at += part.byteLength; } return{ reverse, capture} ; } pdfDateToIso [FunctionDeclaration] (from packages/engine/services/src/shared/pdf-date.ts): export function pdfDateToIso(pdf: string): IsoDateTime | null{ const match = /^(?:D:)?(\d{ 4} )(\d{ 2} )?(\d{ 2} )?(\d{ 2} )?(\d{ 2} )?(\d{ 2} )?(?:([Zz])(?:00'?00'?)?|([+-])(\d{ 2} )(?:'?(\d{ 2} )'?)?)?$/.exec( pdf.trim(), ); if (!match) return null; const [, year, month = '01', day = '01', hour = '00', minute = '00', second = '00'] = match; const [, , , , , , , zulu, sign, offsetHours, offsetMinutes = '00'] = match; const fields ={ year, month, day, hour, minute, second} ; if (!validClock(fields)) return null; let offset = ''; if (zulu){ offset = 'Z'; } else if (sign){ if (Number(offsetHours) > 23 || Number(offsetMinutes) > 59) return null; offset = Number(offsetHours) === 0 && Number(offsetMinutes) === 0 ? 'Z' : `${ sign} ${ offsetHours} :${ offsetMinutes} `; } return `${ year} -${ month} -${ day} T${ hour} :${ minute} :${ second} ${ offset} `; } readActionModel [FunctionDeclaration] (from packages/engine/services/src/features/actions/ActionModelReader.ts): export function readActionModel( fn: PdfFunctions, mem: PdfRuntimeMemory, docPtr: Ptr, modelPtr: Ptr, budget: ActionReadBudgetTracker, ): PdfActionTree | null{ if (modelPtr === NULL_PTR) return null; try{ const nodeCount = fn.EPDFAction_GetNodeCount(modelPtr); if (!Number.isInteger(nodeCount) || nodeCount < 0){ throw malformedActionModel('invalid node count', { nodeCount} ); } budget.addModel(nodeCount); const warningFlags = fn.EPDFAction_GetWarningFlags(modelPtr) >>> 0; const incomplete = !fn.EPDFAction_IsComplete(modelPtr); const rootId = normalizeOptionalNodeId(fn.EPDFAction_GetRootNode(modelPtr), nodeCount); const visiting = new Set(); let payloadDropped = false; const readPayloadString = (call: (buf: Ptr, capacity: number) => number): string | null =>{ const length = call(NULL_PTR, 0); if (length <= 0) return null; budget.reservePayloadBytes(length); return readUtf8String(mem, call); } ; const readOutBool = (read: (outPtr: Ptr) => boolean | number): boolean | null => withScratchN(mem, [I32_BYTES], ([outPtr]) => read(outPtr) ? readI32(mem, outPtr) !== 0 : null, ); const readTargetObjectNumber = (nodeId: number, index: number): number | null => withScratchN(mem, [I32_BYTES], ([outPtr]) =>{ if (!fn.EPDFAction_GetNodeTargetObjectNumber(modelPtr, nodeId, index, outPtr)){ return null; } const value = readI32(mem, outPtr) >>> 0; return value === 0 ? null : value; } ); const readTargets = (nodeId: number, count: number): PdfActionTargetRef[] | null =>{ const targets: PdfActionTargetRef[] = []; for (let index = 0; index < count; index++){ const name = readPayloadString((buf, capacity) => fn.EPDFAction_GetNodeTargetName(modelPtr, nodeId, index, buf, capacity), ); if (name !== null){ targets.push({ kind: 'name', name} ); continue; } const objectNumber = readTargetObjectNumber(nodeId, index); if (objectNumber === null) return null; targets.push({ kind: 'objectNumber', objectNumber} ); } return targets; } ; const readResetFormState = (nodeId: number):{ hasFields: boolean; exclude: boolean} | null => withScratchN(mem, [I32_BYTES, I32_BYTES], ([hasFieldsPtr, excludePtr]) =>{ if (!fn.EPDFAction_GetNodeResetForm(modelPtr, nodeId, hasFieldsPtr, excludePtr)){ return null; } return{ hasFields: readI32(mem, hasFieldsPtr) !== 0, exclude: readI32(mem, excludePtr) !== 0, } ; } ); const readSubmitFormState = (nodeId: number):{ hasFields: boolean; flags: number} | null => withScratchN(mem, [I32_BYTES, I32_BYTES], ([hasFieldsPtr, flagsPtr]) =>{ if (!fn.EPDFAction_GetNodeSubmitForm(modelPtr, nodeId, hasFieldsPtr, flagsPtr)){ return null; } return{ hasFields: readI32(mem, hasFieldsPtr) !== 0, flags: readI32(mem, flagsPtr) >>> 0, } ; } ); const readNode = (nodeId: number): PdfActionNode =>{ if (visiting.has(nodeId)){ throw malformedActionModel('native action model contains a cycle', { nodeId} ); } visiting.add(nodeId); try{ const type = actionTypeFromCode(fn.EPDFAction_GetNodeType(modelPtr, nodeId)); const subtype = readUtf8String(mem, (buf, capacity) => fn.EPDFAction_GetNodeSubtype(modelPtr, nodeId, buf, capacity), ) ?? ''; const nextCount = fn.EPDFAction_GetNextCount(modelPtr, nodeId); if (!Number.isInteger(nextCount) || nextCount < 0){ throw malformedActionModel('invalid action child count', { nodeId, nextCount} ); } const next: PdfActionNode[] = []; for (let index = 0; index < nextCount; index++){ const childId = normalizeNodeId( fn.EPDFAction_GetNextAt(modelPtr, nodeId, index), nodeCount, ); next.push(readNode(childId)); } const degraded = (): PdfActionNode =>{ payloadDropped = true; return{ type: 'unknown', subtype, next} ; } ; switch (type){ case 'javascript':{ if (!fn.EPDFAction_NodeHasJavaScript(modelPtr, nodeId)) return degraded(); const script = readUtf16String(mem, (buf, capacity) => fn.EPDFAction_GetNodeJavaScript(modelPtr, nodeId, buf, capacity), ) ?? ''; budget.addScript(script); return{ type, subtype, script, next} ; } case 'rendition':{ if (!fn.EPDFAction_NodeHasJavaScript(modelPtr, nodeId)){ return{ type, subtype, next} ; } const script = readUtf16String(mem, (buf, capacity) => fn.EPDFAction_GetNodeJavaScript(modelPtr, nodeId, buf, capacity), ) ?? ''; budget.addScript(script); return{ type, subtype, script, next} ; } case 'goto':{ const destPtr = fn.EPDFAction_GetNodeDest(docPtr, modelPtr, nodeId); const destination = destPtr !== NULL_PTR ? readDestination(fn, mem, docPtr, destPtr) : null; return destination ?{ type, subtype, destination, next} : degraded(); } case 'uri':{ const uri = readPayloadString((buf, capacity) => fn.EPDFAction_GetNodeURI(docPtr, modelPtr, nodeId, buf, capacity), ); if (uri === null) return degraded(); const isMap = readOutBool((outPtr) => fn.EPDFAction_GetNodeURIIsMap(modelPtr, nodeId, outPtr)) ?? false; return{ type, subtype, uri, isMap, next} ; } case 'named':{ const name = readPayloadString((buf, capacity) => fn.EPDFAction_GetNodeName(modelPtr, nodeId, buf, capacity), ); return name === null ? degraded() :{ type, subtype, name, next} ; } case 'hide':{ const count = fn.EPDFAction_GetNodeTargetCount(modelPtr, nodeId); if (!Number.isInteger(count) || count < 0) return degraded(); budget.reserveTargets(count); const targets = readTargets(nodeId, count); if (targets === null) return degraded(); const hide = readOutBool((outPtr) => fn.EPDFAction_GetNodeHideFlag(modelPtr, nodeId, outPtr)) ?? true; return{ type, subtype, targets, hide, next} ; } case 'reset-form':{ const state = readResetFormState(nodeId); const count = fn.EPDFAction_GetNodeTargetCount(modelPtr, nodeId); if (state === null || !Number.isInteger(count) || count < 0) return degraded(); budget.reserveTargets(count); const fields = state.hasFields ? readTargets(nodeId, count) : null; if (state.hasFields && fields === null) return degraded(); return{ type, subtype, fields, exclude: state.exclude, next} ; } case 'submit-form':{ if (typeof fn.EPDFAction_GetNodeSubmitForm !== 'function'){ return{ type, subtype, next} ; } const state = readSubmitFormState(nodeId); if (state === null) return degraded(); const url = readPayloadString((buf, capacity) => fn.EPDFAction_GetNodeSubmitFormURL(modelPtr, nodeId, buf, capacity), ); if (url === null) return degraded(); const count = fn.EPDFAction_GetNodeTargetCount(modelPtr, nodeId); if (!Number.isInteger(count) || count < 0) return degraded(); budget.reserveTargets(count); const fields = state.hasFields ? readTargets(nodeId, count) : null; if (state.hasFields && fields === null) return degraded(); const charSet = readPayloadString((buf, capacity) => fn.EPDFAction_GetNodeSubmitFormCharSet(modelPtr, nodeId, buf, capacity), ); return{ type, subtype, payload:{ url, fields, ...decodeSubmitFormFlags(state.flags), ...(charSet === null ?{ } :{ charSet} ), } , next, } ; } case 'goto-remote': case 'goto-embedded': case 'launch':{ const filePath = readPayloadString((buf, capacity) => fn.EPDFAction_GetNodeFilePath(modelPtr, nodeId, buf, capacity), ); return filePath === null ? degraded() :{ type, subtype, filePath, next} ; } default: return{ type, subtype, next} ; } } finally{ visiting.delete(nodeId); } } ; const root = rootId === null ? null : readNode(rootId); const warnings = warningsFromFlags(warningFlags, incomplete); if (payloadDropped) warnings.push('payload-dropped'); return{ root, incomplete, warnings} ; } finally{ fn.EPDFAction_CloseModel(modelPtr); } } readAttachmentFileInfo [FunctionDeclaration] (from packages/engine/services/src/features/attachments/internal/attachmentPrimitives.ts): export function readAttachmentFileInfo( fn: PdfFunctions, mem: PdfRuntimeMemory, attachmentPtr: Ptr, ): AttachmentFileInfo{ const name = readUtf16String(mem, (buf, cap) => fn.FPDFAttachment_GetName(attachmentPtr, buf, cap)) ?? ''; const mimeType = readUtf16String(mem, (buf, cap) => fn.FPDFAttachment_GetSubtype(attachmentPtr, buf, cap), ); const description = readUtf16String(mem, (buf, cap) => fn.EPDFAttachment_GetDescription(attachmentPtr, buf, cap), ); const createdAt = readAttachmentDate(fn, mem, attachmentPtr, 'CreationDate'); const modifiedAt = readAttachmentDate(fn, mem, attachmentPtr, 'ModDate'); const checksum = normalizeChecksum(readAttachmentString(fn, mem, attachmentPtr, 'CheckSum')); const size = readAttachmentSize(fn, mem, attachmentPtr); return{ name, mimeType: mimeType || null, description: description || null, sizeBytes: size, md5: checksum || null, createdAt: createdAt || null, modifiedAt: modifiedAt || null, } ; } readDocumentFaces [FunctionDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export function readDocumentFaces( runtime: PdfRuntimeModule, session: DocumentSession, ): DocumentFaceFacts[]{ const{ fn, mem} = runtime; const faces = fn.EPDFFontFaces_Load(session.requireDocPtr()); if (!faces){ throw new EngineError(EngineErrorCode.Unknown, 'EPDFFontFaces_Load failed'); } try{ const result: DocumentFaceFacts[] = []; const count = fn.EPDFFontFaces_Count(faces); for (let face = 0; face < count; face++){ const programs: FontProgramFacts[] = []; const programCount = fn.EPDFFontFaces_CountPrograms(faces, face); for (let program = 0; program < programCount; program++){ programs.push(programFacts(runtime, faces, face, program)); } result.push({ familyName: readUtf16String(mem, (buf, cap) => fn.EPDFFontFaces_GetFamily(faces, face, buf, cap)) ?? '', weight: fn.EPDFFontFaces_GetWeight(faces, face), italic: fn.EPDFFontFaces_IsItalic(faces, face), programs, } ); } return result; } finally{ fn.EPDFFontFaces_Close(faces); } } readRevisions [FunctionDeclaration] (from packages/engine/services/src/features/signature/internal/readSignatureModel.ts): export function readRevisions( runtime: PdfRuntimeModule, docPtr: Ptr, signatures: ReadonlyArray, ): PdfRevision[]{ const{ fn, mem} = runtime; const count = fn.EPDFDoc_GetRevisionCount(docPtr); const revisions: PdfRevision[] = []; if (count <= 0) return revisions; withScratchN(mem, [U64_BYTES, U64_BYTES], ([endPtr, xrefPtr]) =>{ for (let i = 0; i < count; i++){ pokeU64(mem, endPtr, 0); pokeU64(mem, xrefPtr, 0); if (!fn.EPDFDoc_GetRevision(docPtr, i, endPtr, xrefPtr)){ throw new EngineError(EngineErrorCode.Unknown, `failed to read revision ${ i} `); } const sealedBy = signatures.find((s) => s.revisionIndex === i); revisions.push({ index: i, end: peekU64(mem, endPtr), xrefOffset: peekU64(mem, xrefPtr), signatureIndex: sealedBy ? sealedBy.index : null, } ); } } ); return revisions; } readSignaturesFromModel [FunctionDeclaration] (from packages/engine/services/src/features/signature/internal/readSignatureModel.ts): export function readSignaturesFromModel(runtime: PdfRuntimeModule, model: Ptr): Signature[]{ const{ fn} = runtime; const count = fn.EPDFSig_Count(model); const out: Signature[] = []; const str = (i: number, key: number) => readWide(runtime, (buf, cap) => fn.EPDFSig_GetString(model, i, key, buf, cap)); for (let i = 0; i < count; i++){ const signed = fn.EPDFSig_IsSigned(model, i); const widgetObjNum = fn.EPDFSig_GetWidgetObjNum(model, i); const revisionIndex = fn.EPDFSig_GetRevisionIndex(model, i); const docMdp = fn.EPDFSig_GetDocMDPPermission(model, i); out.push({ index: i, field:{ kind: 'objectNumber', objectNumber: fn.EPDFSig_GetFieldObjNum(model, i)} , fieldName: readWide(runtime, (buf, cap) => fn.EPDFSig_GetFieldName(model, i, buf, cap)) ?? '', widget: widgetObjNum > 0 ? formWidget(widgetObjNum, widgetPageRef(fn.EPDFSig_GetWidgetPageObjNum(model, i))) : null, signed, kind: fn.EPDFSig_GetKind(model, i) === KIND_DOC_TIMESTAMP ? 'timestamp' : 'signature', filter: str(i, STRING_FILTER), subFilter: str(i, STRING_SUBFILTER), byteRange: signed ? readByteRange(runtime, model, i) : null, contentsSizeBytes: signed ? Math.max(0, fn.EPDFSig_GetContents(model, i, NULL_PTR, 0)) : 0, coverage: signed ? (COVERAGE_BY_CODE[fn.EPDFSig_GetCoverage(model, i)] ?? 'malformed') : null, revisionIndex: signed && revisionIndex >= 0 ? revisionIndex : null, signer:{ name: str(i, STRING_NAME), reason: str(i, STRING_REASON), location: str(i, STRING_LOCATION), contactInfo: str(i, STRING_CONTACT_INFO), signedAt: signedAtOf(str(i, STRING_M)), } , docMdp: isPermission(docMdp) ? docMdp : null, catalogCertification: fn.EPDFSig_IsCatalogCertification(model, i), fieldMdp: readLock(runtime, model, i, FIELDS_FIELDMDP), lock: readLock(runtime, model, i, FIELDS_LOCK), seedValue: readSeedValue(runtime, model, i), } ); } return out; } readStructure [FunctionDeclaration] (from packages/engine/services/src/features/signature/internal/readSignatureModel.ts): export function readStructure(runtime: PdfRuntimeModule, docPtr: Ptr): RevisionStructure{ const{ fn, mem} = runtime; const [root, acroForm, pagesRoot] = withScratchN(mem, [4, 4, 4], ([r, a, p]) =>{ mem.poke(r, 'i32', 0); mem.poke(a, 'i32', 0); mem.poke(p, 'i32', 0); fn.EPDFDoc_GetStructureObjectNumbers(docPtr, r, a, p); return [ Number(mem.peek(r, 'i32')) >>> 0, Number(mem.peek(a, 'i32')) >>> 0, Number(mem.peek(p, 'i32')) >>> 0, ]; } ); const pages: number[] = []; const pageCount = fn.FPDF_GetPageCount(docPtr); for (let i = 0; i < pageCount; i++) pages.push(fn.EPDFDoc_GetPageObjectNumberByIndex(docPtr, i)); const fields: RevisionField[] = []; const formModel = fn.EPDFForm_LoadModel(docPtr); if (formModel !== NULL_PTR){ try{ const snapshot = readFormFields(runtime, formModel, docPtr); snapshot.fields.forEach((f, index) =>{ fields.push({ objectNumber: fieldObjectNumberOf(f), name: f.name, kind: f.kind, widgets: f.widgets.map((w) => w.objectNumber), flags: fn.EPDFForm_GetFieldFlags(formModel, index), } ); } ); } finally{ fn.EPDFForm_CloseModel(formModel); } } const signatures = withSignatureModel(runtime, docPtr, (model) => readSignaturesFromModel(runtime, model), ); return{ root, acroForm, pagesRoot, pages, fields, signatures} ; } rotationAt [FunctionDeclaration] (from packages/engine/services/src/features/pages/PagesReader.ts): export function rotationAt(runtime: PdfRuntimeModule, docPtr: Ptr, index: number): PdfRotation{ return withScratch(runtime.mem, 4, (intPtr) => readRotation(runtime.fn, runtime.mem, docPtr, index, intPtr), ); } throwIfAborted [FunctionDeclaration] (from packages/engine/services/src/shared/abort.ts): export function throwIfAborted(signal: AbortSignal): void{ if (signal.aborted){ const reason = signal.reason; if (reason instanceof Error) throw reason; throw new AbortError(reason); } } trackFontChanges [FunctionDeclaration] (from packages/engine/services/src/features/fonts/DocumentFontReader.ts): export function trackFontChanges(runtime: PdfRuntimeModule, session: DocumentSession): void{ if (fontsSeen.has(session)) return; fontsSeen.set(session, { fingerprint: fontsFingerprintOf(runtime, session), documentFonts: listedDocumentFontsOf(runtime, session), } ); } unpackChangeRecord [FunctionDeclaration] (from packages/engine/services/src/features/changes/recordCodec.ts): export function unpackChangeRecord( reverse: string, capture: Uint8Array | null, ): ChangeRecordPayload{ return JSON.parse(reverse, (_key, value: unknown) =>{ const at = (value as{ $capture?: unknown} | null)?.$capture; if (!Array.isArray(at)) return value; if (!capture) throw new Error('a change record names captured bytes it was stored without'); const [offset, size] = at as [number, number]; return capture.slice(offset, offset + size); } ) as ChangeRecordPayload; } visibleBoxReader [FunctionDeclaration] (from packages/engine/services/src/features/pages/PagesReader.ts): export function visibleBoxReader( runtime: PdfRuntimeModule, session: DocumentSession, ): VisibleBoxOf{ const boxes = new Map(); let indexes: Map | null = null; return (page) =>{ const known = boxes.get(page.objectNumber); if (known) return known; indexes ??= new Map( session.allRecords().map((record) => [record.pageObjectNumber, record.pageIndex]), ); const index = indexes.get(page.objectNumber); if (index === undefined){ throw new EngineError( EngineErrorCode.NotFound, `no page with object number ${ page.objectNumber} `, ); } const{ fn, mem} = runtime; const docPtr = session.requireDocPtr(); const box = withScratch( mem, RECTF_BYTES, (rectPtr) => readBoxes(fn, mem, docPtr, index, rectPtr).crop, ); boxes.set(page.objectNumber, box); return box; } ; } writeAttachmentFilePayload [FunctionDeclaration] (from packages/engine/services/src/features/attachments/internal/attachmentPrimitives.ts): export function writeAttachmentFilePayload( fn: PdfFunctions, mem: PdfRuntimeMemory, attachmentPtr: Ptr, docPtr: Ptr, file:{ mimeType?: string | null; description?: string} , resource: WireResource, ): void{ const byteLength = resource.bytes.byteLength; if (byteLength === 0){ if (!fn.FPDFAttachment_SetFile(attachmentPtr, docPtr, NULL_PTR, 0)){ throw new EngineError(EngineErrorCode.Unknown, 'FPDFAttachment_SetFile returned false'); } } else{ const dataPtr = mem.alloc(byteLength); try{ mem.writeBytes(dataPtr, new Uint8Array(resource.bytes)); if (!fn.FPDFAttachment_SetFile(attachmentPtr, docPtr, dataPtr, byteLength)){ throw new EngineError(EngineErrorCode.Unknown, 'FPDFAttachment_SetFile returned false'); } } finally{ mem.free(dataPtr); } } writeUtf16String(mem, formatPdfDate(new Date()), (ptr) => fn.FPDFAttachment_SetStringValue(attachmentPtr, 'CreationDate', ptr), ); if (file.mimeType && !fn.EPDFAttachment_SetSubtype(attachmentPtr, file.mimeType)){ throw new EngineError(EngineErrorCode.Unknown, 'EPDFAttachment_SetSubtype returned false'); } if (file.description !== undefined){ const ok = writeUtf16String(mem, file.description, (ptr) => fn.EPDFAttachment_SetDescription(attachmentPtr, ptr), ); if (!ok){ throw new EngineError( EngineErrorCode.Unknown, 'EPDFAttachment_SetDescription returned false', ); } } }