# @embedpdf/engine-core — ./conformance APPEARANCE_STATES_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runAppearanceStatesConformance.ts): APPEARANCE_STATES_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [4 0 R 10 0 R] >>', '<< /Type /Annot /Subtype /Widget /FT /Btn /T (states) /V /Off /AS /Off /F 4 /Rect [20 20 60 60] ' + '/AP << /N << /Yes 5 0 R /Off 6 0 R >> /D << /Yes 7 0 R /Off 8 0 R >> /R << /Yes 9 0 R >> >> >>', filled('1 0 0 rg'), filled('0 1 0 rg'), filled('0 0 1 rg'), filled('1 1 0 rg'), filled('0 g'), '<< /Type /Annot /Subtype /Square /Rect [100 20 140 60] /F 4 /AP << /N 11 0 R >> >>', filled('0 1 1 rg'), ]) ActionsConformanceFixtures [InterfaceDeclaration] (from packages/engine/core/src/conformance/runActionsConformance.ts): export interface ActionsConformanceFixtures{ document: ConformanceFixture; page: ConformanceFixture; annotation: ConformanceFixture; field: ConformanceFixture; payloads: ConformanceFixture; openDestination: ConformanceFixture; javascriptLink?: ConformanceFixture; } ActionsConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runActionsConformance.ts): export interface ActionsConformanceOptions{ label: string; makeEngine: () => Promise | Engine; fixtures: ActionsConformanceFixtures; openKind: 'bytes' | 'id'; } AnnotationAppearanceConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationAppearanceConformance.ts): export interface AnnotationAppearanceConformanceFixture extends ConformanceFixture{ pageObjectNumber: number; minAppearanceCount: number; expectsInlineAppearance: boolean; } AnnotationAppearanceConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationAppearanceConformance.ts): export interface AnnotationAppearanceConformanceOptions extends Omit< ConformanceOptions, 'fixture' >{ fixture: AnnotationAppearanceConformanceFixture; } AnnotationAttributionConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationAttributionConformance.ts): export interface AnnotationAttributionConformanceOptions{ label: string; makeEngine: () => Promise | Engine; openAs: ( engine: Engine, session: AttributionSession, from?: DocumentHandle, ) => Promise; } AnnotationConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationReadConformance.ts): export interface AnnotationConformanceOptions extends Omit{ fixture: AnnotationReadConformanceFixture; } AnnotationDeclarationConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationDeclarationConformance.ts): export interface AnnotationDeclarationConformanceOptions{ label: string; makeEngine: () => Promise | Engine; openKind: 'bytes' | 'id'; authoring: AnnotationDeclarationFixture; documents: readonly AnnotationDeclarationFixture[]; readOnlyLink: AnnotationDeclarationFixture; } AnnotationDeclarationFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationDeclarationConformance.ts): export interface AnnotationDeclarationFixture{ id: string; bytes: () => Uint8Array | Promise; cloudId?: string; } AnnotationMutationConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationMutationConformance.ts): export interface AnnotationMutationConformanceFixture extends ConformanceFixture{ pageObjectNumber: number; expectsInlineAnnotation: boolean; createQuad?: HighlightDraft['quadPoints']; createShapeRect?: PageBox; createVertices?: PagePoint[]; createLinePoints?: LineDraft['linePoints']; createInkList?: InkDraft['inkList']; } AnnotationMutationConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationMutationConformance.ts): export interface AnnotationMutationConformanceOptions extends Omit{ fixture: AnnotationMutationConformanceFixture; } AnnotationPredictionConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationPredictionConformance.ts): export interface AnnotationPredictionConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } AnnotationReadConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationReadConformance.ts): export interface AnnotationReadConformanceFixture extends ConformanceFixture{ pageObjectNumber: number; expectedAnnotationCount: number; minHighlightCount: number; minUnsupportedCount: number; minCircleCount?: number; minSquareCount?: number; minPolygonCount?: number; minPolylineCount?: number; minLineCount?: number; minInkCount?: number; minFreeTextCount?: number; minCaretCount?: number; expectsInlineAnnotation: boolean; } AnnotationResourceConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationResourceConformance.ts): export interface AnnotationResourceConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, fixture: AnnotationResourceFixture) => Promise; openScoped?: ( engine: Engine, fixture: AnnotationResourceFixture, scope: readonly string[], ) => Promise; } AnnotationResourceFixture [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runAnnotationResourceConformance.ts): export type AnnotationResourceFixture = | 'authoring' | 'acrobat-stamps' | 'acrobat-rewrapped' | 'acrobat-roundtrip-60' | 'acrobat-roundtrip-100'; AnnotationRotationConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationRotationConformance.ts): export interface AnnotationRotationConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, fixture: AnnotationRotationFixture) => Promise; } AnnotationRotationFixture [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runAnnotationRotationConformance.ts): export type AnnotationRotationFixture = | 'authoring' | 'acrobat-stamp-rotated' | 'acrobat-freetext-rotated'; AnnotationTransferConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationTransferConformance.ts): export interface AnnotationTransferConformanceOptions{ label: string; makeEngine: () => Promise | Engine; fixtures: readonly string[]; open: (engine: Engine, fixture: string) => Promise; } AppearanceStatesConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAppearanceStatesConformance.ts): export interface AppearanceStatesConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } AttributionSession [InterfaceDeclaration] (from packages/engine/core/src/conformance/runAnnotationAttributionConformance.ts): export interface AttributionSession{ readonly scope: ReadonlyArray; readonly identity: Identity; } BANDS_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/stampFixtures.ts): BANDS_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R /Resources << >> >>', `<< /Length ${ BANDS_PDF_CONTENT.length} >>\nstream\n${ BANDS_PDF_CONTENT} \nendstream`, ]) BARE_PAGE_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runRedactionApplyConformance.ts): BARE_PAGE_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] >>', ]) BROKEN_OUTLINE_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runOutlineConformance.ts): BROKEN_OUTLINE_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /Outlines 3 0 R >>', '<< /Type /Pages /Kids [6 0 R] /Count 1 >>', '<< /Type /Outlines /First 4 0 R /Last 5 0 R /Count 2 >>', '<< /Title (One) /Parent 3 0 R /Next 5 0 R /First << /Title (Direct) >> >>', '<< /Title (Two) /Parent 3 0 R /Prev 4 0 R /Next 4 0 R >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] >>', ]) CHANGE_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runChangeConformance.ts): CHANGE_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [9 0 R] /DA (/Helv 0 Tf 0 g) ' + '/DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >> >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 10 0 R /Resources << >> ' + '/Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 10 0 R /Resources << >> >>', '<< /Type /Annot /Subtype /Square /Rect [20 200 80 260] /C [0 0 1] /T (Ann) /P 3 0 R >>', '<< /Type /Annot /Subtype /Text /Rect [120 220 140 240] /Contents (Note) /T (Ann) ' + '/Popup 7 0 R /P 3 0 R >>', '<< /Type /Annot /Subtype /Popup /Rect [150 180 250 240] /Parent 6 0 R /P 3 0 R >>', '<< /Type /Annot /Subtype /Text /Rect [120 220 140 240] /Contents (Reply) /T (Bea) ' + '/IRT 6 0 R /P 3 0 R >>', '<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Ann) /Rect [20 20 180 44] /P 3 0 R >>', '<< /Length 0 >>\nstream\n\nendstream', ]) COLOR_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runColorConformance.ts): COLOR_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [4 0 R] >>', '<< /Type /Annot /Subtype /Square /Rect [20 20 120 120] /F 4 /C [0.5] /IC [0 0 0 1] /NM (colored) >>', ]) CROP_OFFSET_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runPageRenderConformance.ts): CROP_OFFSET_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /CropBox [100 200 500 600] /Contents 4 0 R /Resources << >> >>', `<< /Length ${ SQUARE_CONTENT.length} >>\nstream\n${ SQUARE_CONTENT} \nendstream`, ]) ChangeConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runChangeConformance.ts): export interface ChangeConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, pdf?: Uint8Array) => Promise; openAsAnotherUser?: (engine: Engine, doc: DocumentHandle) => Promise; } ColorConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runColorConformance.ts): export interface ColorConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } ConformanceExpect [InterfaceDeclaration] (from packages/engine/core/src/conformance/runMetadataConformance.ts): export interface ConformanceExpect{ (actual: unknown):{ toBe(expected: unknown): void; toBeNull(): void; toEqual(expected: unknown): void; toHaveLength(expected: number): void; toMatch(re: RegExp): void; toMatchObject(shape: Record): void; toContain(expected: unknown): void; toBeInstanceOf(ctor: Function): void; toBeTruthy(): void; rejects:{ toBeInstanceOf(ctor: Function): Promise; toMatchObject(shape: Record): Promise; } ; resolves:{ toMatchObject(shape: Record): Promise; toEqual(expected: unknown): Promise; } ; } ; } ConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runMetadataConformance.ts): export interface ConformanceFixture{ id: string; bytes: () => Uint8Array | Promise; cloudId?: string; expected: Partial; } ConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runMetadataConformance.ts): export interface ConformanceOptions{ label: string; makeEngine: () => Promise | Engine; fixture: ConformanceFixture; openKind: 'bytes' | 'id'; } ConformanceTestRunner [InterfaceDeclaration] (from packages/engine/core/src/conformance/runMetadataConformance.ts): export interface ConformanceTestRunner{ describe(name: string, fn: () => void): void; test(name: string, fn: () => void | Promise): void; beforeAll(fn: () => void | Promise): void; afterAll(fn: () => void | Promise): void; expect: ConformanceExpect; } Creatable [InterfaceDeclaration] (from packages/engine/core/src/conformance/creatables.ts): export interface Creatable{ data: AnnotationDraft; resources?: AnnotationResources; } DRAWING_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runDrawingDetailsConformance.ts): DRAWING_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [4 0 R 5 0 R 6 0 R 7 0 R] >>', '<< /Type /Annot /Subtype /FreeText /IT /FreeTextTypeWriter /Rect [20 240 180 270] /DA (0 0 1 rg /Helv 12 Tf) /Contents (typed) /NM (typewriter) /F 4 >>', '<< /Type /Annot /Subtype /Square /Rect [20 20 120 120] /BS << /S /B /W 2 >> /C [1 0 0] /NM (beveled) /F 4 >>', '<< /Type /Annot /Subtype /Square /Rect [140 20 240 120] /BS << /S /D /W 2 >> /C [1 0 0] /NM (dashed-no-pattern) /F 4 >>', '<< /Type /Annot /Subtype /Square /Rect [140 140 240 220] /BS << /S /D /W 2 /D [] >> /C [1 0 0] /NM (dashed-empty-pattern) /F 4 >>', ]) DateConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runDateConformance.ts): export interface DateConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } DocumentFontsConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runDocumentFontsConformance.ts): export interface DocumentFontsConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, bytes: Uint8Array) => Promise; openReadOnly: (engine: Engine, bytes: Uint8Array) => Promise; servedFont:{ key: string; sha256: string} ; fixtures:{ page: Uint8Array; keptFonts: Uint8Array; documentSubset: Uint8Array; sharedProgram: Uint8Array; fontProgram: Uint8Array; } ; } DrawingDetailsConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runDrawingDetailsConformance.ts): export interface DrawingDetailsConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, fixture: DrawingDetailsFixture) => Promise; } DrawingDetailsFixture [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runDrawingDetailsConformance.ts): export type DrawingDetailsFixture = 'drawing' | 'acrobat-freetext'; DrawnRun [InterfaceDeclaration] (from packages/engine/core/src/conformance/drawnText.ts): export interface DrawnRun{ font: string; text: string; glyphs: string; actualText?: string; x: number; end?: number; baseline: number; } DrawnText [InterfaceDeclaration] (from packages/engine/core/src/conformance/drawnText.ts): export interface DrawnText{ box:{ left: number; bottom: number; right: number; top: number} ; runs: DrawnRun[]; } FIELD_GROUPS_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runFieldGroupsConformance.ts): FIELD_GROUPS_PDF = (() =>{ const group = (name: string) => `/EMBD_Metadata << /SchemaVersion 1 /GroupID (${ name} ) >>`; const text = (name: string, rect: string, extra: string) => `<< /Type /Annot /Subtype /Widget /FT /Tx /T (${ name} ) /Rect [${ rect} ] /F 4 /P 3 0 R ${ extra} >>`; const signature = (name: string, rect: string, extra: string) => `<< /Type /Annot /Subtype /Widget /FT /Sig /T (${ name} ) /Rect [${ rect} ] /F 4 /P 3 0 R ${ extra} >>`; return pdfOf([ '<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] ' + '/CO [7 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 ' + '/BaseFont /Helvetica >> >> >> >> >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 400] /Contents 10 0 R /Resources << >> ' + '/Annots [4 0 R 5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] >>', text('buyer_name', '20 340 180 360', group('buyer')), text('buyer_price', '20 300 180 320', group('buyer')), text('seller_name', '200 340 380 360', group('seller')), text('total', '20 260 180 280', '/AA << /C << /S /JavaScript /JS (event.value = 1; ) >> >>'), signature('buyer_sig', '20 100 180 150', group('buyer')), signature('seller_sig', '200 100 380 150', group('seller')), '<< /Length 0 >>\nstream\n\nendstream', ]); } )() FIELD_GROUP_TOKENS [VariableDeclaration] (from packages/engine/core/src/conformance/runFieldGroupsConformance.ts): FIELD_GROUP_TOKENS ={ buyer:{ scope: ['doc.open', 'doc.render', 'fields:fill:group=buyer', 'fields:sign:group=buyer'], identity:{ userId: 'alice', displayName: 'Alice'} , } , seller:{ scope: ['doc.open', 'doc.render', 'fields:*:group=seller'], identity:{ } } , designer:{ scope: ['doc.open', 'doc.render', 'doc.forms.modify', 'fields:set-group:group=buyer'], identity:{ userId: 'lisa', groupId: 'legal'} , } , everything:{ scope: ['*'], identity:{ } } , } as const satisfies Record FieldGroupToken [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runFieldGroupsConformance.ts): export type FieldGroupToken = keyof typeof FIELD_GROUP_TOKENS; FieldGroupsConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFieldGroupsConformance.ts): export interface FieldGroupsConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: ( engine: Engine, scope: readonly string[], identity: Identity, bytes?: Uint8Array, ) => Promise; completesSignings?: boolean; } FormAttributionConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFormAttributionConformance.ts): export interface FormAttributionConformanceOptions{ label: string; makeEngine: () => Promise | Engine; openAs: ( engine: Engine, session: AttributionSession, from?: DocumentHandle, ) => Promise; } FormConformanceFixtures [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFormConformance.ts): export interface FormConformanceFixtures{ toggleFields: ConformanceFixture &{ pageObjectNumber: number} ; orphanWidgets: ConformanceFixture; choiceFields: ConformanceFixture; importTarget?: ConformanceFixture; deleteTarget?: ConformanceFixture; } FormConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFormConformance.ts): export interface FormConformanceOptions extends Omit{ fixtures: FormConformanceFixtures; } FormPredictionConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFormPredictionConformance.ts): export interface FormPredictionConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } FormScriptConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFormScriptConformance.ts): export interface FormScriptConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, scope: readonly string[]) => Promise; } FormTransferConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runFormTransferConformance.ts): export interface FormTransferConformanceOptions{ label: string; makeEngine: () => Promise | Engine; openAs: ( engine: Engine, session: AttributionSession, bytes: Uint8Array, ) => Promise; } NO_STROKE_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runNoStrokeConformance.ts): NO_STROKE_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 500 ${ PAGE_HEIGHT} ] /Annots [${ annotationObjects .map((_, index) => `${ index + 4} 0 R`) .join(' ')} ] >>`, ...annotationObjects, ]) NoStrokeConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runNoStrokeConformance.ts): export interface NoStrokeConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } OBJECT_NUMBER_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runObjectNumberConformance.ts): OBJECT_NUMBER_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) ' + '/DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >> >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [5 0 R] >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] >>', '<< /Type /Annot /Subtype /Widget /FT /Tx /T (merged) /Rect [10 10 110 30] /P 3 0 R >>', ]) OUTLINE_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runOutlineConformance.ts): OUTLINE_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /Outlines 5 0 R /Names << /Dests 12 0 R >> >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] >>', '<< /Type /Outlines /First 6 0 R /Last 9 0 R /Count 5 >>', '<< /Title (A) /Parent 5 0 R /Next 7 0 R /First 10 0 R /Last 10 0 R /Count 1 ' + '/Dest [3 0 R /XYZ 20 280 null] >>', '<< /Title (B) /Parent 5 0 R /Prev 6 0 R /Next 8 0 R /C [1 0 0] /F 2 ' + '/A << /S /URI /URI (https://example.com/) >> >>', '<< /Title (C) /Parent 5 0 R /Prev 7 0 R /Next 9 0 R /First 11 0 R /Last 11 0 R ' + '/Count -1 /Dest (chapter-two) >>', '<< /Title (D) /Parent 5 0 R /Prev 8 0 R /A << /S /JavaScript /JS (app.alert\\(1\\)) >> >>', '<< /Title (A1) /Parent 6 0 R /Dest [4 0 R /Fit] >>', '<< /Title (C1) /Parent 8 0 R >>', '<< /Names [(chapter-two) [4 0 R /FitH 250]] >>', ]) ObjectNumberConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runObjectNumberConformance.ts): export interface ObjectNumberConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } OpenUnion [InterfaceDeclaration] (from packages/engine/core/src/conformance/tolerantReading.ts): export interface OpenUnion{ at: string; tag: string; catchAll: string; kinds: string[]; } OutlineConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runOutlineConformance.ts): export interface OutlineConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, bytes: Uint8Array) => Promise; openReadOnly: (engine: Engine, bytes: Uint8Array) => Promise; } PAGE_PREDICTION_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runPagePredictionConformance.ts): PAGE_PREDICTION_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /PageLabels << /Nums [0 << /S /r >> 2 << /S /D >> ' + '3 << /S /A /P (App-) /St 2 >>] >> >>', '<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R 6 0 R] /Count 4 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Rotate 90 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 300] /CropBox [10 10 390 290] ' + '/UserUnit 2 /Tabs /R >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 500 500] /TrimBox [20 20 480 480] /Rotate 270 >>', ]) PAGE_SPACE_FIXTURES [VariableDeclaration] (from packages/engine/core/src/conformance/pageSpaceFixtures.ts): PAGE_SPACE_FIXTURES: readonly PageSpaceFixture[] = [ build({ name: 'letter', about: 'the control: a media box at 0, 0 and nothing else', source: 'iso', pages: [ markedPage('/MediaBox [0 0 612 792]', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'tab-order', about: 'a page that says the order its annotations take focus in (/Tabs), as it writes it', source: 'iso', pages: [ markedPage('/MediaBox [0 0 612 792] /Tabs /S', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, tabOrder: 'structure', } ), ], } ), build({ name: 'negative-origin', about: 'a media box around 0, 0, so its corner is at negative numbers', source: 'iso', pages: [ markedPage('/MediaBox [-306 -396 306 396]', rect(-306, -396, 306, 396), { boxes: sameBoxes(rect(-306, -396, 306, 396)), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'cad-origin', about: 'a large drawing centred on 0, 0, as CAD programs export (v2 issue #625)', source: 'iso', pages: [ markedPage('/MediaBox [-1685 -1192 1685 1192]', rect(-1685, -1192, 1685, 1192), { boxes: sameBoxes(rect(-1685, -1192, 1685, 1192)), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'crop-inside', about: 'a crop box inside the media box, away from its corner', source: 'iso', pages: [ markedPage('/MediaBox [0 0 612 792] /CropBox [50 60 562 732]', rect(50, 60, 562, 732), { boxes: sameBoxes(LETTER, rect(50, 60, 562, 732)), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'crop-past-media', about: 'a crop box reaching past the media box is reduced to their intersection (§14.11.2)', source: 'iso', pages: [ markedPage('/MediaBox [0 0 612 792] /CropBox [300 400 900 1000]', rect(300, 400, 612, 792), { boxes: sameBoxes(LETTER, rect(300, 400, 612, 792)), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'flipped-corners', about: 'boxes given by their other corners are normalized (§7.9.5)', source: 'iso', pages: [ markedPage('/MediaBox [612 792 0 0] /CropBox [562 732 50 60]', rect(50, 60, 562, 732), { boxes: sameBoxes(LETTER, rect(50, 60, 562, 732)), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'inherited', about: 'media box, crop box and /Rotate are inherited from the page tree; bleed, trim and art boxes are not (Table 30)', source: 'iso', treeEntries: '/MediaBox [0 0 500 700] /CropBox [20 30 480 680] /Rotate 90 /BleedBox [0 0 500 700] /TrimBox [10 10 490 690]', pages: [ markedPage('', rect(20, 30, 480, 680), { boxes: sameBoxes(rect(0, 0, 500, 700), rect(20, 30, 480, 680)), rotation: 90, userUnit: 1, } ), markedPage('/MediaBox [0 0 300 400] /Rotate 0', rect(20, 30, 300, 400), { boxes: sameBoxes(rect(0, 0, 300, 400), rect(20, 30, 300, 400)), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'page-boxes', about: 'bleed, trim and art boxes: a missing one defaults to the crop box, one past the media box is reduced to it (§14.11.2)', source: 'iso', pages: [ markedPage( '/MediaBox [0 0 612 792] /CropBox [36 36 576 756] /BleedBox [30 30 582 762] /TrimBox [-10 -10 700 900]', rect(36, 36, 576, 756), { boxes:{ media: LETTER, crop: rect(36, 36, 576, 756), bleed: rect(30, 30, 582, 762), trim: LETTER, art: rect(36, 36, 576, 756), } , rotation: 0, userUnit: 1, } , ), ], } ), build({ name: 'turned', about: "a page's /Rotate never moves its positions; negative and full-turn values are the same turn (Table 30)", source: 'iso', pages: ([90, 180, 270, -90, 450] as const).map((turn) => markedPage( `/MediaBox [0 0 612 792] /CropBox [50 60 562 732] /Rotate ${ turn} `, rect(50, 60, 562, 732), { boxes: sameBoxes(LETTER, rect(50, 60, 562, 732)), rotation: (((turn % 360) + 360) % 360) as PdfRotation, userUnit: 1, } , ), ), } ), build({ name: 'user-unit', about: '/UserUnit changes the size of a unit, not the numbers', source: 'iso', pages: [ markedPage('/MediaBox [0 0 306 396] /UserUnit 2', rect(0, 0, 306, 396), { boxes: sameBoxes(rect(0, 0, 306, 396)), rotation: 0, userUnit: 2, } ), ], } ), build({ name: 'destinations', about: "a destination is measured from its target page's visible box, not the link's page", source: 'iso', openDestination:{ toPage: 1, view: '/FitR -200 -100 100 300', expected:{ kind: 'fitR', x: 100, y: 90, width: 300, height: 400} , } , fieldAction:{ toPage: 1, view: '/FitH 350', expected:{ kind: 'fitH', y: 40} } , pages: [ markedPage( '/MediaBox [0 0 612 792]', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1} , { openAction:{ toPage: 1, view: '/XYZ -250 350 0', expected:{ kind: 'xyz', x: 50, y: 40} , } , links: [{ rect: rect(400, 700, 500, 740), toPage: 1, view: '/XYZ -250 350 0', expected:{ kind: 'xyz', x: 50, y: 40} , } , { rect: rect(400, 640, 500, 680), toPage: 1, view: '/XYZ null null 0', expected:{ kind: 'xyz', x: null, y: null} , } , { rect: rect(400, 580, 500, 620), toPage: 1, view: '/FitR -200 -100 100 300', expected:{ kind: 'fitR', x: 100, y: 90, width: 300, height: 400} , } , ], } , ), markedPage( '/MediaBox [-306 -396 306 396] /CropBox [-300 -390 300 390]', rect(-300, -390, 300, 390), { boxes: sameBoxes(rect(-306, -396, 306, 396), rect(-300, -390, 300, 390)), rotation: 0, userUnit: 1, } , { openAction:{ toPage: 0, view: '/FitV 30', expected:{ kind: 'fitV', x: 30} } , links: [{ rect: rect(100, 300, 200, 340), toPage: 0, view: '/FitH 700', expected:{ kind: 'fitH', y: 92} , } , { rect: rect(100, 240, 200, 280), toPage: 0, view: '/FitV 30', expected:{ kind: 'fitV', x: 30} , } , ], } , ), ], } ), build({ name: 'no-media-box', about: 'a page without a media box (required, so the file is broken): US Letter', source: 'recovery', pages: [markedPage('', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1} )], } ), build({ name: 'empty-media-box', about: 'a media box with no area (broken): US Letter', source: 'recovery', pages: [ markedPage('/MediaBox [0 0 0 0]', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'short-crop-box', about: 'a crop box of three numbers (broken) counts as missing', source: 'recovery', pages: [ markedPage('/MediaBox [0 0 612 792] /CropBox [50 60 562]', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'bad-user-unit', about: 'a /UserUnit of zero or below (broken) counts as 1', source: 'recovery', pages: [ markedPage('/MediaBox [0 0 612 792] /UserUnit 0', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, } ), markedPage('/MediaBox [0 0 612 792] /UserUnit -2', LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'crop-outside-media', about: 'a crop box entirely outside the media box (broken): an empty page, as Acrobat shows it', source: 'recovery', pages: [ markedPage('/MediaBox [0 0 612 792] /CropBox [700 800 900 1000]', EMPTY, { boxes: sameBoxes(LETTER, EMPTY), rotation: 0, userUnit: 1, } ), ], } ), build({ name: 'odd-rotate', about: '/Rotate that is not a multiple of 90 (broken): no turn, the content upright as in Acrobat', source: 'recovery', pages: ([45, 135] as const).map((turn) => markedPage(`/MediaBox [0 0 612 792] /Rotate ${ turn} `, LETTER, { boxes: sameBoxes(LETTER), rotation: 0, userUnit: 1, } ), ), } ), ] PERMISSION_TOKENS [VariableDeclaration] (from packages/engine/core/src/conformance/runPermissionConformance.ts): PERMISSION_TOKENS ={ everything: ['*'], fill: ['doc.open', 'doc.render', 'doc.forms.fill'], comment: ['doc.open', 'doc.render', 'doc.annotate.modify'], } as const satisfies Record PREDICTION_FIXTURE_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runAnnotationPredictionConformance.ts): PREDICTION_FIXTURE_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>', ]) PRINT_RULES_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runPrintRenderConformance.ts): PRINT_RULES_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [13 0 R 14 0 R] >> /OCProperties << /OCGs [6 0 R 7 0 R] /D << /ON [7 0 R] /OFF [6 0 R] /AS [<< /Event /Print /Category [/Print] /OCGs [6 0 R 7 0 R] >> << /Event /View /Category [/View] /OCGs [6 0 R 7 0 R] >>] >> >> >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /Resources << /Properties << /OCp 6 0 R /OCv 7 0 R >> >> /Annots [9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2384 3370] /Resources << >> >>', `<< /Length ${ LAYERS.length} >>\nstream\n${ LAYERS} \nendstream`, '<< /Type /OCG /Name (Prints only) /Usage << /Print << /PrintState /ON >> /View << /ViewState /OFF >> >> >>', '<< /Type /OCG /Name (Screen only) /Usage << /Print << /PrintState /OFF >> /View << /ViewState /ON >> >> >>', `<< /Type /XObject /Subtype /Form /BBox [0 0 40 40] /Length ${ SQUARE.length} >>\nstream\n${ SQUARE} \nendstream`, square('10 90 50 130', 36), square('60 90 100 130', 0), square('110 90 150 130', 4), square('150 90 190 130', 6), '<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (print) /Rect [10 30 50 70] /F 0 /P 3 0 R /AP << /N 8 0 R >> >>', '<< /Type /Annot /Subtype /Widget /FT /Tx /T (stamp) /V (x) /Rect [60 30 100 70] /F 36 /P 3 0 R /AP << /N 8 0 R >> >>', ]) PRINT_SCOPES [VariableDeclaration] (from packages/engine/core/src/conformance/runPrintRenderConformance.ts): PRINT_SCOPES ={ everything: ['*'], screen: ['doc.open', 'doc.render', 'doc.annotate.read', 'doc.forms.read'], print: ['doc.open', 'doc.render', 'doc.annotate.read', 'doc.forms.read', 'doc.print'], printOnly: ['doc.open', 'doc.annotate.read', 'doc.forms.read', 'doc.print'], thumbnails: ['doc.open', 'doc.annotate.read', 'doc.forms.read', 'doc.render.thumbnail'], } as const satisfies Record PageCopyConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageCopyConformance.ts): export interface PageCopyConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, id: string) => Promise; } PageFormFieldsConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageFormFieldsConformance.ts): export interface PageFormFieldsConformanceOptions{ label: string; makeEngine: () => Promise | Engine; openKind: 'bytes' | 'id'; form: ConformanceFixture; target: ConformanceFixture; } PageGeometryOrientationFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageGeometryOrientationConformance.ts): export interface PageGeometryOrientationFixture extends ConformanceFixture{ pageObjectNumber: number; expectation: |{ kind: 'upright'; } |{ kind: 'empty-only'; } |{ kind: 'rotated'; rotations: number[]; ascentFlip: boolean; sheared?: boolean; minRotatedRuns?: number; } ; } PageGeometryOrientationOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageGeometryOrientationConformance.ts): export interface PageGeometryOrientationOptions extends Omit{ fixture: PageGeometryOrientationFixture; } PagePredictionConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPagePredictionConformance.ts): export interface PagePredictionConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } PageRenderConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageRenderConformance.ts): export interface PageRenderConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine) => Promise; } PageReorderConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageReorderConformance.ts): export interface PageReorderConformanceFixture extends ConformanceFixture{ pageObjectNumbersForReorderTest?: number[]; } PageReorderConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageReorderConformance.ts): export interface PageReorderConformanceOptions extends Omit{ fixture: PageReorderConformanceFixture; } PageSpaceConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageSpaceConformance.ts): export interface PageSpaceConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, fixture: PageSpaceFixture) => Promise; only?: readonly string[]; } PageSpaceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/pageSpaceFixtures.ts): export interface PageSpaceFixture{ name: string; about: string; source: 'iso' | 'recovery'; treeEntries?: string; openDestination?: PageSpaceGoTo; fieldAction?: PageSpaceGoTo; pages: PageSpaceFixturePage[]; bytes: Uint8Array; } PageSpaceFixturePage [InterfaceDeclaration] (from packages/engine/core/src/conformance/pageSpaceFixtures.ts): export interface PageSpaceFixturePage{ entries: string; marks: PdfRect[]; words: PageSpaceWord[]; links?: PageSpaceLink[]; openAction?: PageSpaceGoTo; expected:{ visible: PdfRect; boxes: PageSpaceBoxes; rotation: PdfRotation; userUnit: number; tabOrder?: PageTabOrder; } ; } PageTextConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageTextConformance.ts): export interface PageTextConformanceFixture extends ConformanceFixture{ pageObjectNumber: number; expectedSubstring: string; minCharCount: number; } PageTextConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPageTextConformance.ts): export interface PageTextConformanceOptions extends Omit{ fixture: PageTextConformanceFixture; } PermissionConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPermissionConformance.ts): export interface PermissionConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, scope: readonly string[]) => Promise; openSameDocument?: ( engine: Engine, doc: DocumentHandle, scope: readonly string[], ) => Promise; } PermissionToken [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runPermissionConformance.ts): export type PermissionToken = keyof typeof PERMISSION_TOKENS; PieceInfoConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPieceInfoConformance.ts): export interface PieceInfoConformanceOptions{ label: string; makeEngine: () => Promise | LocalEngine; fixture: ConformanceFixture; } PrintCopyConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPrintRenderConformance.ts): export interface PrintCopyConformanceOptions extends PrintRenderConformanceOptions{ openCopy: (engine: Engine, bytes: Uint8Array) => Promise; } PrintRenderConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runPrintRenderConformance.ts): export interface PrintRenderConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, scope: readonly string[]) => Promise; } RedactionApplyConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runRedactionApplyConformance.ts): export interface RedactionApplyConformanceOptions extends ConformanceOptions{ openBarePage: (engine: Engine) => Promise; } SearchConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runSearchConformance.ts): export interface SearchConformanceFixture extends ConformanceFixture{ presentLiteral: string; presentPageObjectNumber: number; absentLiteral: string; presentRegex: string; } SearchConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runSearchConformance.ts): export interface SearchConformanceOptions extends Omit{ fixture: SearchConformanceFixture; } SignatureConformanceFixtures [InterfaceDeclaration] (from packages/engine/core/src/conformance/runSignatureConformance.ts): export interface SignatureConformanceFixtures{ unsignedForm: ConformanceFixture; twoApprovals: ConformanceFixture &{ fieldNames: [string, string]; textField: string} ; certified: ConformanceFixture &{ fieldName: string} ; fieldMdp: ConformanceFixture &{ fieldName: string; lockedField: string} ; partialChain: ConformanceFixture; unsignedSigField: ConformanceFixture &{ fieldName: string; textField: string} ; artwork: ConformanceFixture; certifiedNoChanges?: ConformanceFixture; } SignatureConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runSignatureConformance.ts): export interface SignatureConformanceOptions{ label: string; makeEngine: () => Promise | Engine; makePermitEngine?: () => Promise | Engine; openKind: 'bytes' | 'layerBytes' | 'id'; fixtures: SignatureConformanceFixtures; } TEXT_DIVERGENCE_CASES [VariableDeclaration] (from packages/engine/core/src/conformance/runTextDivergenceConformance.ts): TEXT_DIVERGENCE_CASES: Readonly> ={ bug1139:{ resource: 'bug_1139.pdf', pageObjectNumber: 3, exactText: 'Hello, world!\nGoodbye, world!', expectedCharCount: 31, expectedCharMap: [ [1, 0], [15, 13], ], slices: [{ start: 0, count: 1, text: ''} , { start: 1, count: 6, text: 'Hello, '} , { start: 14, count: 2, text: '\n'} , { start: 16, count: 7, text: 'Goodbye'} , ], search:{ query: 'Goodbye', start: 16, count: 7, matchedText: 'Goodbye'} , } , actualText:{ resource: 'bug_384770169.pdf', pageObjectNumber: 3, exactText: 'What is my favorite food?', expectedCharCount: 25, expectedCharMap: null, slices: [{ start: 11, count: 8, text: 'favorite'} ], search:{ query: 'favorite', start: 11, count: 8, matchedText: 'favorite'} , } , astralToUnicode:{ resource: 'embedpdf_astral_tounicode.pdf', pageObjectNumber: 3, exactText: '😀B!', expectedCharCount: 4, expectedCharMap: null, slices: [{ start: 0, count: 2, text: '😀'} , { start: 2, count: 1, text: 'B'} , ], search:{ query: 'B!', start: 2, count: 2, matchedText: 'B!'} , } , joinedHyphen:{ resource: 'bug_781804.pdf', pageObjectNumber: 14, exactText: 'Veritaserum\nUser‐\ngenerated', expectedCharCount: 30, expectedCharMap: [ [7, 6], [13, 11], [20, 17], ], slices: [{ start: 6, count: 1, text: ''} , { start: 0, count: 12, text: 'Veritaserum'} , { start: 12, count: 2, text: '\n'} , ], search:{ query: 'Veritaserum', start: 0, count: 12, matchedText: 'Veritaserum'} , } , } TURNED_FIELDS_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runWidgetRotationConformance.ts): TURNED_FIELDS_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R ' + '11 0 R 12 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 ' + '/BaseFont /Helvetica >> >> >> >> >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Resources << >> ' + '/Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Rotate 90 /Contents 5 0 R ' + '/Resources << >> /Annots [12 0 R] >>', '<< /Length 0 >>\nstream\n\nendstream', field('upright', '20 260 180 284', ''), field('r90', '20 20 44 180', '/MK << /R 90 >>'), field('r180', '60 220 220 244', '/MK << /R 180 >>'), field('r270', '250 20 274 180', '/MK << /R 270 >>'), field('odd', '60 180 220 204', '/MK << /R 45 >>'), field('negative', '200 20 224 180', '/MK << /R -90 >>'), field('on-turned', '20 20 44 180', '/MK << /R 90 >>', 4), ]) TWO_PAGES_PDF [VariableDeclaration] (from packages/engine/core/src/conformance/runFormTransferConformance.ts): TWO_PAGES_PDF = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Resources << >> >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Resources << >> >>', '<< /Length 0 >>\nstream\n\nendstream', ]) TextDivergenceCase [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runTextDivergenceConformance.ts): export type TextDivergenceCase = Omit< TextDivergenceConformanceFixture, 'id' | 'bytes' | 'expected' > &{ resource: string; } ; TextDivergenceConformanceFixture [InterfaceDeclaration] (from packages/engine/core/src/conformance/runTextDivergenceConformance.ts): export interface TextDivergenceConformanceFixture extends ConformanceFixture{ pageObjectNumber: number; exactText: string; expectedCharCount: number; expectedCharMap: ReadonlyArray | null; slices?: ReadonlyArray<{ start: number; count: number; text: string} >; search?:{ query: string; start: number; count: number; matchedText: string} ; } TextDivergenceConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runTextDivergenceConformance.ts): export interface TextDivergenceConformanceOptions extends Omit{ fixture: TextDivergenceConformanceFixture; } UNKNOWN_FIELD [VariableDeclaration] (from packages/engine/core/src/conformance/tolerantReading.ts): UNKNOWN_FIELD = 'fieldFromANewerServer' WIDGET_FINDING_CASES [VariableDeclaration] (from packages/engine/core/src/conformance/runWidgetFindingConformance.ts): WIDGET_FINDING_CASES ={ 'annots-only':{ does: "a merged field/widget in a page's /Annots that the field tree doesn't list", pdf: pdfOf([ `<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [] /DA (/Helv 0 Tf 0 g) ${ FONT_RESOURCES} >> >>`, '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', `<< ${ PAGE} /Annots [4 0 R] >>`, `<< ${ WIDGET} /FT /Tx /T (orphan) /V (hi) /P 3 0 R /AP << /N 5 0 R >> >>`, LOOK, ]), page: 3, field: 'orphan', } , inline:{ does: "a widget written straight into a page's /Annots, as no object of its own", pdf: pdfOf([ `<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [] /DA (/Helv 0 Tf 0 g) ${ FONT_RESOURCES} >> >>`, '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', `<< ${ PAGE} /Annots [<< ${ WIDGET} /FT /Tx /T (inline) /AP << /N 4 0 R >> >>] >>`, LOOK, ]), page: 3, field: null, } , 'no-acroform':{ does: 'a field widget in a file that has no /AcroForm at all', pdf: pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', `<< ${ PAGE} /Annots [4 0 R] >>`, `<< ${ WIDGET} /FT /Tx /T (lonely) /P 3 0 R /AP << /N 5 0 R >> >>`, LOOK, ]), page: 3, field: 'lonely', } , 'stale-p':{ does: "a widget in the second page's /Annots whose /P names the first page", pdf: pdfOf([ `<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) ${ FONT_RESOURCES} >> >>`, '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', `<< ${ PAGE} >>`, `<< ${ PAGE} /Annots [5 0 R] >>`, `<< ${ WIDGET} /FT /Tx /T (moved) /P 3 0 R /AP << /N 6 0 R >> >>`, LOOK, ]), page: 4, field: 'moved', } , 'deleted-page':{ does: 'a field whose widget was on a page the document no longer has', pdf: pdfOf([ `<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) ${ FONT_RESOURCES} >> >>`, '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', `<< ${ PAGE} >>`, '<< /FT /Tx /T (gone) /Kids [5 0 R] >>', `<< ${ WIDGET} /Parent 4 0 R /P 6 0 R /AP << /N 7 0 R >> >>`, `<< ${ PAGE} /Annots [5 0 R] >>`, LOOK, ]), page: null, field: 'gone', } , 'no-field-type':{ does: 'a widget with no field type anywhere on its /Parent chain', pdf: pdfOf([ `<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [] /DA (/Helv 0 Tf 0 g) ${ FONT_RESOURCES} >> >>`, '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', `<< ${ PAGE} /Annots [4 0 R] >>`, `<< ${ WIDGET} /P 3 0 R /AP << /N 5 0 R >> >>`, LOOK, ]), page: 3, field: null, } , } as const satisfies Record WidgetFindingCase [InterfaceDeclaration] (from packages/engine/core/src/conformance/runWidgetFindingConformance.ts): export interface WidgetFindingCase{ readonly does: string; readonly pdf: Uint8Array; readonly page: number | null; readonly field: string | null; } WidgetFindingCaseName [TypeAliasDeclaration] (from packages/engine/core/src/conformance/runWidgetFindingConformance.ts): export type WidgetFindingCaseName = keyof typeof WIDGET_FINDING_CASES; WidgetFindingConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runWidgetFindingConformance.ts): export interface WidgetFindingConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, pdf: Uint8Array, name: WidgetFindingCaseName) => Promise; } WidgetRotationConformanceOptions [InterfaceDeclaration] (from packages/engine/core/src/conformance/runWidgetRotationConformance.ts): export interface WidgetRotationConformanceOptions{ label: string; makeEngine: () => Promise | Engine; open: (engine: Engine, bytes: Uint8Array) => Promise; completesSignings?: boolean; } annotationReadDriftOf [FunctionDeclaration] (from packages/engine/core/src/conformance/annotationReadDrift.ts): export function annotationReadDriftOf(reads: readonly unknown[]): string[]{ const kindsRead = new Set(); const kindsByProblem = new Map>(); const note = (problem: string, subtype: string) =>{ const kinds = kindsByProblem.get(problem) ?? new Set(); kinds.add(subtype); kindsByProblem.set(problem, kinds); } ; for (const read of reads){ const record = read as Record; const subtype = String(record.subtype); kindsRead.add(subtype); if (subtype === 'unsupported' && record.rawSubtypeName === 'Popup'){ note('subtype: popup reads as unsupported', subtype); } const declaration = declarationOf(subtype); if (!declaration){ note('subtype: no declaration', subtype); continue; } for (const name of Object.keys(declaration.fields)){ if (!(name in record) || record[name] === undefined){ note(`${ name} : missing`, subtype); continue; } const schema = declaration.shapes.read[name]!; if (!schema.safeParse(record[name]).success) note(`${ name} : invalid`, subtype); } for (const name of Object.keys(record)){ if (name !== 'subtype' && !(name in declaration.fields)) note(`${ name} : undeclared`, subtype); } } return [...kindsByProblem] .map(([problem, kinds]) => kinds.size === kindsRead.size ? `${ problem} (every kind)` : `${ problem} (${ [...kinds].sort().join(', ')} )`, ) .sort(); } creatables [FunctionDeclaration] (from packages/engine/core/src/conformance/creatables.ts): export function creatables(): Creatable[]{ const rect: PageBox ={ x: 40, y: 40, width: 100, height: 60} ; const quad ={ upperLeft:{ x: 40, y: 40} , upperRight:{ x: 140, y: 40} , lowerLeft:{ x: 40, y: 60} , lowerRight:{ x: 140, y: 60} , } ; const vertices = [{ x: 50, y: 90} , { x: 130, y: 90} , { x: 90, y: 50} , ]; const drafts: AnnotationDraft[] = [{ subtype: 'highlight', quadPoints: [quad]} , { subtype: 'underline', quadPoints: [quad]} , { subtype: 'squiggly', quadPoints: [quad]} , { subtype: 'strikeout', quadPoints: [quad]} , { subtype: 'square', box: rect} , { subtype: 'square', box:{ x: 60, y: 50, width: 60, height: 40} , rotation: 30} , { subtype: 'square', box:{ x: 60, y: 50, width: 60, height: 40} , cloudyIntensity: 1} , { subtype: 'circle', box: rect} , { subtype: 'polygon', rect, vertices} , { subtype: 'polygon', rect, vertices, captionEnabled: true, captionCenter:{ x: 90, y: 80} } , { subtype: 'polyline', rect, vertices} , { subtype: 'line', rect, linePoints:{ start:{ x: 50, y: 90} , end:{ x: 130, y: 50} } } , { subtype: 'ink', rect, inkList: [vertices]} , { subtype: 'free-text', box: rect, intent: 'free-text', fontFamily: 'helvetica', fontSize: 12, textAlign: 'left', contents: 'Declaration conformance', } , { subtype: 'free-text', box:{ x: 80, y: 40, width: 60, height: 40} , intent: 'free-text-callout', fontFamily: 'helvetica', fontSize: 12, textAlign: 'left', contents: 'A callout', calloutLine: [{ x: 45, y: 95} , { x: 60, y: 70} , { x: 80, y: 60} , ], lineEnding: 'open-arrow', } , { subtype: 'caret', box: rect} , { subtype: 'text', rect: iconRect(rect.x, rect.y)} , { subtype: 'link', rect, target:{ kind: 'uri', uri: 'https://example.com'} } , { subtype: 'redact', rect, quadPoints: [quad]} , ]; return [ ...drafts.map((data) => ({ data} )), { data:{ subtype: 'stamp', box: rect} , resources:{ appearance: PNG_1X1} } , { data:{ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y), file:{ name: 'note.txt', mimeType: 'text/plain', description: 'A note'} , } , resources:{ file: new TextEncoder().encode('attached')} , } , ]; } diffAnnotationList [FunctionDeclaration] (from packages/engine/core/src/conformance/diffAnnotationList.ts): export function diffAnnotationList(a: AnnotationList, b: AnnotationList): string[]{ const errs: string[] = []; if (a.pages.length !== b.pages.length){ errs.push(`pages.length mismatch: ${ a.pages.length} vs ${ b.pages.length} `); } const onPage = (list: AnnotationList, page: PageRef) => list.annotations.filter((annotation) => annotation.page.objectNumber === page.objectNumber); const n = Math.min(a.pages.length, b.pages.length); for (let i = 0; i < n; i++){ const pageA = a.pages[i]!; const pageB = b.pages[i]!; for (const e of diffPage(pageA, onPage(a, pageA), pageB, onPage(b, pageB))){ errs.push(`page[${ i} ]: ${ e} `); } } return errs; } drawnTextOf [FunctionDeclaration] (from packages/engine/core/src/conformance/drawnText.ts): export async function drawnTextOf(pdf: Uint8Array): Promise{ const file = await PdfFile.read(pdf); const drawn: DrawnText[] = []; for (const object of file.objects()){ const dict = object.value; if (!(dict instanceof Map) || nameOf(dict.get('Subtype')) !== 'Form' || !object.stream){ continue; } const runs = runsOf(await file.streamData(object.number), await file.fontsOf(dict)); if (runs.length === 0) continue; const [left = 0, bottom = 0, right = 0, top = 0] = numbersOf(file.resolve(dict.get('BBox'))); drawn.push({ box:{ left, bottom, right, top} , runs} ); } return drawn; } iconRect [FunctionDeclaration] (from packages/engine/core/src/conformance/creatables.ts): export function iconRect(x: number, y: number): PageBox{ return{ x, y, width: 20, height: 20} ; } openUnionOf [FunctionDeclaration] (from packages/engine/core/src/conformance/tolerantReading.ts): export function openUnionOf(schema: z.ZodTypeAny): OpenUnion | undefined{ const def = defOf(schema); switch (def.typeName){ case 'ZodLazy': return openUnionOf(def.getter()); case 'ZodOptional': case 'ZodNullable': return openUnionOf(def.innerType); case 'ZodEffects':{ const reading = readingOf(schema); const inner = defOf(def.schema); return reading && 'unknownAs' in reading && inner.typeName === 'ZodDiscriminatedUnion' ? unionAt('response', inner, reading.unknownAs) : undefined; } default: return undefined; } } openUnionsIn [FunctionDeclaration] (from packages/engine/core/src/conformance/tolerantReading.ts): export function openUnionsIn(schema: z.ZodTypeAny, path = 'response'): OpenUnion[]{ const unions: OpenUnion[] = []; walk(schema, path, { problem: () =>{ } , openUnion: (union) => unions.push(union)} ); return unions; } pdfOf [FunctionDeclaration] (from packages/engine/core/src/conformance/pdfOf.ts): export function pdfOf(objects: readonly string[]): Uint8Array{ let text = '%PDF-1.7\n'; const offsets: number[] = []; objects.forEach((object, index) =>{ offsets.push(text.length); text += `${ index + 1} 0 obj\n${ object} \nendobj\n`; } ); const start = text.length; text += `xref\n0 ${ objects.length + 1} \n0000000000 65535 f \n`; for (const offset of offsets) text += `${ String(offset).padStart(10, '0')} 00000 n \n`; text += `trailer\n<< /Size ${ objects.length + 1} /Root 1 0 R >>\nstartxref\n${ start} \n%%EOF\n`; return new TextEncoder().encode(text); } readingProblems [FunctionDeclaration] (from packages/engine/core/src/conformance/tolerantReading.ts): export function readingProblems(schema: z.ZodTypeAny, path = 'response'): string[]{ const problems: string[] = []; walk(schema, path, { problem: (problem) => problems.push(problem), openUnion: () =>{ } } ); return problems; } runActionsConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runActionsConformance.ts): export function runActionsConformance( runner: ConformanceTestRunner, options: ActionsConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; let engine: Engine; describe(`actions conformance: ${ options.label} `, () =>{ beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('reads catalog additional actions and preserves /CO identity', async () =>{ const doc = await open(engine, options, options.fixtures.document); try{ expect(Boolean(doc.actions)).toBe(true); const snapshot = await doc.actions!.get(); expect(DocumentActionsSnapshotSchema.safeParse(snapshot).success).toBe(true); expect(snapshot.openAction).toBeNull(); expect(snapshot.willSave?.root?.type).toBe('javascript'); expect(scriptOf(snapshot.willSave?.root)).toMatch(/Will Save/); expect(scriptOf(snapshot.didSave?.root)).toMatch(/Did Save/); expect(scriptOf(snapshot.willPrint?.root)).toMatch(/Will Print/); expect(scriptOf(snapshot.didPrint?.root)).toMatch(/Did Print/); const form = await doc.forms.list(); expect(form.calculationOrder).toEqual([{ kind: 'objectNumber', objectNumber: 9} ]); } finally{ await doc.close(); } } ); test('attaches page /AA to PageLayout', async () =>{ const doc = await open(engine, options, options.fixtures.page); try{ const pages = await doc.pages.list(); expect(pages.pages[0].actions?.open?.root?.type).toBe('goto-embedded'); expect(pages.pages[0].actions?.close).toBe(undefined); expect(pages.pages[1].actions?.open?.root?.type).toBe('goto-embedded'); expect(pages.pages[1].actions?.close?.root?.type).toBe('goto-embedded'); } finally{ await doc.close(); } } ); test('attaches activation actions to AnnotationBase, including links', async () =>{ const doc = await open(engine, options, options.fixtures.annotation); try{ const firstPage = (await doc.pages.list()).pages[0]; const snapshot = await doc.page(firstPage.ref).annotations.list(); const button = (await doc.forms.list()).widgets.find( (widget) => widget.ref.kind === 'objectNumber' && widget.ref.objectNumber === 7, ); const link = snapshot.annotations.find( (annotation) => annotation.ref.kind === 'objectNumber' && annotation.ref.objectNumber === 8, ); expect(button?.actions?.activate?.root?.type).toBe('uri'); expect(link?.subtype).toBe('link'); expect(link?.actions?.activate?.root?.type).toBe('uri'); if (link?.subtype === 'link'){ expect(link.target?.kind).toBe('uri'); } } finally{ await doc.close(); } } ); test('classifies a /S /JavaScript link target, script staying on base.actions', async () =>{ const fixture = options.fixtures.javascriptLink; if (!fixture) return; const doc = await open(engine, options, fixture); try{ const firstPage = (await doc.pages.list()).pages[0]; const snapshot = await doc.page(firstPage.ref).annotations.list(); const link = snapshot.annotations.find((annotation) => annotation.subtype === 'link'); expect(link?.subtype).toBe('link'); if (link?.subtype === 'link'){ expect(link.target).toEqual({ kind: 'javascript'} ); } expect(link?.actions?.activate?.root?.type).toBe('javascript'); expect(scriptOf(link?.actions?.activate?.root)).toMatch(/app\.alert/); } finally{ await doc.close(); } } ); test('keeps field actions separate from merged widget events', async () =>{ const doc = await open(engine, options, options.fixtures.field); try{ const form = await doc.forms.list(); expect(form.fields).toHaveLength(1); expect(form.fields[0].actions?.format?.root?.type).toBe('javascript'); expect(scriptOf(form.fields[0].actions?.format?.root)).toMatch(/AFDate_FormatEx/); expect(form.widgets).toHaveLength(1); expect(form.widgets[0]!.actions).toBe(null); } finally{ await doc.close(); } } ); test('carries interpreter payloads on every executable node', async () =>{ const doc = await open(engine, options, options.fixtures.payloads); try{ const page = (await doc.pages.list()).pages[0]; const snapshot = await doc.page(page.ref).annotations.list(); const pageObjectNumber = page.ref.objectNumber; const rootOf = (nm: string) =>{ const annotation = snapshot.annotations.find((candidate) => candidate.nm === nm); expect(Boolean(annotation)).toBe(true); return annotation?.actions?.activate?.root ?? null; } ; const targetOf = (nm: string) =>{ const annotation = snapshot.annotations.find((candidate) => candidate.nm === nm); return annotation?.subtype === 'link' ? annotation.target : null; } ; const visible = page.pdfCropBox; expect(rootOf('goto-fitr')).toMatchObject({ type: 'goto', destination:{ kind: 'fitR', page: toPageRef(pageObjectNumber), x: 10 - visible.left, y: visible.top - 400, width: 290, height: 380, } , } ); expect(targetOf('goto-fitr')).toMatchObject({ kind: 'goto', destination:{ kind: 'fitR'} , } ); expect(rootOf('uri-map')).toMatchObject({ type: 'uri', uri: 'https://example.test/map', isMap: true, } ); expect(rootOf('named-next')).toMatchObject({ type: 'named', name: 'NextPage'} ); const mixed = rootOf('hide-mixed'); expect(mixed).toMatchObject({ type: 'hide', hide: false} ); const mixedTargets = mixed?.type === 'hide' ? mixed.targets : []; expect(mixedTargets).toHaveLength(2); expect(mixedTargets[0]).toEqual({ kind: 'name', name: 'note1'} ); expect(mixedTargets[1]?.kind === 'objectNumber' && mixedTargets[1].objectNumber > 0).toBe( true, ); expect(rootOf('hide-scalar')).toMatchObject({ type: 'hide', targets: [{ kind: 'name', name: 'fieldB'} ], hide: true, } ); expect(rootOf('reset-include')).toMatchObject({ type: 'reset-form', fields: [{ kind: 'name', name: 'calc1'} ], exclude: true, } ); expect(rootOf('reset-absent')).toMatchObject({ type: 'reset-form', fields: null, exclude: true, } ); expect(rootOf('reset-empty')).toMatchObject({ type: 'reset-form', fields: [], exclude: false, } ); expect(rootOf('submit-urlspec')).toMatchObject({ type: 'submit-form', payload:{ url: 'https://uf.example.test/submit', fields: [{ kind: 'name', name: 'parent'} ], exclude: false, format: 'fdf', method: 'post', } , } ); expect(rootOf('submit-compat-xfdf')).toMatchObject({ type: 'submit-form', payload:{ url: 'https://example.test/xfdf', fields: [{ kind: 'name', name: 'noexport'} , { kind: 'name', name: 'plain'} , ], exclude: true, includeNoValueFields: true, format: 'xfdf', method: 'post', charSet: 'utf-8', } , } ); expect(rootOf('submit-pdf-get')).toMatchObject({ type: 'submit-form', payload:{ url: 'https://example.test/pdf', fields: null, format: 'pdf', method: 'get', } , } ); expect(rootOf('launch-app')).toMatchObject({ type: 'launch', filePath: 'app.exe'} ); expect(rootOf('gotor-file')).toMatchObject({ type: 'goto-remote', filePath: 'other.pdf'} ); const chain = rootOf('chain-js-goto-hide'); expect(chain).toMatchObject({ type: 'javascript', script: "app.alert('chain'); "} ); expect(chain?.next[0]).toMatchObject({ type: 'goto', destination:{ kind: 'xyz', page: toPageRef(pageObjectNumber), x: 5 - visible.left, y: visible.top - 10, zoom: 1.25, } , } ); expect(chain?.next[0]?.next[0]).toMatchObject({ type: 'hide', targets: [{ kind: 'name', name: 'note1'} ], hide: true, } ); } finally{ await doc.close(); } } ); test('degrades unreadable payloads to unknown with payload-dropped', async () =>{ const doc = await open(engine, options, options.fixtures.payloads); try{ const page = (await doc.pages.list()).pages[0]; const snapshot = await doc.page(page.ref).annotations.list(); for (const [nm, subtype] of [ ['goto-malformed', 'GoTo'], ['hide-partial', 'Hide'], ['submit-not-url', 'SubmitForm'], ['submit-no-f', 'SubmitForm'], ] as const){ const annotation = snapshot.annotations.find((candidate) => candidate.nm === nm); const tree = annotation?.actions?.activate; expect(tree?.root).toMatchObject({ type: 'unknown', subtype} ); expect(tree?.warnings ?? []).toContain('payload-dropped'); if (annotation?.subtype === 'link'){ expect(annotation.target).toEqual({ kind: 'unsupported'} ); } } } finally{ await doc.close(); } } ); test('reads a destination-form /OpenAction as openDestination', async () =>{ const doc = await open(engine, options, options.fixtures.openDestination); try{ expect(Boolean(doc.actions)).toBe(true); const snapshot = await doc.actions!.get(); expect(DocumentActionsSnapshotSchema.safeParse(snapshot).success).toBe(true); expect(snapshot.openAction).toBeNull(); const pageObjectNumber = (await doc.pages.list()).pages[0].ref.objectNumber; expect(snapshot.openDestination).toEqual({ kind: 'xyz', page: toPageRef(pageObjectNumber), x: 10, y: 92, zoom: 1.5, } ); } finally{ await doc.close(); } } ); } ); } runAnnotationAppearanceConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationAppearanceConformance.ts): export function runAnnotationAppearanceConformance( runner: ConformanceTestRunner, options: AnnotationAppearanceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation appearance conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('renders the expected set of appearances with valid output', async () =>{ const doc = await openFixture(engine, options); try{ const{ page, appearances} = await collect(doc, options); expect(page.objectNumber).toBe(options.fixture.pageObjectNumber); expect(appearances.length >= options.fixture.minAppearanceCount).toBe(true); for (const appearance of appearances){ expect(['objectNumber', 'baseIndex'].includes(appearance.ref.kind)).toBe(true); expect(['normal', 'rollover', 'down'].includes(appearance.mode)).toBe(true); expect(appearance.width > 0 && appearance.height > 0).toBe(true); if (appearance.encoded){ expect(appearance.encoded.length > PNG_SIGNATURE.length).toBe(true); expect(PNG_SIGNATURE.every((b, i) => appearance.encoded![i] === b)).toBe(true); } } } finally{ await doc.close(); } } ); if (options.fixture.expectsInlineAppearance){ test('annotations born inline are emitted under their baseIndex name', async () =>{ const doc = await openFixture(engine, options); try{ const{ appearances} = await collect(doc, options); const inline = appearances.find((a) => a.ref.kind === 'baseIndex'); expect(inline !== undefined).toBe(true); } finally{ await doc.close(); } } ); } test('rendered appearances are not blank (non-zero alpha)', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const rasters = await appearanceRasters(page); const anyVisible = [...rasters.values()].some(({ rgba} ) => rgba.some((byte, index) => index % 4 === 3 && byte !== 0), ); expect(anyVisible).toBe(true); } finally{ await doc.close(); } } ); test('abort() rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const p = isLocalPage(page) ? page.annotations.renderAppearancesRaw({ viewport:{ kind: 'scale', scale: 1} } ) : page.annotations.renderAppearances({ format: 'png', viewport:{ kind: 'scale', scale: 1} , } ); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); } ); } runAnnotationAppearanceExportConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationAppearanceExportConformance.ts): export function runAnnotationAppearanceExportConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation appearance export conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('returns a single-page PDF sized to the union rect; source untouched', async () =>{ const doc = await openFixture(engine, options); let exported: DocumentHandle | null = null; try{ const pageObjectNumber = (await doc.pages.list()).pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); if (!page.annotations.exportAppearance) return; const a = (await page.annotations.create(square(20, 20))).annotation.ref; const b = (await page.annotations.create(square(100, 60, 30))).annotation.ref; const before = await page.annotations.list(); const bytes = await page.annotations.exportAppearance([a, b]); expect(bytes.length > 4).toBe(true); expect([...bytes.subarray(0, 4)]).toEqual(PDF_MAGIC); const after = await page.annotations.list(); expect(after.annotations).toEqual(before.annotations); if (options.openKind !== 'bytes') return; exported = await engine.open({ kind: 'bytes', id: `${ options.fixture.id} -appearance`, bytes} , EVERY_PERMISSION, ); const layout = await exported.pages.list(); expect(layout.pageCount).toBe(1); expect(Math.round(layout.pages[0].size.width)).toBe(110); expect(Math.round(layout.pages[0].size.height)).toBe(70); const exportedPage = exported.page(layout.pages[0].ref); expect((await exportedPage.annotations.list()).annotations).toHaveLength(0); } finally{ if (exported) await exported.close(); await doc.close(); } } ); test('a ref on another page and an empty list reject InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const layout = await doc.pages.list(); const page0 = doc.page(layout.pages[0].ref); if (!page0.annotations.exportAppearance) return; await expect(page0.annotations.exportAppearance([])).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); if (layout.pages.length < 2) return; const page1 = doc.page(layout.pages[1].ref); const own = (await page0.annotations.create(square(20, 100))).annotation.ref; const foreign = (await page1.annotations.create(square(20, 100))).annotation.ref; await expect(page0.annotations.exportAppearance([own, foreign])).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } finally{ await doc.close(); } } ); } ); } runAnnotationAttributionConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationAttributionConformance.ts): export function runAnnotationAttributionConformance( runner: ConformanceTestRunner, options: AnnotationAttributionConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation attribution conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const asSession = async ( session: AttributionSession, run: (page: PageHandle, doc: DocumentHandle) => Promise, ): Promise =>{ const doc = await options.openAs(engine, session); try{ return await run(await firstPage(doc), doc); } finally{ await doc.close(); } } ; const expectRefused = async (write: () => Promise, required: string) =>{ const error = await write().then( () => null, (caught: unknown) => caught, ); expect(isPermissionRefusal(error)).toBe(true); expect(String((error as Error).message)).toContain(required); } ; test('the session identity is the one it was opened with', async () =>{ await asSession({ scope: SCOPE, identity: ALICE} , async (_page, doc) =>{ expect(doc.security.identity).toEqual(ALICE); } ); } ); test('create stamps attribution from the session and ignores the data', async () =>{ await asSession({ scope: SCOPE, identity: ALICE} , async (page) =>{ const before = Date.now(); const{ annotation: created} = await page.annotations.create({ ...SQUARE, ...FORGED, } as AnnotationDraft); const after = Date.now(); const read = await readBack(page, created.ref); expect(attributionOf(read)).toEqual({ author: 'Alice Author', userId: 'alice', createdBy: 'alice', modifiedBy: 'alice', groupId: 'legal', importedBy: null, } ); expect(read.createdAt).toBe(read.modifiedAt); expectNow(read.createdAt, before, after); const text = JSON.stringify(read); for (const kept of [ ALICE.email, ALICE.title, ALICE.organization, ALICE.organizationalUnit, ]){ expect(text.includes(kept!)).toBe(false); } } ); } ); test("update stamps modifiedAt and modifiedBy, and keeps the creator's attribution", async () =>{ const alice = await options.openAs(engine, { scope: SCOPE, identity: ALICE} ); let original: Annotation; try{ const page = await firstPage(alice); ({ annotation: original} = await page.annotations.create({ ...SQUARE, nm: 'attribution-conformance-update', } as AnnotationDraft)); } catch (error){ await alice.close(); throw error; } const bob = await options.openAs(engine, { scope: SCOPE, identity: BOB} , alice); await alice.close(); try{ const page = await firstPage(bob); const current = await findByNm(page, 'attribution-conformance-update'); await page.annotations.update(current.ref, { contents: 'Checked', ...FORGED} ); const read = await readBack(page, current.ref); expect(attributionOf(read)).toEqual({ author: 'Alice Author', userId: 'alice', createdBy: 'alice', modifiedBy: 'bob', groupId: 'legal', importedBy: null, } ); expect(read.createdAt).toBe(original.createdAt); expect(Date.parse(read.modifiedAt!) >= Date.parse(original.modifiedAt!)).toBe(true); } finally{ await bob.close(); } } ); test("update of another tool's annotation stamps only modifiedAt and modifiedBy", async () =>{ await asSession({ scope: SCOPE, identity: BOB} , async (page) =>{ const foreign = (await page.annotations.list()).annotations.find( (annotation) => annotation.subtype !== 'popup' && annotation.author !== null && annotation.userId === null, ); expect(foreign !== undefined).toBe(true); const before = Date.now(); await page.annotations.update(foreign!.ref, { contents: 'Checked', ...FORGED} ); const after = Date.now(); const read = await readBack(page, foreign!.ref); expect(attributionOf(read)).toEqual({ author: foreign!.author, userId: null, createdBy: null, modifiedBy: 'bob', groupId: foreign!.groupId, importedBy: null, } ); expect(read.createdAt).toBe(foreign!.createdAt); expectNow(read.modifiedAt, before, after); } ); } ); test("create lands in the session's group unless it may set another", async () =>{ await asSession({ scope: SCOPE, identity: ALICE} , async (page) =>{ const own = await page.annotations.create({ ...SQUARE, groupId: 'legal', } as AnnotationDraft); expect(own.annotation.groupId).toBe('legal'); await expectRefused( () => page.annotations.create({ ...SQUARE, groupId: 'finance'} as AnnotationDraft), 'set-group', ); } ); const granted: AttributionSession ={ scope: [...SCOPE, 'annotations:set-group:group=finance'], identity: ALICE, } ; await asSession(granted, async (page) =>{ const{ annotation: created} = await page.annotations.create({ ...SQUARE, groupId: 'finance', } as AnnotationDraft); expect(attributionOf(await readBack(page, created.ref))).toMatchObject({ groupId: 'finance', userId: 'alice', } ); } ); } ); test('update reassigns a group only with authority for it', async () =>{ await asSession({ scope: SCOPE, identity: ALICE} , async (page) =>{ const{ annotation: created} = await page.annotations.create(SQUARE); await expectRefused( () => page.annotations.update(created.ref, { groupId: 'finance'} ), 'set-group', ); expect((await readBack(page, created.ref)).groupId).toBe('legal'); } ); const granted: AttributionSession ={ scope: [...SCOPE, 'annotations:set-group:group=finance'], identity: ALICE, } ; await asSession(granted, async (page) =>{ const{ annotation: created} = await page.annotations.create(SQUARE); await page.annotations.update(created.ref, { groupId: 'finance'} ); expect((await readBack(page, created.ref)).groupId).toBe('finance'); } ); } ); test('a restoring import keeps the attribution a bundle has, and records who imported it', async () =>{ const alice = await options.openAs(engine, { scope: READ, identity: ALICE} ); const page = await firstPage(alice); const rect ={ x: 300, y: 300, width: 30, height: 30} ; const{ annotation: square} = await page.annotations.create(SQUARE); const{ annotation: note} = await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), } ); await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), reply:{ to: note.ref} , } ); await page.annotations.create({ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y), file:{ name: 'minutes.txt'} , } , { resources:{ file: new TextEncoder().encode('minutes')} } , ); const bob = await options.openAs(engine, { scope: READ, identity: BOB} , alice); await alice.close(); await (await firstPage(bob)).annotations.update(square.ref, { contents: 'Checked'} ); const exported = await bob.annotations.export(); const bundle ={ ...exported, items: exported.items.map((item) => ({ ...item, data:{ ...item.data, nm: null} } )), } as typeof exported; const importer = await options.openAs( engine, { scope: [...READ, 'doc.annotate.import'], identity: IMPORTER} , bob, ); await bob.close(); try{ expect(bundle.items.some(({ data} ) => data.author !== null && data.userId === null)).toBe( true, ); const result = await importer.annotations.import(bundle); expect(result.annotations).toHaveLength(bundle.items.length); result.annotations.forEach((created, index) =>{ const source = bundle.items[index]!.data; expect(attributionOf(created)).toEqual({ ...attributionOf(source), importedBy: 'sync-job', } ); expect([created.createdAt, created.modifiedAt]).toEqual([ source.createdAt, source.modifiedAt, ]); if (created.subtype === 'file-attachment' && source.subtype === 'file-attachment'){ expect(created.file?.createdAt).toBe(source.file?.createdAt); } } ); const edited = result.annotations[ bundle.items.findIndex( (item) => annotationKey(item.data.ref) === annotationKey(square.ref), ) ]!; expect(attributionOf(edited)).toMatchObject({ userId: 'alice', modifiedBy: 'bob'} ); } finally{ await importer.close(); } } ); test('a restoring import needs doc.annotate.import; one that stamps does not', async () =>{ await asSession({ scope: READ, identity: ALICE} , async (page, doc) =>{ const{ annotation: created} = await page.annotations.create(SQUARE); const bundle = await doc.annotations.export({ refs: [created.ref]} ); await expectRefused(() => doc.annotations.import(bundle), 'doc.annotate.import'); const stamped = await doc.annotations.import(bundle, { attribution: 'stamp'} ); expect(attributionOf(stamped.annotations[0]!)).toMatchObject({ userId: 'alice', importedBy: null, } ); } ); } ); test('a user who may create their own annotations may paste them', async () =>{ const createOnly = [ 'doc.open', 'doc.render', 'doc.download', 'doc.annotate.read', 'annotations:create:self', ]; await asSession({ scope: createOnly, identity: BOB} , async (page, doc) =>{ const{ annotation: created} = await page.annotations.create(SQUARE); const bundle = await doc.annotations.export({ refs: [created.ref]} ); const stamped = await doc.annotations.import(bundle, { attribution: 'stamp'} ); expect(attributionOf(stamped.annotations[0]!)).toMatchObject({ userId: 'bob'} ); await expectRefused(() => doc.annotations.import(bundle), 'doc.annotate.modify'); } ); } ); test('doc.annotate.import is granted only by a scope that names it', async () =>{ await asSession({ scope: SCOPE, identity: ALICE} , async (_page, doc) =>{ expect(doc.security.allows('doc.annotate.import')).toBe(false); } ); await asSession({ scope: [...SCOPE, 'doc.annotate.import'], identity: ALICE} , async (_page, doc) =>{ expect(doc.security.allows('doc.annotate.import')).toBe(true); } , ); } ); test("a note with someone else's reply is deleted whole or not at all", async () =>{ const rect ={ x: 200, y: 40, width: 20, height: 20} ; const alice = await options.openAs(engine, { scope: SCOPE, identity: ALICE} ); let note: Annotation; try{ ({ annotation: note} = await ( await firstPage(alice) ).annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), nm: 'attribution-conformance-thread', } )); } catch (error){ await alice.close(); throw error; } const bob = await options.openAs(engine, { scope: SCOPE, identity: BOB} , alice); await alice.close(); let reply: Annotation; try{ const page = await firstPage(bob); const current = await findByNm(page, 'attribution-conformance-thread'); ({ annotation: reply} = await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), contents: 'Seen', reply:{ to: current.ref} , } )); } catch (error){ await bob.close(); throw error; } const own = [ 'doc.open', 'doc.render', 'doc.download', 'doc.annotate.modify', 'annotations:delete:self', ]; const aliceAgain = await options.openAs(engine, { scope: own, identity: ALICE} , bob); await bob.close(); try{ const page = await firstPage(aliceAgain); const current = await findByNm(page, 'attribution-conformance-thread'); const error = await page.annotations.delete(current.ref).then( () => null, (caught: unknown) => caught, ); expect(isPermissionRefusal(error)).toBe(true); const refs = (error as EngineError).details?.['refs'] as AnnotationRef[]; expect(refs.map(annotationKey)).toEqual([annotationKey(reply.ref)]); expect((await readBack(page, current.ref)).nm).toBe(note.nm); expect((await readBack(page, reply.ref)).contents).toBe('Seen'); } finally{ await aliceAgain.close(); } } ); } ); } runAnnotationCopyConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationCopyConformance.ts): export function runAnnotationCopyConformance( runner: ConformanceTestRunner, options: AnnotationResourceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation copy conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDocument = async ( run: (doc: DocumentHandle, page: PageRef, other: PageRef) => Promise, fixture: Parameters[1] = 'authoring', ): Promise =>{ const doc = await options.open(engine, fixture); try{ const{ pages} = await doc.pages.list(); const page = toPageRef(pages[0]!.ref.objectNumber); const{ insertedPages} = await doc.pages.insertBlank({ size:{ width: 300, height: 500} } , { after: page} , ); await run(doc, page, insertedPages[0]!); } finally{ await doc.close(); } } ; const box = (x: number): PageBox => ({ x, y: 300, width: 40, height: 30} ); const create = async ( page: PageHandle, draft: Parameters[0], resources?: Parameters[1], ) => (await page.annotations.create(draft, resources)).annotation as Annotation; const listed = async (doc: DocumentHandle, page: PageRef) => (await doc.page(page).annotations.list()).annotations as Annotation[]; const keysOf = (annotations: readonly Annotation[]) => annotations.map((annotation) => annotationKey(annotation.ref)); const OFFSET ={ x: 12, y: 18} ; test('a copy of every kind a create makes reads back as the copy rule says, moved', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); for (const{ data, resources} of creatables()){ const source = await create(page, data, resources ?{ resources} : undefined); const result = await doc.annotations.copy([source.ref], { offset: OFFSET} ); const kind = source.subtype; expect({ kind, dropped: result.dropped} ).toEqual({ kind, dropped: []} ); const [copy] = result.annotations; const [planned] = planAnnotationCopies([source], { offset: OFFSET} ).copies; const differs = differences(carried(copy!), carried(planned!.data)); expect({ kind, differs} ).toEqual({ kind, differs: []} ); expect(annotationKey(copy!.ref) === annotationKey(source.ref)).toBe(false); expect(result.refMap).toEqual([{ from: source.ref, to: copy!.ref} ]); expect(copy!.nm).toMatch(UUID_V7); expect(copy!.nm === source.nm).toBe(false); expect(copy!.author).toEqual(source.author); expect(keysOf(await listed(doc, pageRef))).toContain(annotationKey(copy!.ref)); } } ); } ); test('a copy keeps its flags: a locked annotation’s copy is locked', async () =>{ await withDocument(async (doc, pageRef) =>{ const locked = await create(doc.page(pageRef), { subtype: 'square', box: box(20), locked: true, print: false, } ); const{ annotations} = await doc.annotations.copy([locked.ref], { offset: OFFSET} ); expect(annotations[0]).toMatchObject({ locked: true, print: false} ); } ); } ); test('a copied stamp places the drawing its source places', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); const stamp = await create( page, { subtype: 'stamp', box: box(20), opacity: 0.5} , { resources:{ appearance: BANDS_PDF} } , ); const{ annotations} = await doc.annotations.copy([stamp.ref], { offset: OFFSET} ); const [copy] = annotations; expect(copy).toMatchObject({ subtype: 'stamp', opacity: 0.5} ); const bundle = await doc.annotations.export({ refs: [stamp.ref, copy!.ref]} ); expect(Object.keys(bundle.resources)).toHaveLength(1); expect(bundle.items.map((item) => item.resources.appearance)).toEqual([ Object.keys(bundle.resources)[0], Object.keys(bundle.resources)[0], ]); const [ofSource, ofCopy] = await Promise.all([ page.annotations.downloadResource(stamp.ref, 'appearance'), page.annotations.downloadResource(copy!.ref, 'appearance'), ]); expect(Array.from(ofCopy)).toEqual(Array.from(ofSource)); } ); } ); test('a stamp another app made is copied too', async () =>{ await withDocument(async (doc, pageRef) =>{ const stamps = (await listed(doc, pageRef)).filter((each) => each.subtype === 'stamp'); expect(stamps.length > 0).toBe(true); const result = await doc.annotations.copy( stamps.map((stamp) => stamp.ref), { offset: OFFSET} , ); expect(result.dropped).toEqual([]); expect(result.annotations).toHaveLength(stamps.length); result.annotations.forEach((copy, at) =>{ const [planned] = planAnnotationCopies([stamps[at]!], { offset: OFFSET} ).copies; expect(differences(geometryOf(copy), geometryOf(planned!.data))).toEqual([]); } ); const drawing = await doc .page(pageRef) .annotations.downloadResource(result.annotations[0]!.ref, 'appearance'); expect(drawing.byteLength > 0).toBe(true); } , 'acrobat-stamps'); } ); test('a copied attachment gets its source’s file, name and dates', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); const bytes = new TextEncoder().encode('attached, then copied'); const source = await create( page, { subtype: 'file-attachment', rect: iconRect(40, 40), file:{ name: 'note.txt', mimeType: 'text/plain', description: 'A note'} , } , { resources:{ file: bytes} } , ); const{ annotations} = await doc.annotations.copy([source.ref], { offset: OFFSET} ); const [copy] = annotations; expect(copy!.subtype === 'file-attachment' && copy.file).toEqual( source.subtype === 'file-attachment' && source.file, ); const copied = await page.annotations.downloadResource(copy!.ref, 'file'); expect(Array.from(copied)).toEqual(Array.from(bytes)); } ); } ); test('links between copies stay: a group is a group of its own, a member alone stands alone', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); const first = await create(page, { subtype: 'square', box: box(20)} ); const second = await create(page, { subtype: 'circle', box: box(80), reply:{ to: first.ref, type: 'group'} , } ); const note = await create(page, { subtype: 'text', rect: iconRect(140, 300)} ); const popup = await create(page, { subtype: 'popup', rect: box(200), parent: note.ref, open: true, } ); const answer = await create(page, { subtype: 'text', rect: iconRect(140, 300), reply:{ to: note.ref} , } ); const whole = await doc.annotations.copy([first.ref, second.ref, note.ref, popup.ref]); expect(whole.dropped).toEqual([]); const [firstCopy, secondCopy, noteCopy, popupCopy] = whole.annotations; expect(firstCopy!.reply ?? null).toBeNull(); expect(secondCopy!.reply).toEqual({ to: firstCopy!.ref, type: 'group'} ); expect(popupCopy!.subtype === 'popup' && popupCopy.parent).toEqual(noteCopy!.ref); expect(noteCopy!.popup).toEqual(popupCopy!.ref); const replies = (await listed(doc, pageRef)).filter((each) => each.reply?.type === 'reply'); expect(keysOf(replies)).toEqual([annotationKey(answer.ref)]); const alone = await doc.annotations.copy([second.ref, answer.ref]); expect(alone.dropped).toEqual([]); expect(alone.annotations.map((copy) => copy.reply ?? null)).toEqual([null, null]); const orphan = await doc.annotations.copy([popup.ref]); expect(orphan.annotations).toEqual([]); expect(orphan.dropped).toEqual([{ ref: popup.ref, reason: 'parent-missing'} ]); expect(orphan.meta.undoable).toBe(false); } ); } ); test('onto another page: the same spot from that page’s top-left', async () =>{ await withDocument(async (doc, pageRef, other) =>{ const square = await create(doc.page(pageRef), { subtype: 'square', box: box(20)} ); const before = keysOf(await listed(doc, other)); const{ annotations} = await doc.annotations.copy([square.ref], { page: other} ); const [copy] = annotations; expect(copy!.ref.page).toEqual(other); expect(differences(geometryOf(copy!), geometryOf(square))).toEqual([]); expect(keysOf(await listed(doc, other))).toEqual([...before, annotationKey(copy!.ref)]); } ); } ); test('an annotation named twice is copied twice, under the object numbers given', async () =>{ await withDocument(async (doc, pageRef) =>{ const square = await create(doc.page(pageRef), { subtype: 'square', box: box(20)} ); await doc.objectNumbers.reserve(2); const numbers = [doc.objectNumbers.take()!, doc.objectNumbers.take()!]; const result = await doc.annotations.copy([square.ref, square.ref], { offset: OFFSET, objectNumbers: numbers, } ); expect(result.refMap.map((pair) => annotationKey(pair.from))).toEqual([ annotationKey(square.ref), annotationKey(square.ref), ]); expect( result.annotations.map( (copy) => copy.ref.kind === 'objectNumber' && copy.ref.objectNumber, ), ).toEqual(numbers); expect(new Set(result.annotations.map((copy) => copy.nm)).size).toBe(2); } ); } ); test('emits one annotations.created per copy, as one transaction', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); const refs = [ (await create(page, { subtype: 'square', box: box(20)} )).ref, (await create(page, { subtype: 'circle', box: box(80)} )).ref, ]; const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const result = await doc.annotations.copy(refs, { offset: OFFSET, opId: 'copy-1'} ); expect(result.meta).toMatchObject({ opId: 'copy-1', undoable: true} ); expect(events.map((event) => event.type)).toEqual([ 'annotations.created', 'annotations.created', ]); events.forEach((event, index) =>{ expect('origin' in event && event.origin.transaction).toEqual({ id: 'copy-1', index, count: 2, } ); expect(event.type === 'annotations.created' && event.annotation).toEqual( result.annotations[index], ); } ); } ); } ); test('is undone and redone: the same refs, and a copy changed since stays', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); const refs = [ (await create(page, { subtype: 'square', box: box(20)} )).ref, (await create(page, { subtype: 'circle', box: box(80)} )).ref, ]; const before = keysOf(await listed(doc, pageRef)); const copied = await doc.annotations.copy(refs, { offset: OFFSET} ); const after = await listed(doc, pageRef); const undo = await doc.apply({ undoOf: copied.meta.opId} ); expect(keysOf(await listed(doc, pageRef))).toEqual(before); await doc.apply({ undoOf: undo.meta.opId} ); expect(await listed(doc, pageRef)).toEqual(after); const [changed, untouched] = copied.annotations; await page.annotations.update(changed!.ref, { subtype: 'square', color: '#16a34a'} ); const partial = await doc.apply({ undoOf: copied.meta.opId} ); expect(partial.items.some((item) => item.type === 'skipped')).toBe(true); const left = keysOf(await listed(doc, pageRef)); expect(left).toContain(annotationKey(changed!.ref)); expect(left.includes(annotationKey(untouched!.ref))).toBe(false); } ); } ); test('refuses before anything is written, and says what it left out', async () =>{ await withDocument(async (doc, pageRef) =>{ const page = doc.page(pageRef); const square = await create(page, { subtype: 'square', box: box(20)} ); const before = await listed(doc, pageRef); const missing: AnnotationRef ={ kind: 'objectNumber', page: pageRef, objectNumber: 9999} ; await expect(doc.annotations.copy([square.ref, missing])).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); await expect( doc.annotations.copy([square.ref], { page: toPageRef(9999)} ), ).rejects.toMatchObject({ code: EngineErrorCode.NotFound} ); await expect( doc.annotations.copy([square.ref], { objectNumbers: []} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(await listed(doc, pageRef)).toEqual(before); await doc.forms.create({ kind: 'text', name: 'city', widgets: [{ page: pageRef, rect:{ x: 20, y: 400, width: 120, height: 24} } ], } ); const widget = (await doc.forms.list()).widgets[0]!; const mixed = await doc.annotations.copy([widget.ref, square.ref], { offset: OFFSET} ); expect(mixed.dropped).toEqual([{ ref: widget.ref, reason: 'widget'} ]); expect(mixed.refMap.map((pair) => annotationKey(pair.from))).toEqual([ annotationKey(square.ref), ]); } ); } ); test('a copy of more annotations than a bundle holds is refused, and writes nothing', async () =>{ await withDocument(async (doc, pageRef) =>{ const square = await create(doc.page(pageRef), { subtype: 'square', box: box(20)} ); const before = await listed(doc, pageRef); const max = DEFAULT_BUNDLE_LIMITS.items; const refs = Array.from({ length: max + 1} , () => square.ref); await expect(doc.annotations.copy(refs)).rejects.toMatchObject({ code: EngineErrorCode.PayloadTooLarge, details:{ limit: 'items', max, value: max + 1} , } ); expect(await listed(doc, pageRef)).toEqual(before); } ); } ); test('a session without doc.download copies a stamp; one that may not read annotations copies nothing', async () =>{ if (!options.openScoped) return; const writer = await options.openScoped(engine, 'authoring', [ 'doc.open', 'doc.render', 'doc.annotate.modify', ]); try{ const{ pages} = await writer.pages.list(); const pageRef = toPageRef(pages[0]!.ref.objectNumber); const page = writer.page(pageRef); const stamp = await create( page, { subtype: 'stamp', box: box(20)} , { resources:{ appearance: PNG_1X1} } , ); const refused = await page.annotations.downloadResource(stamp.ref, 'appearance').then( () => null, (error: unknown) => error, ); expect(isPermissionRefusal(refused)).toBe(true); const result = await writer.annotations.copy([stamp.ref], { offset: OFFSET} ); expect(result.dropped).toEqual([]); expect(result.annotations[0]).toMatchObject({ subtype: 'stamp'} ); } finally{ await writer.close(); } const reader = await options.openScoped(engine, 'authoring', ['doc.open', 'doc.render']); try{ const{ pages} = await reader.pages.list(); const ref: AnnotationRef ={ kind: 'objectNumber', page: toPageRef(pages[0]!.ref.objectNumber), objectNumber: 1, } ; const refused = await reader.annotations.copy([ref]).then( () => null, (error: unknown) => error, ); expect(isPermissionRefusal(refused)).toBe(true); } finally{ await reader.close(); } } ); } ); } runAnnotationDeclarationConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationDeclarationConformance.ts): export function runAnnotationDeclarationConformance( runner: ConformanceTestRunner, options: AnnotationDeclarationConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation declaration conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('every read matches its kind declaration', async () =>{ const reads: unknown[] = []; for (const fixture of options.documents){ const doc = await openFixture(engine, options, fixture); try{ reads.push(...(await doc.annotations.list()).annotations); } finally{ await doc.close(); } } const doc = await openFixture(engine, options, options.authoring); try{ const first = (await doc.annotations.list()).pages[0]; expect(first !== undefined).toBe(true); const page = first!; for (const{ data, resources} of creatables()){ const{ annotation: created} = await doc .page(page) .annotations.create(data, { resources} ); reads.push(created); } reads.push(...(await doc.annotations.list({ pages: [page]} )).annotations); } finally{ await doc.close(); } expect(annotationReadDriftOf(reads)).toEqual([]); } ); const onAuthoringPage = async ( run: (page: PageHandle, doc: DocumentHandle) => Promise, ): Promise =>{ const doc = await openFixture(engine, options, options.authoring); try{ const first = (await doc.annotations.list()).pages[0]!; await run(doc.page(first), doc); } finally{ await doc.close(); } } ; test('shared fields follow the write rules on every kind', async () =>{ await onAuthoringPage(async (page) =>{ for (const{ data, resources} of creatables()){ const{ annotation: created} = await page.annotations.create(data, { resources} ); const read = async () => (await page.annotations.list()).annotations.find( (annotation) => annotationKey(annotation.ref) === annotationKey(created.ref), ) as unknown as Record; const key = annotationKey(created.ref); const text: [string, string, string][] = [ ['subject', 'Pricing', 'Terms'], ['nm', `first-${ key} `, `second-${ key} `], ]; if (data.subtype !== 'free-text' && data.subtype !== 'redact'){ text.push(['contents', 'First note', 'Second note']); } for (const [field, first, second] of text){ await page.annotations.update(created.ref, { [field]: first} ); expect((await read())[field]).toBe(first); await page.annotations.update(created.ref, { } ); expect((await read())[field]).toBe(first); await page.annotations.update(created.ref, { [field]: second} ); expect((await read())[field]).toBe(second); await page.annotations.update(created.ref, { [field]: null} ); expect((await read())[field]).toBe(null); } await page.annotations.update(created.ref, { hidden: true} ); await page.annotations.update(created.ref, { print: true} ); expect(await read()).toMatchObject({ hidden: true, print: true, locked: false} ); await page.annotations.update(created.ref, { hidden: false} ); expect(await read()).toMatchObject({ hidden: false, print: true} ); } } ); } ); test('a read sent back as an update changes nothing', async () =>{ await onAuthoringPage(async (page) =>{ for (const{ data, resources} of creatables()){ const{ annotation: created} = await page.annotations.create(data, { resources} ); const result = await page.annotations.update(created.ref, created as never); expect(result.appearance.changed).toBe(false); const{ modifiedAt: _before, ...expected} = created; const{ modifiedAt: _after, ...updated} = result.annotation; expect(updated).toEqual(expected); } } ); } ); test("a box kind's rect is worked out, and another one puts the box there", async () =>{ await onAuthoringPage(async (page) =>{ const box: PageBox ={ x: 300, y: 300, width: 60, height: 40} ; const{ annotation: created} = await page.annotations.create({ subtype: 'square', box, rect:{ x: 0, y: 0, width: 1, height: 1} , } as never); expect(created.rect).toEqual(box); const moved ={ ...box, x: box.x + 20} ; const{ annotation: updated} = await page.annotations.update(created.ref, { rect: created.rect, box: moved, } ); expect(updated.rect).toEqual(moved); const wider ={ ...moved, width: moved.width + 10} ; const{ annotation: placed} = await page.annotations.update(created.ref, { rect: wider} ); expect(placed.subtype === 'square' && placed.box).toEqual(wider); await expect( page.annotations.update(created.ref, { rect: moved, box: box} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'rect'} } ); } ); } ); test('an update takes its subtype from the annotation it targets', async () =>{ await onAuthoringPage(async (page) =>{ const{ annotation: created} = await page.annotations.create(creatables()[0]!.data); const result = await page.annotations.update(created.ref, { contents: 'No subtype'} ); expect(result.annotation.contents).toBe('No subtype'); await expect( page.annotations.update(created.ref, { subtype: 'square', contents: 'x'} as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } ); } ); test('a field the kind does not declare is refused', async () =>{ await onAuthoringPage(async (page) =>{ const square = creatables().find(({ data} ) => data.subtype === 'square')!.data; await expect( page.annotations.create({ ...square, colour: '#000000'} as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const{ annotation: created} = await page.annotations.create(square); await expect( page.annotations.update(created.ref, { quadPoints: []} as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } ); } ); test('a create left without a name gets a fresh one; nm: null names none', async () =>{ await onAuthoringPage(async (page) =>{ const square = creatables().find(({ data} ) => data.subtype === 'square')!.data; const{ nm: _name, ...unnamed} = square as typeof square &{ nm?: string | null} ; const{ annotation: named} = await page.annotations.create(unnamed); expect(named.nm).toMatch(UUID_V7); const{ annotation: none} = await page.annotations.create({ ...unnamed, nm: null} ); expect(none.nm).toBe(null); } ); } ); test('a popup links to its parent in both directions', async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 200, y: 200, width: 60, height: 40} ; const note = ( await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y)} ) ).annotation; const popup = (await page.annotations.create({ subtype: 'popup', rect, parent: note.ref} )) .annotation; const find = async (ref: AnnotationRef) => (await page.annotations.list()).annotations.find( (annotation) => annotationKey(annotation.ref) === annotationKey(ref), )!; expect(popup.subtype === 'popup' && popup.parent !== null).toBe(true); expect(annotationKey((await find(note.ref)).popup!)).toBe(annotationKey(popup.ref)); await expect( page.annotations.create({ subtype: 'popup', rect} as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'parent'} } ); await expect( page.annotations.update(popup.ref, { parent: null} as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await page.annotations.delete(popup.ref); expect((await find(note.ref)).popup).toBe(null); } ); } ); test("a popup's open state is read and written", async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 200, y: 260, width: 60, height: 40} ; const note = ( await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y)} ) ).annotation; const closed = (await page.annotations.create({ subtype: 'popup', rect, parent: note.ref} )) .annotation; expect(closed.subtype === 'popup' && closed.open).toBe(false); const opened = await page.annotations.update(closed.ref, { open: true} ); expect(opened.annotation.subtype === 'popup' && opened.annotation.open).toBe(true); const other = ( await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y + 60)} ) ).annotation; const created = ( await page.annotations.create({ subtype: 'popup', rect, parent: other.ref, open: true} ) ).annotation; expect(created.subtype === 'popup' && created.open).toBe(true); } ); } ); test('values are checked, not only names, with the field named', async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 300, y: 520, width: 60, height: 40} ; const refused = (field: string) => ({ code: EngineErrorCode.InvalidArg, details:{ field} , } ); await expect( page.annotations.create({ subtype: 'square', box: rect, color: 'red'} ), ).rejects.toMatchObject(refused('color')); await expect( page.annotations.create({ subtype: 'square', box: rect, opacity: 1.5} ), ).rejects.toMatchObject(refused('opacity')); await expect( page.annotations.create({ subtype: 'square', box: rect, cloudyIntensity: 0} ), ).rejects.toMatchObject(refused('cloudyIntensity')); await expect( page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), icon: 'dragon', } as never), ).rejects.toMatchObject(refused('icon')); await expect( page.annotations.create({ subtype: 'free-text', box: rect, contents: 'x', verticalAlign: 'center', } as never), ).rejects.toMatchObject(refused('verticalAlign')); await expect( page.annotations.create({ subtype: 'link', rect, target:{ kind: 'javascript'} , } as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await expect( page.annotations.create({ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y), file:{ name: ''} , } , { resources:{ file: new Uint8Array([1])} } , ), ).rejects.toMatchObject(refused('file.name')); const{ annotation} = await page.annotations.create({ subtype: 'square', box: rect} ); await expect( page.annotations.update(annotation.ref, { opacity: -1} ), ).rejects.toMatchObject(refused('opacity')); const after = (await page.annotations.list()).annotations.find( (read) => annotationKey(read.ref) === annotationKey(annotation.ref), ); expect(after?.subtype === 'square' && after.opacity).toBe(1); } ); } ); test('opacity reads back as written', async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 300, y: 580, width: 60, height: 40} ; const{ annotation} = await page.annotations.create({ subtype: 'square', box: rect, opacity: 0.5, } ); expect(annotation.subtype === 'square' && annotation.opacity).toBe(0.5); const{ annotation: updated} = await page.annotations.update(annotation.ref, { opacity: 0.3, } ); expect(updated.subtype === 'square' && updated.opacity).toBe(0.3); const{ annotation: stamp} = await page.annotations.create({ subtype: 'stamp', box: rect, opacity: 0.75} , { resources:{ appearance: PNG_1X1} } , ); expect(stamp.subtype === 'stamp' && stamp.opacity).toBe(0.75); } ); } ); test('a new quad list replaces the old one, shorter or longer', async () =>{ await onAuthoringPage(async (page) =>{ const quad = (y: number) => ({ upperLeft:{ x: 40, y} , upperRight:{ x: 140, y} , lowerLeft:{ x: 40, y: y + 10} , lowerRight:{ x: 140, y: y + 10} , } ); for (const subtype of ['highlight', 'redact'] as const){ const{ annotation} = await page.annotations.create({ subtype, quadPoints: [quad(600), quad(620)], } as never); const{ annotation: fewer} = await page.annotations.update(annotation.ref, { quadPoints: [quad(640)], } ); const quads = (fewer as{ quadPoints: unknown[]} ).quadPoints; expect(quads.length).toBe(1); expect(fewer.rect).toMatchObject({ y: 640, height: 10} ); } const{ annotation} = await page.annotations.create({ subtype: 'highlight', quadPoints: [quad(600)], } ); await expect( page.annotations.update(annotation.ref, { quadPoints: []} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'quadPoints'} , } ); } ); } ); test("a redaction's box comes from its quads, and a mark needs one or the other", async () =>{ await onAuthoringPage(async (page) =>{ const{ annotation} = await page.annotations.create({ subtype: 'redact', quadPoints: [{ upperLeft:{ x: 50, y: 520} , upperRight:{ x: 150, y: 520} , lowerLeft:{ x: 50, y: 500} , lowerRight:{ x: 150, y: 500} , } , ], } ); expect(annotation.rect).toMatchObject({ x: 50, y: 500, width: 100, height: 20} ); await expect(page.annotations.create({ subtype: 'redact'} as never)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'rect'} , } , ); } ); } ); test('a review state brings its model; a custom state needs one', async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 420, y: 520, width: 20, height: 20} ; const{ annotation} = await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), state: 'accepted', } ); expect(annotation.subtype === 'text' && annotation.stateModel).toBe('review'); const{ annotation: marked} = await page.annotations.update(annotation.ref, { state: 'marked', } ); expect(marked.subtype === 'text' && marked.stateModel).toBe('marked'); await expect( page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), state: 'escalated', } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'stateModel'} , } ); const{ annotation: custom} = await page.annotations.create({ subtype: 'text', rect: iconRect(rect.x, rect.y), state: 'escalated', stateModel: 'triage', } ); const{ annotation: moved} = await page.annotations.update(custom.ref, { state: 'closed', } ); expect(moved.subtype === 'text' && moved.stateModel).toBe('triage'); } ); } ); test('a line without a caption flag reads captionEnabled: false, its default', async () =>{ await onAuthoringPage(async (page) =>{ const{ annotation} = await page.annotations.create({ subtype: 'line', linePoints:{ start:{ x: 40, y: 480} , end:{ x: 140, y: 480} } , } as never); expect(annotation.subtype === 'line' && annotation.captionEnabled).toBe(false); const{ annotation: flagged} = await page.annotations.update(annotation.ref, { captionEnabled: true, } ); expect(flagged.subtype === 'line' && flagged.captionEnabled).toBe(true); const{ annotation: cleared} = await page.annotations.update(annotation.ref, { captionEnabled: false, } ); expect(cleared.subtype === 'line' && cleared.captionEnabled).toBe(false); } ); } ); test('a stamp takes a one-page PDF', async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 420, y: 460, width: 60, height: 40} ; await expect( page.annotations.create({ subtype: 'stamp', box: rect} , { resources:{ appearance: TWO_PAGE_PDF} } , ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } ); } ); test('an annotation born inline exports by its baseIndex name', async () =>{ for (const fixture of options.documents){ const doc = await openFixture(engine, options, fixture); try{ const inline = (await doc.annotations.list()).annotations.find( (annotation) => annotation.ref.kind === 'baseIndex', ); if (!inline) continue; const bundle = await doc.annotations.export({ refs: [inline.ref]} ); expect(bundle.items.map((item) => item.data.subtype)).toEqual([inline.subtype]); return; } finally{ await doc.close(); } } throw new Error('no fixture document has an annotation born inline'); } ); test('a link read back can be sent back; its read-only target is kept', async () =>{ const doc = await openFixture(engine, options, options.readOnlyLink); try{ const link = (await doc.annotations.list()).annotations.find( (annotation) => annotation.subtype === 'link' && annotation.target !== null && annotation.target.kind !== 'goto' && annotation.target.kind !== 'uri', ) as Extract | undefined; expect(link !== undefined).toBe(true); const page = doc.page(link!.ref.page); const sentBack = await page.annotations.update(link!.ref, { ...link!, contents: 'Sent back', } as never); expect(sentBack.annotation.subtype === 'link' && sentBack.annotation.target).toEqual( link!.target, ); await expect( page.annotations.update(link!.ref, { target:{ kind: 'named', name: 'GoBack'} , } as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'target'} } ); } finally{ await doc.close(); } } ); test('deleting a note deletes its thread and popups, in one change', async () =>{ await onAuthoringPage(async (page, doc) =>{ const rect: PageBox ={ x: 460, y: 300, width: 20, height: 20} ; const find = async (ref: AnnotationRef) => (await page.annotations.list()).annotations.find( (annotation) => annotationKey(annotation.ref) === annotationKey(ref), ); const create = async (data: object) => (await page.annotations.create(data as never)).annotation; const note = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), contents: 'Note', } ); const notePopup = await create({ subtype: 'popup', rect, parent: note.ref} ); const reply = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), contents: 'Reply', reply:{ to: note.ref} , } ); const replyPopup = await create({ subtype: 'popup', rect, parent: reply.ref} ); const nested = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), contents: 'Nested', reply:{ to: reply.ref} , } ); const status = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), state: 'accepted', reply:{ to: note.ref} , } ); const bystander = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), contents: 'Unrelated', } ); const replyDelete = await page.annotations.delete(reply.ref); expect(replyDelete.meta.changedRefs.length).toBe(3); expect(await find(reply.ref)).toBe(undefined); expect(await find(nested.ref)).toBe(undefined); expect(await find(replyPopup.ref)).toBe(undefined); expect((await find(note.ref)) !== undefined).toBe(true); const deleted: unknown[][] = []; const stop = doc.events.on('annotations.deleted', (event) =>{ deleted.push(event.deleted); } ); try{ const{ meta} = await page.annotations.delete(note.ref); expect(meta.changedRefs.length).toBe(3); expect(meta.changedRefs[0]).toMatchObject({ kind: 'objectNumber'} ); expect(deleted).toEqual([meta.changedRefs]); } finally{ stop(); } for (const gone of [note, notePopup, status]) expect(await find(gone.ref)).toBe(undefined); expect((await find(bystander.ref)) !== undefined).toBe(true); } ); } ); test('a resource belongs to the kinds that take it', async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 300, y: 300, width: 60, height: 40} ; const refused ={ code: EngineErrorCode.InvalidArg} ; await expect( page.annotations.create({ subtype: 'stamp', box: rect} ), ).rejects.toMatchObject(refused); await expect( page.annotations.create({ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y), file:{ name: 'a.txt'} , } ), ).rejects.toMatchObject(refused); await expect( page.annotations.create({ subtype: 'square', box: rect} , { resources:{ appearance: PNG_1X1} } , ), ).rejects.toMatchObject(refused); await expect( page.annotations.create({ subtype: 'stamp', box: rect} , { resources:{ appearance: new TextEncoder().encode('not an image')} } , ), ).rejects.toMatchObject(refused); const{ annotation: created} = await page.annotations.create({ subtype: 'stamp', box: rect} , { resources:{ appearance: PNG_1X1} } , ); await expect( page.annotations.update(created.ref, { } , { resources:{ file: new Uint8Array([1])} } ), ).rejects.toMatchObject(refused); } ); } ); test("a new appearance replaces a stamp's drawing and keeps its data", async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 300, y: 400, width: 60, height: 40} ; const{ annotation: created} = await page.annotations.create({ subtype: 'stamp', box: rect, name: 'Approved'} , { resources:{ appearance: PNG_1X1} } , ); const result = await page.annotations.update( created.ref, { } , { resources:{ appearance: PNG_1X1} } , ); expect(result.appearance.changed).toBe(true); const{ modifiedAt: _before, ...expected} = created; const{ modifiedAt: _after, ...updated} = result.annotation; expect(updated).toEqual(expected); } ); } ); test("a stamp's fit is recorded, and a new box is filled the same way", async () =>{ await onAuthoringPage(async (page) =>{ const rect: PageBox ={ x: 300, y: 460, width: 60, height: 40} ; const fitOf = (dto:{ subtype: string} ) => (dto as{ fit?: unknown} ).fit; const plain = await page.annotations.create({ subtype: 'stamp', box: rect} , { resources:{ appearance: PNG_1X1} } , ); expect(fitOf(plain.annotation)).toBe('contain'); const{ annotation: created} = await page.annotations.create({ subtype: 'stamp', box: rect, fit: 'cover'} , { resources:{ appearance: PNG_1X1} } , ); expect(fitOf(created)).toBe('cover'); const moved = await page.annotations.update(created.ref, { box:{ ...rect, width: rect.width + 40} , } ); expect(fitOf(moved.annotation)).toBe('cover'); const refit = await page.annotations.update(created.ref, { fit: 'fill'} ); expect(fitOf(refit.annotation)).toBe('fill'); expect(refit.appearance.changed).toBe(true); const forgotten = await page.annotations.update(created.ref, { fit: null} ); expect(fitOf(forgotten.annotation)).toBe(null); } ); } ); test('an attached file is renamed by its data and replaced by its resource', async () =>{ await onAuthoringPage(async (page) =>{ const attachment = creatables().find(({ data} ) => data.subtype === 'file-attachment')!; const{ annotation: created} = await page.annotations.create(attachment.data, { resources: attachment.resources, } ); const fileOf = (dto:{ subtype: string} ) => (dto as{ file?:{ name: string; sizeBytes?: number; md5?: string} | null} ).file; const original = fileOf(created)!; const renamed = await page.annotations.update(created.ref, { file:{ ...original, name: 'renamed.txt', description: null} , } ); expect(renamed.appearance.changed).toBe(false); expect(fileOf(renamed.annotation)).toEqual({ name: 'renamed.txt', mimeType: 'text/plain', description: null, sizeBytes: original.sizeBytes, md5: original.md5, createdAt: (original as{ createdAt?: string} ).createdAt, modifiedAt: (original as{ modifiedAt?: string} ).modifiedAt, } ); const bytes = new TextEncoder().encode('replaced bytes'); const replaced = await page.annotations.update( created.ref, { } , { resources:{ file: bytes} } , ); expect(fileOf(replaced.annotation)).toMatchObject({ name: 'renamed.txt', mimeType: 'text/plain', sizeBytes: bytes.byteLength, } ); const read = await page.annotations.downloadResource(created.ref, 'file'); expect(new TextDecoder().decode(read)).toBe('replaced bytes'); } ); } ); } ); } runAnnotationExportConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationExportConformance.ts): export function runAnnotationExportConformance( runner: ConformanceTestRunner, options: AnnotationResourceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation export conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const onPage = async ( fixture: AnnotationResourceFixture, run: (page: PageHandle, doc: DocumentHandle, pageRef: PageRef) => Promise, ): Promise =>{ const doc = await options.open(engine, fixture); try{ const{ pages} = await doc.pages.list(); const pageRef = toPageRef(pages[0]!.ref.objectNumber); await run(doc.page(pageRef), doc, pageRef); } finally{ await doc.close(); } } ; const keysOf = (bundle: AnnotationBundle) => bundle.items.map((item) => annotationKey(item.data.ref)); test('exports the annotations as a read returns them, and each resource once', async () =>{ await onPage('authoring', async (page, doc, pageRef) =>{ const box = (x: number): PageBox => ({ x, y: 20, width: 60, height: 30} ); const first = await page.annotations.create({ subtype: 'stamp', box: box(20)} , { resources:{ appearance: BANDS_PDF} } , ); const second = await page.annotations.create({ subtype: 'stamp', box: box(100), opacity: 0.5} , { resources:{ appearance: BANDS_PDF} } , ); const image = await page.annotations.create({ subtype: 'stamp', box: box(180)} , { resources:{ appearance: BANDS_PNG} } , ); const file = await page.annotations.create({ subtype: 'file-attachment', rect: iconRect(box(260).x, box(260).y), file:{ name: 'note.txt'} , } , { resources:{ file: new TextEncoder().encode('attached')} } , ); const bundle = await doc.annotations.export(); await assertAnnotationBundle(bundle); const read = await doc.annotations.list({ pages: [pageRef]} ); expect(bundle.items.map((item) => item.data)).toEqual(read.annotations); const{ pages} = await doc.pages.list(); expect(bundle.pages).toEqual([{ page: pageRef, position: 0, size: pages[0]!.size} ]); const idOf = (ref: AnnotationRef, role: 'appearance' | 'file') => bundle.items.find((item) => annotationKey(item.data.ref) === annotationKey(ref))! .resources[role]!; expect(idOf(first.annotation.ref, 'appearance')).toBe( idOf(second.annotation.ref, 'appearance'), ); expect(Object.keys(bundle.resources)).toHaveLength(3); for (const [ref, role] of [ [first.annotation.ref, 'appearance'], [image.annotation.ref, 'appearance'], [file.annotation.ref, 'file'], ] as const){ const bytes = await page.annotations.downloadResource(ref, role); expect(sameBytes(bundle.resources[idOf(ref, role)]!, bytes)).toBe(true); } expect(await AnnotationTransfer.parse(AnnotationTransfer.stringify(bundle))).toEqual( bundle, ); } ); } ); test('exports a stamp another tool made as downloadResource returns it', async () =>{ await onPage('acrobat-stamps', async (page, doc) =>{ const bundle = await doc.annotations.export(); await assertAnnotationBundle(bundle); const stamps = bundle.items.filter((item) => item.data.subtype === 'stamp'); expect(stamps).toHaveLength(2); for (const stamp of stamps){ const bytes = await page.annotations.downloadResource(stamp.data.ref, 'appearance'); expect(sameBytes(bundle.resources[stamp.resources.appearance!]!, bytes)).toBe(true); } } ); } ); test('exports a document to the same file on every engine', async () =>{ const expected ={ 'acrobat-stamps': '612f68c76bcdbd06f9ff0d4b2f9e975a9cb6042e060ac301acceb9018874fc9c', 'acrobat-rewrapped': '370f5e29cd89ae185060bb71fffaae82fa4a94804aa0d5c635d29bdb93e27b44', } as const; for (const [fixture, hash] of Object.entries(expected)){ await onPage(fixture as AnnotationResourceFixture, async (_page, doc) =>{ const text = AnnotationTransfer.stringify(await doc.annotations.export()); const digest = new Uint8Array( await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)), ); let hex = ''; for (const byte of digest) hex += byte.toString(16).padStart(2, '0'); expect(hex).toBe(hash); } ); } } ); test('takes a comment with its thread, or only what it points at', async () =>{ await onPage('authoring', async (page, doc) =>{ const rect: PageBox ={ x: 300, y: 300, width: 20, height: 20} ; const create = async (draft: Parameters[0]) => (await page.annotations.create(draft)).annotation as Annotation; const note = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), contents: 'Check this', } ); const popup = await create({ subtype: 'popup', rect, parent: note.ref} ); const reply = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), reply:{ to: note.ref} , } ); const answer = await create({ subtype: 'text', rect: iconRect(rect.x, rect.y), reply:{ to: reply.ref} , } ); await create({ subtype: 'square', box: rect} ); const keys = (refs: Annotation[]) => refs.map((annotation) => annotationKey(annotation.ref)); expect(keysOf(await doc.annotations.export({ refs: [note.ref]} ))).toEqual( keys([note, popup, reply, answer]), ); expect( keysOf(await doc.annotations.export({ refs: [note.ref], include: 'references'} )), ).toEqual(keys([note, popup])); expect( keysOf(await doc.annotations.export({ refs: [answer.ref], include: 'references'} )), ).toEqual(keys([note, popup, reply, answer])); } ); } ); test('exports the document as it is now, after an edit and after a page move', async () =>{ await onPage('authoring', async (page, doc, first) =>{ const rect: PageBox ={ x: 20, y: 20, width: 60, height: 30} ; await page.annotations.create({ subtype: 'square', box: rect} ); const before = await doc.annotations.export(); expect(before.items).toHaveLength(1); await page.annotations.create({ subtype: 'circle', box: rect} ); expect((await doc.annotations.export()).items).toHaveLength(2); await doc.pages.insertBlank({ size:{ width: 200, height: 200} } , 'start'); expect((await doc.annotations.export()).pages.map((entry) => entry.position)).toEqual([1]); await doc.pages.reorder([first], 'start'); const moved = await doc.annotations.export(); expect(moved.pages).toEqual([{ ...before.pages[0]!, position: 0} ]); } ); } ); test('takes a selection larger than a URL holds', async () =>{ await onPage('authoring', async (page, doc) =>{ const{ annotation: seed} = await page.annotations.create({ subtype: 'square', box:{ x: 10, y: 10, width: 30, height: 30} , } ); const one = await doc.annotations.export({ refs: [seed.ref]} ); const many = await doc.annotations.import({ ...one, items: Array.from({ length: 300} , () => one.items[0]!)} , { attribution: 'stamp'} , ); const refs = many.annotations.map((annotation) => annotation.ref); const bundle = await doc.annotations.export({ refs} ); expect(bundle.items.map((item) => annotationKey(item.data.ref)).sort()).toEqual( refs.map(annotationKey).sort(), ); } ); } ); test('refuses a page or an annotation the document does not have', async () =>{ await onPage('authoring', async (_page, doc, pageRef) =>{ const missing ={ code: EngineErrorCode.NotFound} ; await expect(doc.annotations.export({ pages: [toPageRef(999_999)]} )).rejects.toMatchObject( missing, ); await expect( doc.annotations.export({ refs: [{ kind: 'objectNumber', page: pageRef, objectNumber: 999_999} ], } ), ).rejects.toMatchObject(missing); } ); } ); } ); } runAnnotationFlattenConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationFlattenConformance.ts): export function runAnnotationFlattenConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation flatten conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('flattens exactly the given refs and reports per-ref status', async () =>{ const doc = await openFixture(engine, options); try{ const layoutBefore = await doc.pages.list(); const pageObjectNumber = layoutBefore.pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); if (!page.annotations.flatten) return; const a = (await page.annotations.create(square(20, 20))).annotation.ref; const b = (await page.annotations.create(square(80, 20))).annotation.ref; const c = (await page.annotations.create(square(140, 20))).annotation.ref; await page.annotations.update(c, { subtype: 'square', hidden: true} ); const before = await page.annotations.list(); const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type === 'annotations.flattened') events.push(event); } ); const result = await page.annotations.flatten([a, c], { usage: 'display'} ); unsubscribe(); expect(AnnotationFlattenResultSchema.safeParse(result).success).toBe(true); expect(result.page.objectNumber).toBe(pageObjectNumber); expect(result.usage).toBe('display'); expect(result.results.map((item) => item.status)).toEqual(['applied', 'unchanged']); expect(result.meta.affectedPages).toEqual([page.ref]); expect(events).toHaveLength(1); expect(await doc.pages.list()).toEqual(layoutBefore); const after = await page.annotations.list(); expect(after.annotations.length).toBe(before.annotations.length - 1); expect(after.annotations.some((dto) => sameRef(dto.ref, b))).toBe(true); expect(after.annotations.some((dto) => sameRef(dto.ref, c))).toBe(true); expect(after.annotations.some((dto) => sameRef(dto.ref, a))).toBe(false); } finally{ await doc.close(); } } ); test('a ref on another page rejects InvalidArg and mutates nothing', async () =>{ const doc = await openFixture(engine, options); try{ const layout = await doc.pages.list(); if (layout.pages.length < 2) return; const page0 = doc.page(layout.pages[0].ref); const page1 = doc.page(layout.pages[1].ref); if (!page0.annotations.flatten) return; const own = (await page0.annotations.create(square(20, 100))).annotation.ref; const foreign = (await page1.annotations.create(square(20, 100))).annotation.ref; const countBefore = (await page0.annotations.list()).annotations.length; await expect(page0.annotations.flatten([own, foreign])).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); expect((await page0.annotations.list()).annotations.length).toBe(countBefore); } finally{ await doc.close(); } } ); test('an empty ref list rejects InvalidArg; an unknown ref rejects NotFound', async () =>{ const doc = await openFixture(engine, options); try{ const pageObjectNumber = (await doc.pages.list()).pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); if (!page.annotations.flatten) return; await expect(page.annotations.flatten([])).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); let unknown: unknown = null; try{ await page.annotations.flatten([{ kind: 'objectNumber', page: toPageRef(pageObjectNumber), objectNumber: 987654321, } , ]); } catch (error){ unknown = error; } expect(EngineError.is(unknown, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); } ); } runAnnotationImportConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationImportConformance.ts): export function runAnnotationImportConformance( runner: ConformanceTestRunner, options: AnnotationResourceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation import conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const twoCopies = async ( fixture: AnnotationResourceFixture, run: (source: DocumentHandle, target: DocumentHandle, page: PageRef) => Promise, ): Promise =>{ const source = await options.open(engine, fixture); const target = await options.open(engine, fixture); try{ const{ pages} = await source.pages.list(); await run(source, target, toPageRef(pages[0]!.ref.objectNumber)); } finally{ await source.close(); await target.close(); } } ; const box = (x: number): PageBox => ({ x, y: 300, width: 40, height: 30} ); const create = async ( page: PageHandle, draft: Parameters[0], resources?: Parameters[1], ) => (await page.annotations.create(draft, resources)).annotation as Annotation; test('imports every kind a create makes, as the export has it', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const page = source.page(pageRef); for (const{ data, resources} of creatables()) await create(page, data, { resources} ); await create( page, { subtype: 'stamp', box: box(20)} , { resources:{ appearance: BANDS_PDF} } , ); await create( page, { subtype: 'stamp', box: box(80), opacity: 0.5} , { resources:{ appearance: BANDS_PDF} } , ); const note = await create(page, { subtype: 'text', rect: iconRect(box(140).x, box(140).y), contents: 'Check', } ); await create(page, { subtype: 'popup', rect: box(200), parent: note.ref, open: true} ); await create(page, { subtype: 'text', rect: iconRect(box(140).x, box(140).y), reply:{ to: note.ref} , } ); await create(page, { subtype: 'link', rect: box(260), target:{ kind: 'goto', destination:{ kind: 'fit', page: pageRef} } , } ); const bundle = await source.annotations.export(); const result = await target.annotations.import(bundle, { attribution: 'stamp'} ); expect(result.dropped).toEqual([]); expect(result.annotations).toHaveLength(bundle.items.length); expect(result.refMap.map((pair) => annotationKey(pair.from))).toEqual( bundle.items.map((item) => annotationKey(item.data.ref)), ); const names = new Set(bundle.items.map((item) => item.data.nm)); for (const annotation of result.annotations){ expect(annotation.nm).toMatch(UUID_V7); expect(names.has(annotation.nm)).toBe(false); } const again = await target.annotations.export(); expect(comparable(again, result)).toEqual(comparable(bundle)); expect(Object.keys(again.resources).sort()).toEqual(Object.keys(bundle.resources).sort()); expect(result.annotations).toEqual(again.items.map((item) => item.data)); } ); } ); test('emits one annotations.created per annotation, as one transaction', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const page = source.page(pageRef); await create(page, { subtype: 'square', box: box(20)} ); await create(page, { subtype: 'circle', box: box(80)} ); const bundle = await source.annotations.export(); const events: DocumentEvent[] = []; target.events.subscribe((event) => events.push(event)); const result = await target.annotations.import(bundle, { attribution: 'stamp', opId: 'import-1', } ); const created = events.filter((event) => event.type === 'annotations.created'); expect(created).toHaveLength(2); created.forEach((event, index) =>{ if (event.type !== 'annotations.created') return; expect(event.annotation).toEqual(result.annotations[index]); expect(event.page).toEqual(pageRef); expect(event.origin.transaction).toEqual({ id: 'import-1', index, count: 2} ); } ); } ); } ); test('a restore leaves out a name the page has, and what points at it, then names on a repeat', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const page = source.page(pageRef); const taken = await create(page, { subtype: 'text', rect: iconRect(box(20).x, box(20).y), nm: 'taken', } ); const reply = await create(page, { subtype: 'text', rect: iconRect(box(20).x, box(20).y), reply:{ to: taken.ref} , } ); const free = await create(page, { subtype: 'square', box: box(80), nm: 'free'} ); const circle = await create(page, { subtype: 'circle', box: box(140)} ); await create(target.page(pageRef), { subtype: 'square', box: box(200), nm: 'taken'} ); const bundle = await source.annotations.export(); const first = await target.annotations.import(bundle, { attribution: 'restore'} ); expect(first.dropped).toEqual([{ ref: taken.ref, reason: 'name-conflict'} , { ref: reply.ref, reason: 'parent-dropped'} , ]); expect(first.refMap.map((pair) => annotationKey(pair.from))).toEqual( [free, circle].map((annotation) => annotationKey(annotation.ref)), ); expect(first.annotations.map((annotation) => annotation.nm)).toEqual(['free', circle.nm]); const second = await target.annotations.import(bundle, { attribution: 'restore'} ); expect(second.dropped.map((drop) => drop.reason)).toEqual([ 'name-conflict', 'parent-dropped', 'name-conflict', 'name-conflict', ]); expect(second.annotations).toEqual([]); } ); } ); test('a stamp makes copies: each gets a fresh name, so a name the page has is no conflict', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const page = source.page(pageRef); const taken = await create(page, { subtype: 'text', rect: iconRect(box(20).x, box(20).y), nm: 'taken', } ); await create(page, { subtype: 'text', rect: iconRect(box(20).x, box(20).y), reply:{ to: taken.ref} , } ); await create(target.page(pageRef), { subtype: 'square', box: box(200), nm: 'taken'} ); const bundle = await source.annotations.export(); for (let copy = 0; copy < 2; copy++){ const result = await target.annotations.import(bundle, { attribution: 'stamp'} ); expect(result.dropped).toEqual([]); const [note, reply] = result.annotations; expect(note!.nm).toMatch(UUID_V7); expect(reply!.nm).toMatch(UUID_V7); expect(note!.nm === 'taken').toBe(false); expect(reply!.reply?.to).toEqual(note!.ref); } } ); } ); test('puts each page where the options say', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ await create(source.page(pageRef), { subtype: 'square', box: box(20)} ); const bundle = await source.annotations.export(); await target.pages.insertBlank({ size:{ width: 300, height: 300} } , 'start'); const{ pages} = await target.pages.list(); const blank = toPageRef(pages[0]!.ref.objectNumber); const pageOf = (result: AnnotationImportResult) => result.annotations[0]!.ref.page; const same = await target.annotations.import(bundle, { attribution: 'stamp'} ); expect(pageOf(same)).toEqual(pageRef); const byPosition = await target.annotations.import(bundle, { attribution: 'stamp', pages: 'by-position', } ); expect(pageOf(byPosition)).toEqual(blank); const listed = await target.annotations.import(bundle, { attribution: 'stamp', pages: [{ from: pageRef, to: blank} ], } ); expect(pageOf(listed)).toEqual(blank); expect((await target.annotations.list({ pages: [blank]} )).annotations).toHaveLength(2); } ); } ); test('refuses before writing anything: an unmapped page, a tampered or oversized resource', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const page = source.page(pageRef); const stamp = await create( page, { subtype: 'stamp', box: box(20)} , { resources:{ appearance: PNG_1X1} } , ); await source.pages.insertBlank({ size:{ width: 300, height: 300} } , { after: pageRef} ); const{ pages} = await source.pages.list(); const second = toPageRef(pages[1]!.ref.objectNumber); await create(source.page(second), { subtype: 'square', box: box(20)} ); const bundle = await source.annotations.export(); const events: DocumentEvent[] = []; target.events.subscribe((event) => events.push(event)); const refused = ( candidate: AnnotationBundle, options: Parameters[1], ) => target.annotations.import(candidate, { attribution: 'stamp', ...options} ); await expect(refused(bundle, { } )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ pages: [encodePageKey(second)]} , } ); const stampOnly = (bytes: Uint8Array, id: `sha256-${ string} `): AnnotationBundle => ({ ...bundle, pages: bundle.pages.slice(0, 1), items: [{ data: stamp, resources:{ appearance: id} } ], resources:{ [id]: bytes} , } ); const tampered = stampOnly(PNG_1X1, await resourceIdOf(BANDS_PDF)); await expect(refused(tampered, { } )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const huge = PNG_1X1.slice(); new DataView(huge.buffer).setUint32(16, 10_000); new DataView(huge.buffer).setUint32(20, 10_000); await expect(refused(stampOnly(huge, await resourceIdOf(huge)), { } )).rejects.toMatchObject({ code: EngineErrorCode.PayloadTooLarge, details:{ limit: 'imagePixels'} , } ); expect((await target.annotations.list({ pages: [pageRef]} )).annotations).toEqual([]); expect(events).toEqual([]); } ); } ); const listed = async (doc: DocumentHandle, pageRef: PageRef) => (await doc.annotations.list({ pages: [pageRef]} )).annotations as Annotation[]; const keysOf = (annotations: readonly{ ref: AnnotationRef} []) => annotations.map((annotation) => annotationKey(annotation.ref)).sort(); const threadBundle = async (source: DocumentHandle, pageRef: PageRef) =>{ const page = source.page(pageRef); const note = await create(page, { subtype: 'text', rect: iconRect(box(20).x, box(20).y), contents: 'Check', } ); await create(page, { subtype: 'popup', rect: box(80), parent: note.ref} ); await create(page, { subtype: 'text', rect: iconRect(box(20).x, box(20).y), reply:{ to: note.ref} , } ); await create(page, { subtype: 'square', box: box(140)} ); await create( page, { subtype: 'stamp', box: box(200)} , { resources:{ appearance: PNG_1X1} } , ); return source.annotations.export(); } ; for (const attribution of ['stamp', 'restore'] as const){ test(`an import (${ attribution} ) is undone and redone: the same refs and attribution`, async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const bundle = await threadBundle(source, pageRef); const before = keysOf(await listed(target, pageRef)); const imported = await target.annotations.import(bundle, { attribution} ); expect(imported.meta.undoable).toBe(true); expect(imported.annotations).toHaveLength(5); const undo = await target.apply({ undoOf: imported.meta.opId} ); expect(undo.items.map((item) => item.type)).toEqual([ 'annotations.delete', 'annotations.delete', 'annotations.delete', ]); expect(keysOf(await listed(target, pageRef))).toEqual(before); await target.apply({ undoOf: undo.meta.opId} ); const back = await listed(target, pageRef); const byKey = new Map( back.map((annotation) => [annotationKey(annotation.ref), annotation]), ); for (const annotation of imported.annotations){ const again = byKey.get(annotationKey(annotation.ref)); expect(again).toMatchObject({ nm: annotation.nm, userId: annotation.userId, createdBy: annotation.createdBy, author: annotation.author, rect: annotation.rect, } ); } } ); } ); } test('an imported annotation changed since stays; the rest of the import goes', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ const page = source.page(pageRef); await create(page, { subtype: 'square', box: box(20)} ); await create(page, { subtype: 'circle', box: box(80)} ); const bundle = await source.annotations.export(); const imported = await target.annotations.import(bundle, { attribution: 'stamp'} ); const [square, circle] = imported.annotations; await target.page(pageRef).annotations.update(square!.ref, { color: '#00aa00'} ); const undo = await target.apply({ undoOf: imported.meta.opId} ); expect(undo.items.map((item) => item.type).sort()).toEqual([ 'annotations.delete', 'skipped', ]); const left = keysOf(await listed(target, pageRef)); expect(left.includes(annotationKey(square!.ref))).toBe(true); expect(left.includes(annotationKey(circle!.ref))).toBe(false); } ); } ); test('a retry under the same opId answers again and writes nothing more', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ await create(source.page(pageRef), { subtype: 'square', box: box(20)} ); const bundle = await source.annotations.export(); const first = await target.annotations.import(bundle, { attribution: 'stamp', opId: 'import-retry', } ); const again = await target.annotations.import(bundle, { attribution: 'stamp', opId: 'import-retry', } ); expect(keysOf(again.annotations)).toEqual(keysOf(first.annotations)); const squares = (await listed(target, pageRef)).filter((a) => a.subtype === 'square'); expect(squares).toHaveLength(1); } ); } ); test("doc.apply takes no import: restoring attribution stays the import verb's", async () =>{ await twoCopies('authoring', async (source, target) =>{ const bundle = await source.annotations.export(); const change ={ ops: [{ type: 'annotations.import', bundle, attribution: 'restore'} ]} ; await expect(target.apply(change as unknown as Change)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } ); } ); test('a final write ends undo for an import before it', async () =>{ await twoCopies('authoring', async (source, target, pageRef) =>{ await create(source.page(pageRef), { subtype: 'square', box: box(20)} ); const bundle = await source.annotations.export(); const imported = await target.annotations.import(bundle, { attribution: 'stamp'} ); await target.page(pageRef).annotations.flatten([imported.annotations[0]!.ref]); await expect(target.apply({ undoOf: imported.meta.opId} )).rejects.toMatchObject({ code: EngineErrorCode.UndoUnavailable, } ); } ); } ); test("undoing a restoring import takes the import's rights, not the per-annotation ones", async () =>{ if (!options.openScoped) return; const scope = [ 'doc.open', 'doc.render', 'doc.download', 'doc.annotate.modify', 'doc.annotate.import', 'annotations:delete:self', ]; const source = await options.open(engine, 'authoring'); const target = await options.openScoped(engine, 'authoring', scope); try{ const{ pages} = await source.pages.list(); const pageRef = toPageRef(pages[0]!.ref.objectNumber); await create(source.page(pageRef), { subtype: 'square', box: box(20)} ); const bundle = await source.annotations.export(); const imported = await target.annotations.import(bundle, { attribution: 'restore'} ); const [square] = imported.annotations; const refused = await target .page(pageRef) .annotations.delete(square!.ref) .then( () => null, (error: unknown) => error, ); expect(isPermissionRefusal(refused)).toBe(true); const undo = await target.apply({ undoOf: imported.meta.opId} ); const key = annotationKey(square!.ref); expect(keysOf(await listed(target, pageRef)).includes(key)).toBe(false); await target.apply({ undoOf: undo.meta.opId} ); expect(keysOf(await listed(target, pageRef)).includes(key)).toBe(true); } finally{ await source.close(); await target.close(); } } ); } ); } runAnnotationMutationConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationMutationConformance.ts): export function runAnnotationMutationConformance( runner: ConformanceTestRunner, options: AnnotationMutationConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const fix = options.fixture; const quad = fix.createQuad ?? DEFAULT_QUAD; const shapeRect = fix.createShapeRect ?? DEFAULT_SHAPE_RECT; const vertices = fix.createVertices ?? DEFAULT_VERTICES; const linePoints = fix.createLinePoints ?? DEFAULT_LINE_POINTS; const inkStrokes = fix.createInkList ?? DEFAULT_INK_STROKES; describe(`annotation mutation conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('create appends on top without moving the others', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const before = await page.annotations.list(); const beforeCount = before.annotations.length; const draft: HighlightDraft ={ subtype: 'highlight', contents: 'mutation conformance: created', color: '#c86432', opacity: 0.5, quadPoints: quad, } ; const result = await page.annotations.create(draft); expect(AnnotationCreateResultSchema.safeParse(result).success).toBe(true); expect(result.meta.affectedPages.length).toBe(1); expect(result.meta.affectedPages[0].objectNumber).toBe(fix.pageObjectNumber); expect('cacheDelta' in result.meta).toBe(true); expect(result.annotation.subtype).toBe('highlight'); expect(result.annotation.ref.kind).toBe('objectNumber'); expect(result.meta.changedRefs.length).toBe(1); const after = await page.annotations.list(); expect(after.annotations.length).toBe(beforeCount + 1); expect(annotationKey(after.annotations.at(-1)!.ref)).toBe( annotationKey(result.annotation.ref), ); } finally{ await doc.close(); } } ); test('create and update write each annotation flag as its own field', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft: HighlightDraft ={ subtype: 'highlight', contents: 'mutation conformance: flags', color: '#0a141e', opacity: 1, quadPoints: quad, print: true, } ; const created = await page.annotations.create(draft); expect(created.annotation.print).toBe(true); expect(created.annotation.hidden).toBe(false); const hidden = await page.annotations.update(created.annotation.ref, { hidden: true} ); expect(hidden.annotation.hidden).toBe(true); expect(hidden.annotation.print).toBe(true); const cleared = await page.annotations.update(created.annotation.ref, { print: false} ); expect(cleared.annotation.print).toBe(false); expect(cleared.annotation.hidden).toBe(true); } finally{ await doc.close(); } } ); test('create shape annotations (circle + square) round-trip shape fields', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const circleDraft: CircleDraft ={ subtype: 'circle', contents: 'mutation conformance: circle', box: shapeRect, interiorColor: '#ff0000', color: '#0000ff', strokeWidth: 3, borderStyle: 'solid', opacity: 0.6, } ; const circle = await page.annotations.create(circleDraft); expect(AnnotationCreateResultSchema.safeParse(circle).success).toBe(true); expect(circle.annotation.subtype).toBe('circle'); expect(circle.annotation.ref.kind).toBe('objectNumber'); if (circle.annotation.subtype === 'circle'){ expect(circle.annotation.interiorColor).toBe('#ff0000'); expect(circle.annotation.color).toBe('#0000ff'); expect(circle.annotation.strokeWidth).toBe(3); expect(circle.annotation.borderStyle).toBe('solid'); expect(Math.round(circle.annotation.opacity * 100) / 100).toBe(0.6); expect(circle.annotation.box).toEqual(shapeRect); expect(circle.annotation.rect).toEqual(shapeRect); } const squareDraft: SquareDraft ={ subtype: 'square', contents: 'mutation conformance: square', box: shapeRect, interiorColor: null, color: '#008000', strokeWidth: 2, borderStyle: 'dashed', dashArray: [3, 2], opacity: 1, } ; const square = await page.annotations.create(squareDraft); expect(AnnotationCreateResultSchema.safeParse(square).success).toBe(true); expect(square.annotation.subtype).toBe('square'); if (square.annotation.subtype === 'square'){ expect(square.annotation.interiorColor).toBe(null); expect(square.annotation.color).toBe('#008000'); expect(square.annotation.borderStyle).toBe('dashed'); expect(square.annotation.dashArray).toEqual([3, 2]); } const after = await page.annotations.list(); const subtypes = after.annotations.map((a) => a.subtype); expect(subtypes.includes('circle')).toBe(true); expect(subtypes.includes('square')).toBe(true); } finally{ await doc.close(); } } ); test('a cloudy border reaches past the box, and rect takes it in', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const plainDraft: SquareDraft ={ subtype: 'square', contents: 'mutation conformance: cloudy border', box: shapeRect, color: '#008000', strokeWidth: 2, borderStyle: 'solid', opacity: 1, cloudyIntensity: null, } ; const plain = await page.annotations.create(plainDraft); expect(plain.annotation.subtype).toBe('square'); if (plain.annotation.subtype === 'square'){ expect(plain.annotation.cloudyIntensity).toBe(null); expect(plain.annotation.rect).toEqual(shapeRect); } const cloudy = await page.annotations.update(plain.annotation.ref, { subtype: 'square', cloudyIntensity: 2, } ); expect(cloudy.annotation.subtype).toBe('square'); if (cloudy.annotation.subtype === 'square'){ expect(cloudy.annotation.cloudyIntensity).toBe(2); const{ box, rect} = cloudy.annotation; for (const edge of ['x', 'y', 'width', 'height'] as const){ expect(Math.abs(box[edge] - shapeRect[edge]) < 1e-3).toBe(true); } expect(rect.x < box.x - 1 && rect.y < box.y - 1).toBe(true); expect(rect.x + rect.width > box.x + box.width + 1).toBe(true); expect(rect.y + rect.height > box.y + box.height + 1).toBe(true); } const solid = await page.annotations.update(plain.annotation.ref, { subtype: 'square', cloudyIntensity: null, } ); expect(solid.annotation.subtype).toBe('square'); if (solid.annotation.subtype === 'square'){ expect(solid.annotation.cloudyIntensity).toBe(null); expect(solid.annotation.rect).toEqual(shapeRect); } const polyDraft: PolygonDraft ={ subtype: 'polygon', contents: 'mutation conformance: polygon cloudy tri-state', vertices, color: '#0000ff', strokeWidth: 2, borderStyle: 'solid', opacity: 1, cloudyIntensity: 1, } ; const poly = await page.annotations.create(polyDraft); expect(poly.annotation.subtype).toBe('polygon'); if (poly.annotation.subtype === 'polygon'){ expect(poly.annotation.cloudyIntensity).toBe(1); } const polySolid = await page.annotations.update(poly.annotation.ref, { subtype: 'polygon', cloudyIntensity: null, } ); expect(polySolid.annotation.subtype).toBe('polygon'); if (polySolid.annotation.subtype === 'polygon'){ expect(polySolid.annotation.cloudyIntensity).toBe(null); } } finally{ await doc.close(); } } ); test('update echoes the appearance verdict: moves preserve /AP, restyles re-bake', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft: SquareDraft ={ subtype: 'square', contents: 'mutation conformance: appearance echo', box: shapeRect, color: '#c80000', strokeWidth: 2, borderStyle: 'solid', opacity: 1, } ; const created = await page.annotations.create(draft); const moved = await page.annotations.update(created.annotation.ref, { subtype: 'square', box:{ ...shapeRect, x: shapeRect.x + 12, y: shapeRect.y + 8} , color: '#c80000', strokeWidth: 2, opacity: 1, } ); expect(moved.appearance).toEqual({ action: 'preserved', changed: false} ); const flagged = await page.annotations.update(created.annotation.ref, { subtype: 'square', print: true, } ); expect(flagged.appearance).toEqual({ action: 'preserved', changed: false} ); const restyled = await page.annotations.update(created.annotation.ref, { subtype: 'square', interiorColor: '#ffd600', } ); expect(restyled.appearance).toEqual({ action: 'regenerated', changed: true} ); const resized = await page.annotations.update(created.annotation.ref, { subtype: 'square', box:{ ...shapeRect, width: shapeRect.width + 40} , } ); expect(resized.appearance).toEqual({ action: 'regenerated', changed: true} ); } finally{ await doc.close(); } } ); test('a partial /DA patch preserves the unpatched font members', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft: FreeTextDraft ={ subtype: 'free-text', intent: 'free-text', contents: 'DA read-modify-write', box: shapeRect, fontFamily: 'times-roman', fontSize: 14, textAlign: 'left', color: '#c80000', } ; const created = await page.annotations.create(draft); expect(created.annotation.subtype).toBe('free-text'); if (created.annotation.subtype === 'free-text'){ expect(created.annotation.fontFamily).toBe('times-roman'); } const sized = await page.annotations.update(created.annotation.ref, { subtype: 'free-text', fontSize: 18, } ); expect(sized.annotation.subtype).toBe('free-text'); if (sized.annotation.subtype === 'free-text'){ expect(sized.annotation.fontFamily).toBe('times-roman'); expect(sized.annotation.fontSize).toBe(18); expect(sized.annotation.color).toBe('#c80000'); } const recolored = await page.annotations.update(created.annotation.ref, { subtype: 'free-text', color: '#0000c8', } ); if (recolored.annotation.subtype === 'free-text'){ expect(recolored.annotation.fontFamily).toBe('times-roman'); expect(recolored.annotation.fontSize).toBe(18); expect(recolored.annotation.color).toBe('#0000c8'); } } finally{ await doc.close(); } } ); test('a turn stays until changed: a box move keeps it, null straightens', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft: SquareDraft ={ subtype: 'square', contents: 'transform tri-state', box: shapeRect, color: '#0000ff', strokeWidth: 2, borderStyle: 'solid', opacity: 1, rotation: 90, } ; const created = await page.annotations.create(draft); expect(created.annotation.subtype).toBe('square'); if (created.annotation.subtype === 'square'){ expect(created.annotation.rotation).toBe(90); } const turnedRect = created.annotation.rect; expect(turnedRect.width).toBe(shapeRect.height); expect(turnedRect.height).toBe(shapeRect.width); const d ={ x: 15, y: -10} ; const shift = (r: PageBox): PageBox => ({ ...r, x: r.x + d.x, y: r.y + d.y} ); const moved = await page.annotations.update(created.annotation.ref, { subtype: 'square', box: shift(shapeRect), rotation: 90, } ); expect(moved.appearance).toEqual({ action: 'preserved', changed: false} ); expect(moved.annotation.rect).toEqual(shift(turnedRect)); if (moved.annotation.subtype === 'square'){ expect(moved.annotation.rotation).toBe(90); } const boxOnly = await page.annotations.update(created.annotation.ref, { subtype: 'square', box: shapeRect, } ); if (boxOnly.annotation.subtype === 'square'){ expect(boxOnly.annotation.rotation).toBe(90); } const straightened = await page.annotations.update(created.annotation.ref, { subtype: 'square', rotation: null, } ); if (straightened.annotation.subtype === 'square'){ expect(straightened.annotation.rotation).toBe(null); expect(straightened.annotation.box).toEqual(shapeRect); expect(straightened.annotation.rect).toEqual(shapeRect); } } finally{ await doc.close(); } } ); test('a line, polyline, polygon or ink: rect is what the engine draws', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const contains = (outer: PageBox, inner: PageBox) => outer.x <= inner.x + 1e-3 && outer.y <= inner.y + 1e-3 && outer.x + outer.width >= inner.x + inner.width - 1e-3 && outer.y + outer.height >= inner.y + inner.height - 1e-3; const area = (r: PageBox) => r.width * r.height; const grown = (r: PageBox, by: number): PageBox => ({ x: r.x - by, y: r.y - by, width: r.width + 2 * by, height: r.height + 2 * by, } ); const line = (lineEndings: LineDraft['lineEndings']) => page.annotations.create({ subtype: 'line', linePoints, color: '#000000', strokeWidth: 2, lineEndings, } satisfies LineDraft); const plain = (await line({ start: 'none', end: 'none'} )).annotation; const arrowed = (await line({ start: 'closed-arrow', end: 'closed-arrow'} )).annotation; const ends = pagePointsBounds([linePoints.start, linePoints.end]); expect(contains(plain.rect, grown(ends, 0.5))).toBe(true); expect(contains(arrowed.rect, plain.rect)).toBe(true); expect(area(arrowed.rect) > area(plain.rect)).toBe(true); const ink = (strokeWidth: number) => page.annotations.create({ subtype: 'ink', inkList: inkStrokes, color: '#1d4ed8', strokeWidth, } satisfies InkDraft); const thin = (await ink(1)).annotation; const wide = (await ink(6)).annotation; const drawn = pagePointsBounds(inkStrokes.flat()); expect(contains(thin.rect, grown(drawn, 0.5))).toBe(true); expect(contains(wide.rect, grown(drawn, 3))).toBe(true); expect(wide.rect.width > thin.rect.width + 4.9).toBe(true); const narrowed = await page.annotations.update(wide.ref, { subtype: 'ink', strokeWidth: 1, } ); expect(near(narrowed.annotation.rect.x, thin.rect.x)).toBe(true); expect(near(narrowed.annotation.rect.width, thin.rect.width)).toBe(true); } finally{ await doc.close(); } } ); test('points are upright: rotation turns them about the middle of their box', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const expectPoints = (actual: readonly PagePoint[], expected: readonly PagePoint[]) =>{ expect(actual.length).toBe(expected.length); actual.forEach((point, i) =>{ expect(near(point.x, expected[i]!.x)).toBe(true); expect(near(point.y, expected[i]!.y)).toBe(true); } ); } ; const created = await page.annotations.create({ subtype: 'polygon', vertices, color: '#0000ff', strokeWidth: 2, rotation: 90, } satisfies PolygonDraft); const polygon = created.annotation; if (polygon.subtype !== 'polygon') throw new Error('expected a polygon'); expect(polygon.rotation).toBe(90); expectPoints(polygon.vertices, vertices); const turn = pageTurnOfUpright(vertices, 90); const drawn = vertices.map((point) => pagePointTurned(point, turn)); expectPoints(drawnPointsOf(polygon)![0]!, drawn); const drawnBounds = pagePointsBounds(drawn); expect(polygon.rect.x <= drawnBounds.x).toBe(true); expect(polygon.rect.y <= drawnBounds.y).toBe(true); expect(polygon.rect.x + polygon.rect.width >= drawnBounds.x + drawnBounds.width).toBe(true); expect(polygon.rect.y + polygon.rect.height >= drawnBounds.y + drawnBounds.height).toBe( true, ); const d ={ x: 15, y: -10} ; const moved = await page.annotations.update(polygon.ref, { subtype: 'polygon', vertices: vertices.map((point) => ({ x: point.x + d.x, y: point.y + d.y} )), } ); expect(moved.appearance).toEqual({ action: 'preserved', changed: false} ); if (moved.annotation.subtype !== 'polygon') throw new Error('expected a polygon'); expect(moved.annotation.rotation).toBe(90); expect(near(moved.annotation.rect.x, polygon.rect.x + d.x)).toBe(true); expect(near(moved.annotation.rect.y, polygon.rect.y + d.y)).toBe(true); const turned = await page.annotations.update(polygon.ref, { subtype: 'polygon', vertices, rotation: 45, } ); expect(turned.appearance.action === 'preserved').toBe(false); if (turned.annotation.subtype !== 'polygon') throw new Error('expected a polygon'); expect(turned.annotation.rotation).toBe(45); expectPoints(turned.annotation.vertices, vertices); const straightened = await page.annotations.update(polygon.ref, { subtype: 'polygon', rotation: null, } ); if (straightened.annotation.subtype !== 'polygon') throw new Error('expected a polygon'); expect(straightened.annotation.rotation).toBe(null); expectPoints(straightened.annotation.vertices, vertices); expectPoints(drawnPointsOf(straightened.annotation)![0]!, vertices); } finally{ await doc.close(); } } ); test("a note's icon fills its rect, and moves and grows with it", async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const rect = iconRect(shapeRect.x, shapeRect.y); const created = await page.annotations.create({ subtype: 'text', rect, icon: 'comment', } satisfies TextDraft); const note = created.annotation; if (note.subtype !== 'text') throw new Error('expected a note'); expect(note.rect).toEqual(rect); const to = iconRect(rect.x + 30, rect.y + 15); const moved = await page.annotations.update(note.ref, { subtype: 'text', rect: to} ); expect(moved.annotation.rect).toEqual(to); expect(moved.appearance.changed).toBe(false); const bigger ={ ...to, width: 50, height: 50} ; const grown = await page.annotations.update(note.ref, { subtype: 'text', rect: bigger} ); expect(grown.annotation.rect).toEqual(bigger); expect(grown.appearance.changed).toBe(true); } finally{ await doc.close(); } } ); test("a new rect puts a drawing there, as a script's annot.rect does in Acrobat", async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const offset = (r: PageBox, dx: number, dy: number): PageBox => ({ ...r, x: r.x + dx, y: r.y + dy, } ); const expectPoint = (actual: PagePoint, expected: PagePoint) =>{ expect(near(actual.x, expected.x) && near(actual.y, expected.y)).toBe(true); } ; const expectRect = (actual: PageBox, expected: PageBox) =>{ expectPoint(actual, expected); expectPoint({ x: actual.width, y: actual.height} , { x: expected.width, y: expected.height} , ); } ; const refused ={ code: EngineErrorCode.InvalidArg, details:{ field: 'rect'} } ; const created = ( await page.annotations.create({ subtype: 'line', linePoints, color: '#000000', } satisfies LineDraft) ).annotation; if (created.subtype !== 'line') throw new Error('expected a line'); const movedTo = offset(created.rect, 40, 20); const moved = await page.annotations.update(created.ref, { subtype: 'line', rect: movedTo, } ); if (moved.annotation.subtype !== 'line') throw new Error('expected a line'); expectRect(moved.annotation.rect, movedTo); expectPoint(moved.annotation.linePoints.start, { x: linePoints.start.x + 40, y: linePoints.start.y + 20, } ); expectPoint(moved.annotation.linePoints.end, { x: linePoints.end.x + 40, y: linePoints.end.y + 20, } ); expect(moved.appearance.changed).toBe(false); const from = moved.annotation.rect; const to ={ ...from, width: from.width + 60, height: from.height + 30} ; const onto = (point: PagePoint): PagePoint => ({ x: to.x + ((point.x - from.x) * to.width) / from.width, y: to.y + ((point.y - from.y) * to.height) / from.height, } ); const stretched = await page.annotations.update(created.ref, { subtype: 'line', rect: to} ); if (stretched.annotation.subtype !== 'line') throw new Error('expected a line'); expectPoint(stretched.annotation.linePoints.start, onto(moved.annotation.linePoints.start)); expectPoint(stretched.annotation.linePoints.end, onto(moved.annotation.linePoints.end)); expect(stretched.appearance.changed).toBe(true); const back = await page.annotations.update(created.ref, { subtype: 'line', rect: stretched.annotation.rect, contents: 'sent back', } ); if (back.annotation.subtype !== 'line') throw new Error('expected a line'); expect(back.annotation.rect).toEqual(stretched.annotation.rect); expect(back.annotation.linePoints).toEqual(stretched.annotation.linePoints); expect(back.annotation.contents).toBe('sent back'); const rect = back.annotation.rect; await expect( page.annotations.update(created.ref, { subtype: 'line', rect: offset(rect, 5, 5), linePoints:{ start: linePoints.start, end:{ x: 90, y: 90} } , } ), ).rejects.toMatchObject(refused); await expect( page.annotations.update(created.ref, { subtype: 'line', rect:{ ...rect, width: 0} , } ), ).rejects.toMatchObject(refused); const highlight = ( await page.annotations.create({ subtype: 'highlight', quadPoints: quad, color: '#ffff00', } satisfies HighlightDraft) ).annotation; const highlightTo = offset(highlight.rect, 10, 15); const movedHighlight = await page.annotations.update(highlight.ref, { subtype: 'highlight', rect: highlightTo, } ); if (movedHighlight.annotation.subtype !== 'highlight') throw new Error('expected a highlight'); expectRect(movedHighlight.annotation.rect, highlightTo); expectPoint(movedHighlight.annotation.quadPoints[0]!.upperLeft, { x: quad[0]!.upperLeft.x + 10, y: quad[0]!.upperLeft.y + 15, } ); const turned = ( await page.annotations.create({ subtype: 'square', box: shapeRect, rotation: 30, color: '#0000ff', } satisfies SquareDraft) ).annotation; if (turned.subtype !== 'square') throw new Error('expected a square'); const turnedTo = offset(turned.rect, 25, 5); const movedTurned = await page.annotations.update(turned.ref, { subtype: 'square', rect: turnedTo, } ); if (movedTurned.annotation.subtype !== 'square') throw new Error('expected a square'); expectRect(movedTurned.annotation.box, offset(shapeRect, 25, 5)); expect(movedTurned.annotation.rotation).toBe(30); await expect( page.annotations.update(turned.ref, { subtype: 'square', rect:{ ...turnedTo, width: turnedTo.width + 20} , } ), ).rejects.toMatchObject(refused); } finally{ await doc.close(); } } ); test('create vertex + line annotations (polygon/polyline/line) round-trip geometry', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const polygonDraft: PolygonDraft ={ subtype: 'polygon', contents: 'mutation conformance: polygon', vertices, interiorColor: '#ffc800', color: '#0000ff', strokeWidth: 2, borderStyle: 'solid', opacity: 0.8, } ; const polygon = await page.annotations.create(polygonDraft); expect(AnnotationCreateResultSchema.safeParse(polygon).success).toBe(true); expect(polygon.annotation.subtype).toBe('polygon'); if (polygon.annotation.subtype === 'polygon'){ expect(polygon.annotation.vertices.length).toBe(vertices.length); expect(polygon.annotation.color).toBe('#0000ff'); expect(polygon.annotation.interiorColor).toBe('#ffc800'); } const polylineDraft: PolylineDraft ={ subtype: 'polyline', contents: 'mutation conformance: polyline', vertices, interiorColor: null, color: '#c80000', strokeWidth: 2, borderStyle: 'solid', opacity: 1, lineEndings:{ start: 'open-arrow', end: 'closed-arrow'} , } ; const polyline = await page.annotations.create(polylineDraft); expect(AnnotationCreateResultSchema.safeParse(polyline).success).toBe(true); expect(polyline.annotation.subtype).toBe('polyline'); if (polyline.annotation.subtype === 'polyline'){ expect(polyline.annotation.vertices.length).toBe(vertices.length); expect(polyline.annotation.lineEndings.start).toBe('open-arrow'); expect(polyline.annotation.lineEndings.end).toBe('closed-arrow'); } const lineDraft: LineDraft ={ subtype: 'line', contents: 'mutation conformance: line', linePoints, interiorColor: null, color: '#008080', strokeWidth: 2, borderStyle: 'solid', opacity: 1, lineEndings:{ start: 'none', end: 'open-arrow'} , } ; const line = await page.annotations.create(lineDraft); expect(AnnotationCreateResultSchema.safeParse(line).success).toBe(true); expect(line.annotation.subtype).toBe('line'); if (line.annotation.subtype === 'line'){ expect(Math.round(line.annotation.linePoints.start.x)).toBe( Math.round(linePoints.start.x), ); expect(Math.round(line.annotation.linePoints.end.y)).toBe(Math.round(linePoints.end.y)); expect(line.annotation.lineEndings.end).toBe('open-arrow'); } const inkDraft: InkDraft ={ subtype: 'ink', contents: 'mutation conformance: ink', inkList: inkStrokes, color: '#1d4ed8', strokeWidth: 3, borderStyle: 'solid', opacity: 1, } ; const ink = await page.annotations.create(inkDraft); expect(AnnotationCreateResultSchema.safeParse(ink).success).toBe(true); expect(ink.annotation.subtype).toBe('ink'); if (ink.annotation.subtype === 'ink'){ expect(ink.annotation.inkList.length).toBe(inkStrokes.length); expect(ink.annotation.inkList[0]!.length).toBe(inkStrokes[0]!.length); expect(ink.annotation.color).toBe('#1d4ed8'); expect(ink.annotation.intent).toBe(null); expect(ink.annotation.blendMode).toBe('normal'); expect('interiorColor' in ink.annotation).toBe(false); } const after = await page.annotations.list(); const subtypes = after.annotations.map((a) => a.subtype); expect(subtypes.includes('polygon')).toBe(true); expect(subtypes.includes('polyline')).toBe(true); expect(subtypes.includes('line')).toBe(true); expect(subtypes.includes('ink')).toBe(true); } finally{ await doc.close(); } } ); test('create free-text + callout round-trip text/colour/intent fields', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const freeTextDraft: FreeTextDraft ={ subtype: 'free-text', intent: 'free-text', contents: 'mutation conformance: free text', box: shapeRect, fontFamily: 'helvetica', fontSize: 14, textAlign: 'center', color: '#14283c', interiorColor: '#fafad2', opacity: 1, strokeWidth: 1, borderStyle: 'solid', } ; const freeText = await page.annotations.create(freeTextDraft); expect(AnnotationCreateResultSchema.safeParse(freeText).success).toBe(true); expect(freeText.annotation.subtype).toBe('free-text'); if (freeText.annotation.subtype === 'free-text'){ expect(freeText.annotation.intent).toBe('free-text'); expect(freeText.annotation.fontFamily).toBe('helvetica'); expect(freeText.annotation.fontSize).toBe(14); expect(freeText.annotation.textAlign).toBe('center'); expect(freeText.annotation.color).toBe('#14283c'); expect(freeText.annotation.interiorColor).toBe('#fafad2'); expect(freeText.annotation.fontColor).toBe('#000000'); } const calloutDraft: FreeTextDraft ={ subtype: 'free-text', intent: 'free-text-callout', contents: 'mutation conformance: callout', box: shapeRect, fontFamily: 'times-roman', fontSize: 12, textAlign: 'left', color: '#000000', fontColor: '#c80000', interiorColor: null, opacity: 1, strokeWidth: 1, borderStyle: 'solid', calloutLine: DEFAULT_CALLOUT_LINE, lineEnding: 'open-arrow', } ; const callout = await page.annotations.create(calloutDraft); expect(AnnotationCreateResultSchema.safeParse(callout).success).toBe(true); expect(callout.annotation.subtype).toBe('free-text'); if (callout.annotation.subtype === 'free-text'){ expect(callout.annotation.intent).toBe('free-text-callout'); expect(callout.annotation.interiorColor).toBe(null); expect(callout.annotation.fontColor).toBe('#c80000'); expect(callout.annotation.color).toBe('#000000'); expect(callout.annotation.calloutLine?.length).toBe(DEFAULT_CALLOUT_LINE.length); expect(callout.annotation.lineEnding).toBe('open-arrow'); expect(callout.annotation.box).toEqual(shapeRect); const{ rect} = callout.annotation; for (const point of DEFAULT_CALLOUT_LINE){ expect(point.x >= rect.x && point.x <= rect.x + rect.width).toBe(true); expect(point.y >= rect.y && point.y <= rect.y + rect.height).toBe(true); } } const after = await page.annotations.list(); const freeTexts = after.annotations.filter((a) => a.subtype === 'free-text'); expect(freeTexts.length >= 2).toBe(true); } finally{ await doc.close(); } } ); test('update a free-text patches alignment + colours and is non-structural', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'free-text', intent: 'free-text', contents: 'free-text-update-base', box: shapeRect, fontFamily: 'helvetica', fontSize: 12, textAlign: 'left', color: '#000000', interiorColor: null, opacity: 1, strokeWidth: 1, borderStyle: 'solid', } satisfies FreeTextDraft); const before = await page.annotations.list(); const result = await page.annotations.update(created.annotation.ref, { subtype: 'free-text', textAlign: 'right', fontFamily: 'helvetica', fontSize: 18, color: '#0050a0', interiorColor: '#f0f0f0', } ); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.annotation.subtype).toBe('free-text'); if (result.annotation.subtype === 'free-text'){ expect(result.annotation.textAlign).toBe('right'); expect(result.annotation.fontSize).toBe(18); expect(result.annotation.color).toBe('#0050a0'); expect(result.annotation.interiorColor).toBe('#f0f0f0'); } } finally{ await doc.close(); } } ); test('rich text: a plain draft reads back body-style paragraphs and a body from its font', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'free-text', intent: 'free-text', contents: 'Plain\rtext', box: shapeRect, fontFamily: 'helvetica-bold', fontSize: 18, textAlign: 'center', color: '#000000', } satisfies FreeTextDraft); expect(created.annotation.subtype).toBe('free-text'); if (created.annotation.subtype === 'free-text'){ const rich = created.annotation.richText; expect(created.annotation.fontFamily).toBe('helvetica-bold'); expect(rich.body.family).toBe('Helvetica'); expect(rich.body.weight).toBe(700); expect(rich.body.italic).toBe(false); expect(rich.body.size).toBe(18); expect(rich.body.align).toBe('center'); expect(rich.paragraphs).toEqual([{ runs: [{ text: 'Plain'} ]} , { runs: [{ text: 'text'} ]} , ]); } } finally{ await doc.close(); } } ); test('rich text: a draft with runs round-trips the body, the runs and the plain projection', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'free-text', intent: 'free-text', box: shapeRect, color: '#0000ff', richText:{ body:{ family: 'Helvetica', size: 18, color: '#102030'} , paragraphs: [{ runs: [{ text: 'Hello '} , { text: 'bold', style:{ weight: 700} } , { text: ' red', style:{ color: '#FF0000'} } , ], } , { align: 'center', runs: [{ text: 'H'} , { text: '2', style:{ script: 'sub'} } ]} , ], } , } satisfies FreeTextDraft); expect(AnnotationCreateResultSchema.safeParse(created).success).toBe(true); expect(created.annotation.subtype).toBe('free-text'); if (created.annotation.subtype === 'free-text'){ const dto = created.annotation; expect(dto.contents).toBe('Hello bold red\nH2'); expect(dto.fontFamily).toBe('helvetica'); expect(dto.fontSize).toBe(18); expect(dto.color).toBe('#0000ff'); expect(dto.fontColor).toBe('#102030'); expect(dto.richText.body.color).toBe('#102030'); expect(dto.richText.paragraphs[0]!.runs).toEqual([{ text: 'Hello '} , { text: 'bold', style:{ weight: 700} } , { text: ' red', style:{ color: '#ff0000'} } , ]); expect(dto.richText.paragraphs[1]!.align).toBe('center'); expect(dto.richText.paragraphs[1]!.runs[1]).toEqual({ text: '2', style:{ script: 'sub'} , } ); } const listed = (await page.annotations.list()).annotations.find( (a) => annotationKey(a.ref) === annotationKey(created.annotation.ref), ); expect(listed?.subtype).toBe('free-text'); if (listed?.subtype === 'free-text'){ expect(listed.richText.paragraphs[0]!.runs[1]).toEqual({ text: 'bold', style:{ weight: 700} , } ); } } finally{ await doc.close(); } } ); test('rich text: paragraphs-only patch keeps the body; contents-only rewrites body-style paragraphs', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'free-text', intent: 'free-text', box: shapeRect, fontFamily: 'helvetica', fontSize: 14, textAlign: 'center', color: '#000000', richText:{ body:{ family: 'Helvetica', size: 14} , paragraphs: [{ runs: [{ text: 'a'} , { text: 'b', style:{ weight: 700} } ]} ], } , } satisfies FreeTextDraft); const ref = created.annotation.ref; const restyled = await page.annotations.update(ref, { subtype: 'free-text', richText:{ paragraphs: [{ runs: [{ text: 'ab', style:{ italic: true} } , { text: 'c'} ]} ], } , } ); expect(AnnotationUpdateResultSchema.safeParse(restyled).success).toBe(true); expect(restyled.annotation.subtype).toBe('free-text'); if (restyled.annotation.subtype === 'free-text'){ expect(restyled.annotation.contents).toBe('abc'); expect(restyled.annotation.richText.body.size).toBe(14); expect(restyled.annotation.richText.body.align).toBe('center'); expect(restyled.annotation.textAlign).toBe('center'); expect(restyled.annotation.richText.paragraphs[0]!.runs[0]).toEqual({ text: 'ab', style:{ italic: true} , } ); } const rewritten = await page.annotations.update(ref, { subtype: 'free-text', contents: 'one\ntwo', } ); expect(rewritten.annotation.subtype).toBe('free-text'); if (rewritten.annotation.subtype === 'free-text'){ expect(rewritten.annotation.contents).toBe('one\ntwo'); expect(rewritten.annotation.richText.paragraphs).toEqual([{ runs: [{ text: 'one'} ]} , { runs: [{ text: 'two'} ]} , ]); expect(rewritten.annotation.richText.body.size).toBe(14); } } finally{ await doc.close(); } } ); test('rich text: fontSize / fontColor / fontFamily move the body while runs keep their deltas', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'free-text', intent: 'free-text', box: shapeRect, fontFamily: 'helvetica', fontSize: 14, textAlign: 'left', color: '#000000', richText:{ body:{ family: 'Helvetica', size: 14} , paragraphs: [{ runs: [{ text: 'a'} , { text: 'b', style:{ size: 30} } ]} ], } , } satisfies FreeTextDraft); const updated = await page.annotations.update(created.annotation.ref, { subtype: 'free-text', fontSize: 20, fontColor: '#ff0000', fontFamily: 'times-bold', } ); expect(updated.annotation.subtype).toBe('free-text'); if (updated.annotation.subtype === 'free-text'){ const dto = updated.annotation; expect(dto.fontSize).toBe(20); expect(dto.fontFamily).toBe('times-bold'); expect(dto.richText.body.size).toBe(20); expect(dto.richText.body.color).toBe('#ff0000'); expect(dto.richText.body.family).toBe('Times'); expect(dto.richText.body.weight).toBe(700); expect(dto.richText.paragraphs[0]!.runs[1]).toEqual({ text: 'b', style:{ size: 30} } ); } } finally{ await doc.close(); } } ); test('rich text: contents and richText that disagree reject with InvalidArg; agreeing writes the runs', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'free-text', intent: 'free-text', contents: 'x', box: shapeRect, fontFamily: 'helvetica', fontSize: 14, textAlign: 'left', color: '#000000', } satisfies FreeTextDraft); const ref = created.annotation.ref; let caught: unknown; try{ await page.annotations.update(ref, { subtype: 'free-text', contents: 'stale', richText:{ paragraphs: [{ runs: [{ text: 'fresh'} ]} ]} , } ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); const after = (await page.annotations.list()).annotations.find( (a) => annotationKey(a.ref) === annotationKey(created.annotation.ref), ); expect(after?.contents).toBe('x'); const agreed = await page.annotations.update(ref, { subtype: 'free-text', contents: 'fresh', richText:{ paragraphs: [{ runs: [{ text: 'fr'} , { text: 'esh', style:{ weight: 700} } ]} ], } , } ); expect(agreed.annotation.subtype).toBe('free-text'); if (agreed.annotation.subtype === 'free-text'){ expect(agreed.annotation.contents).toBe('fresh'); expect(agreed.annotation.richText.paragraphs[0]!.runs[1]).toEqual({ text: 'esh', style:{ weight: 700} , } ); } } finally{ await doc.close(); } } ); test("a comment as rich text: a note's reads back with its plain projection; a plain one reads null", async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const rich = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), richText:{ paragraphs: [{ runs: [{ text: 'Hello '} , { text: 'bold', style:{ weight: 700} } ]} , { runs: [{ text: 'two', style:{ decoration: ['underline']} } ]} , ], } , } satisfies TextDraft); const note = rich.annotation; if (note.subtype !== 'text') throw new Error('expected a note'); expect(note.contents).toBe('Hello bold\ntwo'); expect(note.richText?.paragraphs).toEqual([{ runs: [{ text: 'Hello '} , { text: 'bold', style:{ weight: 700} } ]} , { runs: [{ text: 'two', style:{ decoration: ['underline']} } ]} , ]); expect(note.richText?.body.family).toBe('Helvetica'); expect(note.richText?.body.size).toBe(12); const plain = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x + 40, shapeRect.y), contents: 'plain', } satisfies TextDraft); if (plain.annotation.subtype !== 'text') throw new Error('expected a note'); expect(plain.annotation.richText).toBeNull(); } finally{ await doc.close(); } } ); test('a comment as rich text: new contents rewrite a rich comment, and null makes it plain', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'square', box: shapeRect, richText:{ body:{ color: '#102030'} , paragraphs: [{ runs: [{ text: 'was '} , { text: 'bold', style:{ weight: 700} } ]} ], } , } satisfies SquareDraft); const ref = created.annotation.ref; const rewritten = await page.annotations.update(ref, { subtype: 'square', contents: 'now\nplain', } ); if (rewritten.annotation.subtype !== 'square') throw new Error('expected a square'); expect(rewritten.annotation.contents).toBe('now\nplain'); expect(rewritten.annotation.richText?.paragraphs).toEqual([{ runs: [{ text: 'now'} ]} , { runs: [{ text: 'plain'} ]} , ]); expect(rewritten.annotation.richText?.body.color).toBe('#102030'); const unstyled = await page.annotations.update(ref, { subtype: 'square', richText: null} ); if (unstyled.annotation.subtype !== 'square') throw new Error('expected a square'); expect(unstyled.annotation.richText).toBeNull(); expect(unstyled.annotation.contents).toBe('now\nplain'); } finally{ await doc.close(); } } ); test("a comment as rich text: a redact's comment in another font leaves its overlay's", async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'redact', rect: shapeRect, overlayText: 'CONFIDENTIAL', fontFamily: 'courier', fontSize: 10, fontColor: '#ff0000', richText:{ body:{ family: 'Times', size: 14} , paragraphs: [{ runs: [{ text: 'why'} ]} ], } , } satisfies RedactDraft); const redact = created.annotation; if (redact.subtype !== 'redact') throw new Error('expected a redact'); expect(redact.richText?.body.family).toBe('Times'); expect(redact.richText?.body.size).toBe(14); expect(redact.fontFamily).toBe('courier'); expect(redact.fontSize).toBe(10); expect(redact.fontColor).toBe('#ff0000'); } finally{ await doc.close(); } } ); test('create redact (area + text) round-trips label + colour fields', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const areaDraft: RedactDraft ={ subtype: 'redact', contents: 'mutation conformance: area redact', rect: shapeRect, color: '#e44234', opacity: 1, interiorColor: '#000000', overlayText: 'CONFIDENTIAL', repeat: true, fontFamily: 'helvetica', fontSize: 10, fontColor: '#ffffff', textAlign: 'center', } ; const area = await page.annotations.create(areaDraft); expect(AnnotationCreateResultSchema.safeParse(area).success).toBe(true); expect(area.annotation.subtype).toBe('redact'); if (area.annotation.subtype === 'redact'){ expect(area.annotation.quadPoints.length).toBe(0); expect(area.annotation.color).toBe('#e44234'); expect(area.annotation.interiorColor).toBe('#000000'); expect(area.annotation.overlayText).toBe('CONFIDENTIAL'); expect(area.annotation.repeat).toBe(true); expect(area.annotation.fontFamily).toBe('helvetica'); expect(area.annotation.fontSize).toBe(10); expect(area.annotation.fontColor).toBe('#ffffff'); expect(area.annotation.textAlign).toBe('center'); } const textDraft: RedactDraft ={ subtype: 'redact', contents: 'mutation conformance: text redact', rect: shapeRect, quadPoints: quad, } ; const text = await page.annotations.create(textDraft); expect(AnnotationCreateResultSchema.safeParse(text).success).toBe(true); expect(text.annotation.subtype).toBe('redact'); if (text.annotation.subtype === 'redact'){ expect(text.annotation.quadPoints.length).toBe(quad.length); expect(text.annotation.interiorColor).toBe(null); expect(text.annotation.overlayText).toBe(null); expect(text.annotation.repeat).toBe(false); expect(text.annotation.color).toBe('#ff0000'); } } finally{ await doc.close(); } } ); test('update a redact patches the label and clears it, non-structurally', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'redact', contents: 'redact-update-base', rect: shapeRect, interiorColor: '#000000', overlayText: 'DRAFT', fontFamily: 'helvetica', fontSize: 8, fontColor: '#ffffff', } satisfies RedactDraft); const before = await page.annotations.list(); const restyled = await page.annotations.update(created.annotation.ref, { subtype: 'redact', overlayText: 'REDACTED', repeat: true, fontFamily: 'helvetica', fontSize: 0, fontColor: '#fff0f0', textAlign: 'right', interiorColor: '#0a0a0a', } ); expect(AnnotationUpdateResultSchema.safeParse(restyled).success).toBe(true); expect(restyled.annotation.subtype).toBe('redact'); if (restyled.annotation.subtype === 'redact'){ expect(restyled.annotation.overlayText).toBe('REDACTED'); expect(restyled.annotation.repeat).toBe(true); expect(restyled.annotation.fontSize).toBe(0); expect(restyled.annotation.fontColor).toBe('#fff0f0'); expect(restyled.annotation.textAlign).toBe('right'); expect(restyled.annotation.interiorColor).toBe('#0a0a0a'); } const cleared = await page.annotations.update(created.annotation.ref, { subtype: 'redact', overlayText: null, repeat: false, interiorColor: null, } ); expect(cleared.annotation.subtype).toBe('redact'); if (cleared.annotation.subtype === 'redact'){ expect(cleared.annotation.overlayText).toBe(null); expect(cleared.annotation.repeat).toBe(false); expect(cleared.annotation.interiorColor).toBe(null); } } finally{ await doc.close(); } } ); test('create + update a caret round-trips color/opacity and its box', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const caretDraft: CaretDraft ={ subtype: 'caret', intent: 'replace', contents: 'mutation conformance: caret', box: shapeRect, color: '#0080ff', opacity: 0.7, } ; const caret = await page.annotations.create(caretDraft); expect(AnnotationCreateResultSchema.safeParse(caret).success).toBe(true); expect(caret.annotation.subtype).toBe('caret'); expect(caret.annotation.ref.kind).toBe('objectNumber'); if (caret.annotation.subtype === 'caret'){ expect(caret.annotation.intent).toBe('replace'); expect(caret.annotation.color).toBe('#0080ff'); expect(Math.round(caret.annotation.opacity * 100) / 100).toBe(0.7); expect('strokeWidth' in caret.annotation).toBe(false); expect('quadPoints' in caret.annotation).toBe(false); expect(caret.annotation.box).toEqual(shapeRect); const{ rect} = caret.annotation; expect(rect.x <= shapeRect.x && rect.y <= shapeRect.y).toBe(true); expect(rect.x + rect.width >= shapeRect.x + shapeRect.width).toBe(true); expect(rect.y + rect.height >= shapeRect.y + shapeRect.height).toBe(true); } const before = await page.annotations.list(); const result = await page.annotations.update(caret.annotation.ref, { subtype: 'caret', color: '#ff0000', } ); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.annotation.subtype).toBe('caret'); if (result.annotation.subtype === 'caret'){ expect(result.annotation.color).toBe('#ff0000'); expect(result.annotation.box).toEqual(shapeRect); } const after = await page.annotations.list(); expect(after.annotations.some((a) => a.subtype === 'caret')).toBe(true); } finally{ await doc.close(); } } ); test('update an ink annotation patches strokes + color and is non-structural', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'ink', contents: 'ink-update-base', inkList: inkStrokes, color: '#000000', strokeWidth: 2, borderStyle: 'solid', opacity: 1, } satisfies InkDraft); const before = await page.annotations.list(); const newStrokes: InkDraft['inkList'] = [ ...inkStrokes, [{ x: 80, y: 90} , { x: 120, y: 110} , ], ]; const result = await page.annotations.update(created.annotation.ref, { subtype: 'ink', inkList: newStrokes, color: '#dc143c', } ); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.annotation.subtype).toBe('ink'); if (result.annotation.subtype === 'ink'){ expect(result.annotation.inkList.length).toBe(newStrokes.length); expect(result.annotation.color).toBe('#dc143c'); } } finally{ await doc.close(); } } ); test('ink highlight intent + blend round-trip and unrelated patches preserve blend', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'ink', intent: 'ink-highlight', blendMode: 'multiply', inkList: inkStrokes, color: '#ffcd45', strokeWidth: 14, borderStyle: 'solid', opacity: 1, } satisfies InkDraft); expect(created.annotation.subtype).toBe('ink'); if (created.annotation.subtype !== 'ink') return; expect(created.annotation.intent).toBe('ink-highlight'); expect(created.annotation.blendMode).toBe('multiply'); const recolored = await page.annotations.update(created.annotation.ref, { subtype: 'ink', color: '#fabe28', } ); expect(recolored.annotation.subtype).toBe('ink'); expect(recolored.annotation.blendMode).toBe('multiply'); const screened = await page.annotations.update(created.annotation.ref, { subtype: 'ink', blendMode: 'screen', } ); expect(screened.annotation.subtype).toBe('ink'); expect(screened.annotation.blendMode).toBe('screen'); } finally{ await doc.close(); } } ); test('update a polyline patches vertices + line endings and is non-structural', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'polyline', contents: 'polyline-update-base', vertices, interiorColor: null, color: '#000000', strokeWidth: 1, borderStyle: 'solid', opacity: 1, lineEndings:{ start: 'none', end: 'none'} , } satisfies PolylineDraft); const before = await page.annotations.list(); const newVertices: PagePoint[] = [ ...vertices, { x: vertices[0]!.x + 5, y: vertices[0]!.y + 5} , ]; const result = await page.annotations.update(created.annotation.ref, { subtype: 'polyline', vertices: newVertices, lineEndings:{ start: 'circle', end: 'diamond'} , } ); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.annotation.subtype).toBe('polyline'); if (result.annotation.subtype === 'polyline'){ expect(result.annotation.vertices.length).toBe(newVertices.length); expect(result.annotation.lineEndings.start).toBe('circle'); expect(result.annotation.lineEndings.end).toBe('diamond'); } } finally{ await doc.close(); } } ); test('update a shape annotation patches color and is non-structural', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'circle', contents: 'shape-update-base', box: shapeRect, interiorColor: '#0a141e', color: '#000000', strokeWidth: 1, borderStyle: 'solid', opacity: 1, } satisfies CircleDraft); const before = await page.annotations.list(); const result = await page.annotations.update(created.annotation.ref, { subtype: 'circle', interiorColor: '#c86432', strokeWidth: 4, } ); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.annotation.subtype).toBe('circle'); if (result.annotation.subtype === 'circle'){ expect(result.annotation.interiorColor).toBe('#c86432'); expect(result.annotation.strokeWidth).toBe(4); expect(result.annotation.borderStyle).toBe('solid'); } } finally{ await doc.close(); } } ); test('creating a shape bakes an /AP appearance the reader can rasterize', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'circle', contents: 'appearance-gen', box: shapeRect, interiorColor: '#ff0000', color: '#000000', strokeWidth: 2, borderStyle: 'solid', opacity: 1, } satisfies CircleDraft); const raster = await appearanceRaster(page, created.annotation.ref); expect(raster.width > 0).toBeTruthy(); expect(raster.height > 0).toBeTruthy(); } finally{ await doc.close(); } } ); test("update keeps the annotation's name and never touches /NM", async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const before = await page.annotations.list(); const target = before.annotations.find((a) => a.ref.kind === 'objectNumber'); if (!target) return; const newContents = `mutation conformance: updated@${ Date.now()} `; const patch = subtypeAwarePatch(target.subtype, newContents); if (!patch) return; const result = await page.annotations.update(target.ref, patch); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.meta.affectedPages).toEqual([toPageRef(fix.pageObjectNumber)]); expect('cacheDelta' in result.meta).toBe(true); expect(annotationKey(result.annotation.ref)).toBe(annotationKey(target.ref)); expect(result.annotation.nm).toBe(target.nm); expect(result.annotation.contents).toBe(newContents); } finally{ await doc.close(); } } ); if (fix.expectsInlineAnnotation){ test('update of an annotation born inline keeps its baseIndex name and writes no /NM', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const before = await page.annotations.list(); const inline = before.annotations.find((a) => a.ref.kind === 'baseIndex'); expect(inline !== undefined).toBe(true); if (!inline) return; const newContents = `inline-update@${ Date.now()} `; const patch = subtypeAwarePatch(inline.subtype, newContents); if (!patch) return; const result = await page.annotations.update(inline.ref, patch); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(annotationKey(result.annotation.ref)).toBe(annotationKey(inline.ref)); expect(result.annotation.nm).toBe(inline.nm); expect(result.meta.changedRefs).toEqual([inline.ref]); const after = await page.annotations.list(); const read = after.annotations.find( (a) => annotationKey(a.ref) === annotationKey(inline.ref), ); expect(read?.contents).toBe(newContents); } finally{ await doc.close(); } } ); } if (fix.expectsInlineAnnotation){ test('reorder of an annotation born inline keeps its baseIndex name', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const before = await page.annotations.list(); const inline = before.annotations.find((a) => a.ref.kind === 'baseIndex'); expect(inline !== undefined).toBe(true); if (!inline) return; const atBottom = annotationKey(before.annotations[0]!.ref) === annotationKey(inline.ref); const result = await page.annotations.reorder([inline.ref], atBottom ? 'end' : 'start'); const at = atBottom ? result.order.length - 1 : 0; expect(annotationKey(result.order[at]!)).toBe(annotationKey(inline.ref)); expect(result.meta.changedRefs).toEqual([inline.ref]); const after = (await page.annotations.list()).annotations[at]!; expect(annotationKey(after.ref)).toBe(annotationKey(inline.ref)); expect(after.nm).toBe(inline.nm); } finally{ await doc.close(); } } ); } test('delete by objectNumber removes the annotation and reports a stable id', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft: HighlightDraft ={ subtype: 'highlight', contents: 'mutation conformance: to-delete', quadPoints: quad, } ; const created = await page.annotations.create(draft); const before = await page.annotations.list(); const deletions: AnnotationRef[][] = []; const stop = doc.events.subscribe((event) =>{ if (event.type === 'annotations.deleted') deletions.push(event.deleted); } ); const result = await page.annotations.delete(created.annotation.ref); stop(); expect(Object.keys(result)).toEqual(['meta']); expect(deletions).toEqual([[created.annotation.ref]]); expect(result.meta.affectedPages).toEqual([toPageRef(fix.pageObjectNumber)]); expect('cacheDelta' in result.meta).toBe(true); expect(result.meta.changedRefs).toEqual([created.annotation.ref]); const after = await page.annotations.list(); expect(after.annotations.length).toBe(before.annotations.length - 1); } finally{ await doc.close(); } } ); if (fix.expectsInlineAnnotation){ test('delete of an annotation born inline reports its baseIndex name; the others keep theirs', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const before = await page.annotations.list(); const inline = before.annotations.find((a) => a.ref.kind === 'baseIndex'); expect(inline !== undefined).toBe(true); if (!inline) return; const result = await page.annotations.delete(inline.ref); expect(result.meta.changedRefs[0]).toEqual(inline.ref); expect(result.meta.affectedPages).toEqual([toPageRef(fix.pageObjectNumber)]); const gone = new Set(result.meta.changedRefs.map(annotationKey)); const after = await page.annotations.list(); expect(after.annotations.map((a) => annotationKey(a.ref))).toEqual( before.annotations.map((a) => annotationKey(a.ref)).filter((key) => !gone.has(key)), ); const patch = subtypeAwarePatch(inline.subtype, 'gone'); if (!patch) return; const again = await page.annotations.update(inline.ref, patch).then( () => null, (error: unknown) => error, ); expect(EngineError.is(again, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); } test('abort on create rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft: HighlightDraft ={ subtype: 'highlight', contents: 'will be aborted', quadPoints: quad, } ; const p = page.annotations.create(draft); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); test('reorder puts annotations right after or before their neighbour', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const seeded: AnnotationRef[] = []; for (const label of ['order-a', 'order-b', 'order-c']){ const created = await page.annotations.create({ subtype: 'highlight', contents: label, quadPoints: quad, } ); seeded.push(created.annotation.ref); } const [a, b, c] = seeded as [AnnotationRef, AnnotationRef, AnnotationRef]; const listed = async () => (await page.annotations.list()).annotations.map((x) => annotationKey(x.ref)); const before = await listed(); const others = before.filter((key) => !seeded.map(annotationKey).includes(key)); const result = await page.annotations.reorder([a], { after: c} ); expect(AnnotationReorderResultSchema.safeParse(result).success).toBe(true); expect(result.meta.affectedPages).toEqual([toPageRef(fix.pageObjectNumber)]); expect('cacheDelta' in result.meta).toBe(true); expect(result.meta.changedRefs.map(annotationKey)).toEqual([annotationKey(a)]); const afterC = [...others, annotationKey(b), annotationKey(c), annotationKey(a)]; expect(result.order.map(annotationKey)).toEqual(afterC); expect(await listed()).toEqual(afterC); const backBeforeB = await page.annotations.reorder([a], { before: b} ); expect(backBeforeB.order.map(annotationKey)).toEqual(before); expect(await listed()).toEqual(before); } finally{ await doc.close(); } } ); test('reorder keeps the order given and goes to the bottom or the top', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const ids = await Promise.all( ['multi-1', 'multi-2', 'multi-3'].map((label) => page.annotations.create({ subtype: 'highlight', contents: label, quadPoints: quad, } ), ), ); const given = [ids[2].annotation.ref, ids[0].annotation.ref, ids[1].annotation.ref]; const bottom = await page.annotations.reorder(given, 'start'); expect(bottom.meta.changedRefs.map(annotationKey)).toEqual(given.map(annotationKey)); expect(bottom.order.slice(0, 3).map(annotationKey)).toEqual(given.map(annotationKey)); const top = await page.annotations.reorder([ids[2].annotation.ref], 'end'); expect(annotationKey(top.order.at(-1)!)).toBe(annotationKey(ids[2].annotation.ref)); expect(top.order).toHaveLength(bottom.order.length); } finally{ await doc.close(); } } ); test('reorder refuses a neighbour that moves (InvalidArg) or is not on the page (NotFound)', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const a = await page.annotations.create({ subtype: 'highlight', contents: 'anchor-a', quadPoints: quad, } ); const before = (await page.annotations.list()).annotations.map((x) => annotationKey(x.ref)); const refused = async (attempt: () => Promise) =>{ try{ await attempt(); } catch (err){ return err; } return undefined; } ; const self = await refused(() => page.annotations.reorder([a.annotation.ref], { after: a.annotation.ref} ), ); expect(EngineError.is(self, EngineErrorCode.InvalidArg)).toBe(true); const gone: AnnotationRef ={ kind: 'objectNumber', page: toPageRef(fix.pageObjectNumber), objectNumber: 999_999, } ; const missing = await refused(() => page.annotations.reorder([a.annotation.ref], { before: gone} ), ); expect(EngineError.is(missing, EngineErrorCode.NotFound)).toBe(true); const missingRow = await refused(() => page.annotations.reorder([gone], 'start')); expect(EngineError.is(missingRow, EngineErrorCode.NotFound)).toBe(true); expect( (await page.annotations.list()).annotations.map((x) => annotationKey(x.ref)), ).toEqual(before); } finally{ await doc.close(); } } ); test('reorder with duplicate refs rejects with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const a = await page.annotations.create({ subtype: 'highlight', contents: 'dup-a', quadPoints: quad, } ); let caught: unknown; try{ await page.annotations.reorder([a.annotation.ref, a.annotation.ref], 'start'); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('abort on reorder rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const a = await page.annotations.create({ subtype: 'highlight', contents: 'abort-a', quadPoints: quad, } ); const p = page.annotations.reorder([a.annotation.ref], 'start'); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); test('create a reply links /IRT and defaults /RT to "reply"', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const parent = await page.annotations.create({ subtype: 'highlight', contents: 'reply parent', quadPoints: quad, } satisfies HighlightDraft); expect(parent.annotation.reply).toBe(null); const reply = await page.annotations.create({ subtype: 'highlight', contents: 'a reply', quadPoints: quad, reply:{ to: parent.annotation.ref} , } satisfies HighlightDraft); expect(AnnotationCreateResultSchema.safeParse(reply).success).toBe(true); expect(reply.annotation.reply?.type).toBe('reply'); expect(reply.annotation.reply?.to !== undefined).toBe(true); if ( reply.annotation.reply?.to.kind === 'objectNumber' && parent.annotation.ref.kind === 'objectNumber' ){ expect(reply.annotation.reply!.to.objectNumber).toBe(parent.annotation.ref.objectNumber); expect(reply.annotation.reply!.to.page.objectNumber).toBe(fix.pageObjectNumber); } expect(reply.meta.changedRefs).toEqual([reply.annotation.ref]); const after = await page.annotations.list(); const readReply = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && reply.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === reply.annotation.ref.objectNumber, ); expect(readReply?.reply?.type).toBe('reply'); expect(readReply?.reply?.to !== undefined).toBe(true); } finally{ await doc.close(); } } ); test('create a grouped subordinate writes /RT /Group', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const primary = await page.annotations.create({ subtype: 'highlight', contents: 'group primary', quadPoints: quad, } satisfies HighlightDraft); const caret = await page.annotations.create({ subtype: 'caret', contents: '', box: shapeRect, color: '#000000', opacity: 1, reply:{ to: primary.annotation.ref, type: 'group'} , } satisfies CaretDraft); expect(AnnotationCreateResultSchema.safeParse(caret).success).toBe(true); expect(caret.annotation.reply?.type).toBe('group'); expect(caret.annotation.reply?.to !== undefined).toBe(true); const after = await page.annotations.list(); const readCaret = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && caret.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === caret.annotation.ref.objectNumber, ); expect(readCaret?.reply?.type).toBe('group'); } finally{ await doc.close(); } } ); test('create link annotations round-trip uri, goto/xyz, goto/fitH, and dead targets', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const uri = await page.annotations.create({ subtype: 'link', rect: shapeRect, target:{ kind: 'uri', uri: 'https://www.embedpdf.com/'} , } satisfies LinkDraft); expect(AnnotationCreateResultSchema.safeParse(uri).success).toBe(true); expect(uri.annotation.subtype).toBe('link'); if (uri.annotation.subtype === 'link'){ expect(uri.annotation.target).toEqual({ kind: 'uri', uri: 'https://www.embedpdf.com/'} ); } const xyz = await page.annotations.create({ subtype: 'link', rect: shapeRect, target:{ kind: 'goto', destination:{ kind: 'xyz', page: toPageRef(fix.pageObjectNumber), x: 30, y: 300, zoom: null, } , } , } satisfies LinkDraft); expect(xyz.annotation.subtype).toBe('link'); if (xyz.annotation.subtype === 'link'){ expect(xyz.annotation.target?.kind).toBe('goto'); if (xyz.annotation.target?.kind === 'goto'){ const dest = xyz.annotation.target.destination; expect(dest.kind).toBe('xyz'); if (dest.kind === 'xyz'){ expect(dest.page.objectNumber).toBe(fix.pageObjectNumber); expect(dest.x).toBe(30); expect(dest.y).toBe(300); expect(dest.zoom).toBe(null); } } } const fitH = await page.annotations.create({ subtype: 'link', rect: shapeRect, target:{ kind: 'goto', destination:{ kind: 'fitH', page: toPageRef(fix.pageObjectNumber), y: 420} , } , } satisfies LinkDraft); expect(fitH.annotation.subtype).toBe('link'); if (fitH.annotation.subtype === 'link' && fitH.annotation.target?.kind === 'goto'){ expect(fitH.annotation.target.destination).toEqual({ kind: 'fitH', page: toPageRef(fix.pageObjectNumber), y: 420, } ); } const dead = await page.annotations.create({ subtype: 'link', rect: shapeRect, target: null, } satisfies LinkDraft); expect(dead.annotation.subtype).toBe('link'); if (dead.annotation.subtype === 'link') expect(dead.annotation.target).toBe(null); const after = await page.annotations.list(); const links = after.annotations.filter((a) => a.subtype === 'link'); expect(links.length >= 4).toBe(true); } finally{ await doc.close(); } } ); test('a link patch retargets in both directions (uri→goto, goto→uri) and moves the rect', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'link', rect: shapeRect, target:{ kind: 'uri', uri: 'https://old.example/'} , } satisfies LinkDraft); const toGoto = await page.annotations.update(created.annotation.ref, { subtype: 'link', target:{ kind: 'goto', destination:{ kind: 'fit', page: toPageRef(fix.pageObjectNumber)} , } , } ); expect(AnnotationUpdateResultSchema.safeParse(toGoto).success).toBe(true); if (toGoto.annotation.subtype === 'link'){ expect(toGoto.annotation.target).toEqual({ kind: 'goto', destination:{ kind: 'fit', page: toPageRef(fix.pageObjectNumber)} , } ); } const movedRect ={ ...shapeRect, x: shapeRect.x + 5, y: shapeRect.y + 5} ; const toUri = await page.annotations.update(created.annotation.ref, { subtype: 'link', rect: movedRect, target:{ kind: 'uri', uri: 'https://new.example/'} , } ); if (toUri.annotation.subtype === 'link'){ expect(toUri.annotation.target).toEqual({ kind: 'uri', uri: 'https://new.example/'} ); expect(Math.round(toUri.annotation.rect.x)).toBe(Math.round(movedRect.x)); } } finally{ await doc.close(); } } ); test('a link patch clears the target with null — a dead link on re-read', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const created = await page.annotations.create({ subtype: 'link', rect: shapeRect, target:{ kind: 'goto', destination:{ kind: 'fit', page: toPageRef(fix.pageObjectNumber)} , } , } satisfies LinkDraft); const cleared = await page.annotations.update(created.annotation.ref, { subtype: 'link', target: null, } ); expect(AnnotationUpdateResultSchema.safeParse(cleared).success).toBe(true); if (cleared.annotation.subtype === 'link') expect(cleared.annotation.target).toBe(null); const after = await page.annotations.list(); const readBack = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && created.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === created.annotation.ref.objectNumber, ); expect(readBack?.subtype).toBe('link'); if (readBack?.subtype === 'link') expect(readBack.target).toBe(null); const revived = await page.annotations.update(created.annotation.ref, { subtype: 'link', target:{ kind: 'uri', uri: 'https://revived.example/'} , } ); if (revived.annotation.subtype === 'link'){ expect(revived.annotation.target).toEqual({ kind: 'uri', uri: 'https://revived.example/', } ); } } finally{ await doc.close(); } } ); test('a link grouped to a highlight round-trips /IRT + /RT /Group with its target', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const parent = await page.annotations.create({ subtype: 'highlight', contents: 'linked text', quadPoints: quad, } satisfies HighlightDraft); const link = await page.annotations.create({ subtype: 'link', rect: shapeRect, target:{ kind: 'uri', uri: 'https://www.embedpdf.com/docs'} , reply:{ to: parent.annotation.ref, type: 'group'} , } satisfies LinkDraft); expect(AnnotationCreateResultSchema.safeParse(link).success).toBe(true); expect(link.annotation.reply?.type).toBe('group'); expect(link.annotation.reply?.to !== undefined).toBe(true); if ( link.annotation.reply?.to.kind === 'objectNumber' && parent.annotation.ref.kind === 'objectNumber' ){ expect(link.annotation.reply!.to.objectNumber).toBe(parent.annotation.ref.objectNumber); } const after = await page.annotations.list(); const readLink = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && link.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === link.annotation.ref.objectNumber, ); expect(readLink?.subtype).toBe('link'); expect(readLink?.reply?.type).toBe('group'); if (readLink?.subtype === 'link'){ expect(readLink.target).toEqual({ kind: 'uri', uri: 'https://www.embedpdf.com/docs'} ); } } finally{ await doc.close(); } } ); test('replace-text round-trips /IT and groups StrikeOut under its Caret', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const caret = await page.annotations.create({ subtype: 'caret', intent: 'replace', contents: 'replacement text', box: shapeRect, color: '#e44234', opacity: 1, } satisfies CaretDraft); const strikeout = await page.annotations.create({ subtype: 'strikeout', intent: 'strikeout-text-edit', quadPoints: quad, color: '#e44234', opacity: 1, reply:{ to: caret.annotation.ref, type: 'group'} , } satisfies StrikeoutDraft); expect(caret.annotation.subtype).toBe('caret'); if (caret.annotation.subtype === 'caret') expect(caret.annotation.intent).toBe('replace'); expect(strikeout.annotation.subtype).toBe('strikeout'); if (strikeout.annotation.subtype === 'strikeout'){ expect(strikeout.annotation.intent).toBe('strikeout-text-edit'); } expect(strikeout.annotation.reply?.type).toBe('group'); expect(strikeout.annotation.reply?.to).toEqual(caret.annotation.ref); const after = await page.annotations.list(); const readCaret = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && caret.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === caret.annotation.ref.objectNumber, ); const readStrikeout = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && strikeout.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === strikeout.annotation.ref.objectNumber, ); expect(readCaret?.subtype === 'caret' && readCaret.intent).toBe('replace'); expect(readStrikeout?.subtype === 'strikeout' && readStrikeout.intent).toBe( 'strikeout-text-edit', ); expect(readStrikeout?.reply?.type).toBe('group'); expect(readStrikeout?.reply?.to).toEqual(caret.annotation.ref); } finally{ await doc.close(); } } ); test('patch reply: null clears /IRT and /RT (back to top-level)', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const parent = await page.annotations.create({ subtype: 'highlight', contents: 'clear parent', quadPoints: quad, } satisfies HighlightDraft); const reply = await page.annotations.create({ subtype: 'highlight', contents: 'clearable reply', quadPoints: quad, reply:{ to: parent.annotation.ref} , } satisfies HighlightDraft); expect(reply.annotation.reply?.type).toBe('reply'); const cleared = await page.annotations.update(reply.annotation.ref, { subtype: 'highlight', reply: null, } ); expect(AnnotationUpdateResultSchema.safeParse(cleared).success).toBe(true); expect(cleared.annotation.reply).toBe(null); } finally{ await doc.close(); } } ); test('create with a cross-page /IRT parent throws InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const parent = await page.annotations.create({ subtype: 'highlight', contents: 'cross-page parent', quadPoints: quad, } satisfies HighlightDraft); if (parent.annotation.ref.kind !== 'objectNumber') return; const crossPageRef: AnnotationRef ={ kind: 'objectNumber', page: toPageRef(fix.pageObjectNumber + 2), objectNumber: parent.annotation.ref.objectNumber, } ; let caught: unknown; try{ await page.annotations.create({ subtype: 'highlight', contents: 'bad cross-page reply', quadPoints: quad, reply:{ to: crossPageRef} , } satisfies HighlightDraft); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('create refuses an nm already used on the page, naming the field', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const draft ={ subtype: 'highlight', quadPoints: quad, nm: 'taken'} as const; await page.annotations.create(draft satisfies HighlightDraft); await expect(page.annotations.create(draft)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'nm'} , } ); const{ pages} = await doc.pages.list(); const other = pages.find((entry) => entry.ref.objectNumber !== fix.pageObjectNumber); if (!other) return; const elsewhere = await doc.page(other.ref).annotations.create(draft); expect(elsewhere.annotation.nm).toBe('taken'); } finally{ await doc.close(); } } ); test('a review-status reply round-trips /State + /StateModel + /Subj', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const target = await page.annotations.create({ subtype: 'highlight', contents: 'status target', subject: 'Pricing question', quadPoints: quad, } satisfies HighlightDraft); expect(target.annotation.subject).toBe('Pricing question'); const status = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), reply:{ to: target.annotation.ref} , state: 'accepted', stateModel: 'review', } satisfies TextDraft); expect(AnnotationCreateResultSchema.safeParse(status).success).toBe(true); expect(status.annotation.subtype).toBe('text'); if (status.annotation.subtype !== 'text') return; expect(status.annotation.state).toBe('accepted'); expect(status.annotation.stateModel).toBe('review'); expect(status.annotation.reply?.type).toBe('reply'); const after = await page.annotations.list(); const read = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && status.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === status.annotation.ref.objectNumber, ); expect(read?.subtype).toBe('text'); if (read?.subtype === 'text'){ expect(read.state).toBe('accepted'); expect(read.stateModel).toBe('review'); } } finally{ await doc.close(); } } ); test('a draft /State without /StateModel takes its standard model, or is refused', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const{ annotation} = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), state: 'accepted', } satisfies TextDraft); expect(annotation.subtype === 'text' && annotation.stateModel).toBe('review'); let caught: unknown; try{ await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), state: 'escalated', } satisfies TextDraft); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test("a comment's line breaks are `\\n` in `contents` and `\\r` in the saved /Contents", async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const note = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), contents: 'first\nsecond\r\nthird', } satisfies TextDraft); expect(note.annotation.contents).toBe('first\nsecond\nthird'); const ref = note.annotation.ref; if (ref.kind !== 'objectNumber') throw new Error('expected an object-number ref'); const pdf = new TextDecoder('latin1').decode(await doc.download()); const objects = [ ...pdf.matchAll(new RegExp(`(?:^|[\\r\\n])${ ref.objectNumber} 0 obj`, 'g')), ]; const at = objects[objects.length - 1]!.index; const body = pdf.slice(at, pdf.indexOf('endobj', at)); expect(/\/Contents\s*\(first(?:\\r|\r)second(?:\\r|\r)third\)/.test(body)).toBe(true); } finally{ await doc.close(); } } ); test('null-clear patches truly remove /State, /StateModel, /Subj and /Contents', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const note = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), contents: 'work in progress', subject: 'Draft', state: 'none', stateModel: 'review', } satisfies TextDraft); const cycled = await page.annotations.update(note.annotation.ref, { subtype: 'text', state: 'rejected', } satisfies TextPatch); expect(cycled.appearance.changed).toBe(false); expect(cycled.annotation.subtype).toBe('text'); if (cycled.annotation.subtype === 'text'){ expect(cycled.annotation.state).toBe('rejected'); expect(cycled.annotation.stateModel).toBe('review'); } const cleared = await page.annotations.update(note.annotation.ref, { subtype: 'text', contents: null, subject: null, state: null, stateModel: null, } satisfies TextPatch); expect(cleared.appearance.changed).toBe(false); expect(cleared.annotation.contents).toBe(null); expect(cleared.annotation.subject).toBe(null); if (cleared.annotation.subtype === 'text'){ expect(cleared.annotation.state).toBe(null); expect(cleared.annotation.stateModel).toBe(null); } const after = await page.annotations.list(); const read = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && note.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === note.annotation.ref.objectNumber, ); expect(read?.contents).toBe(null); expect(read?.subject).toBe(null); if (read?.subtype === 'text'){ expect(read.state).toBe(null); expect(read.stateModel).toBe(null); } } finally{ await doc.close(); } } ); test('custom state models round-trip verbatim', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const custom = await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), state: 'in-progress', stateModel: 'X-ReviewWorkflow', } satisfies TextDraft); expect(custom.annotation.subtype).toBe('text'); if (custom.annotation.subtype !== 'text') return; expect(custom.annotation.state).toBe('in-progress'); expect(custom.annotation.stateModel).toBe('X-ReviewWorkflow'); const after = await page.annotations.list(); const read = after.annotations.find( (a) => a.ref.kind === 'objectNumber' && custom.annotation.ref.kind === 'objectNumber' && a.ref.objectNumber === custom.annotation.ref.objectNumber, ); if (read?.subtype === 'text'){ expect(read.state).toBe('in-progress'); expect(read.stateModel).toBe('X-ReviewWorkflow'); } } finally{ await doc.close(); } } ); const readBack = async (doc: DocumentHandle, ref: AnnotationRef) => (await doc.page(toPageRef(fix.pageObjectNumber)).annotations.list()).annotations.find( (annotation) => annotationKey(annotation.ref) === annotationKey(ref), ); test('a highlight becomes a squiggly line and stays the same annotation', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const mark = ( await page.annotations.create({ subtype: 'highlight', contents: 'mutation conformance: kind change', color: '#1d4ed8', quadPoints: quad, } satisfies HighlightDraft) ).annotation; const reply = ( await page.annotations.create({ subtype: 'text', rect: iconRect(shapeRect.x, shapeRect.y), contents: 'a reply to the mark', reply:{ to: mark.ref, type: 'reply'} , } satisfies TextDraft) ).annotation; const order = (await page.annotations.list()).annotations.map((a) => annotationKey(a.ref)); const result = await page.annotations.update(mark.ref, { subtype: 'squiggly'} ); expect(AnnotationUpdateResultSchema.safeParse(result).success).toBe(true); expect(result.appearance.changed).toBe(true); const changed = result.annotation; expect(changed.subtype).toBe('squiggly'); expect(annotationKey(changed.ref)).toBe(annotationKey(mark.ref)); expect(changed.nm).toBe(mark.nm); expect(changed.contents).toBe(mark.contents); expect(changed.author).toBe(mark.author); expect(changed.createdAt).toBe(mark.createdAt); if (changed.subtype === 'squiggly' && mark.subtype === 'highlight'){ expect(changed.color).toBe(mark.color); expect(changed.quadPoints).toEqual(mark.quadPoints); } const after = await page.annotations.list(); expect(after.annotations.map((a) => annotationKey(a.ref))).toEqual(order); const answer = await readBack(doc, reply.ref); expect(answer?.reply?.to && annotationKey(answer.reply.to)).toBe(annotationKey(mark.ref)); expect((await readBack(doc, mark.ref))?.subtype).toBe('squiggly'); } finally{ await doc.close(); } } ); test('a square becomes a circle with a new color, and back', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const square = ( await page.annotations.create({ subtype: 'square', box: shapeRect, color: '#008000', strokeWidth: 2, } satisfies SquareDraft) ).annotation; const circle = ( await page.annotations.update(square.ref, { subtype: 'circle', color: '#dc143c'} ) ).annotation; expect(circle.subtype).toBe('circle'); expect(annotationKey(circle.ref)).toBe(annotationKey(square.ref)); if (circle.subtype === 'circle'){ expect(circle.box).toEqual(shapeRect); expect(circle.color).toBe('#dc143c'); expect(circle.strokeWidth).toBe(2); } const back = (await page.annotations.update(square.ref, { subtype: 'square'} )).annotation; expect(back.subtype).toBe('square'); if (back.subtype === 'square') expect(back.color).toBe('#dc143c'); } finally{ await doc.close(); } } ); test('a kind outside the group, or over a value the new kind cannot hold, is refused', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const mark = ( await page.annotations.create({ subtype: 'highlight', quadPoints: quad, } satisfies HighlightDraft) ).annotation; await expect( page.annotations.update(mark.ref, { subtype: 'ink'} as unknown as AnnotationPatch), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'subtype'} , } ); const ink = ( await page.annotations.create({ subtype: 'ink', inkList: inkStrokes} satisfies InkDraft) ).annotation; await expect( page.annotations.update(ink.ref, { subtype: 'square'} as unknown as AnnotationPatch), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'subtype'} , } ); const caret = ( await page.annotations.create({ subtype: 'caret', intent: 'replace', box:{ x: shapeRect.x, y: shapeRect.y, width: 8, height: 12} , contents: 'invoice', } satisfies CaretDraft) ).annotation; const strikeout = ( await page.annotations.create({ subtype: 'strikeout', intent: 'strikeout-text-edit', quadPoints: quad, reply:{ to: caret.ref, type: 'group'} , } satisfies StrikeoutDraft) ).annotation; await expect( page.annotations.update(strikeout.ref, { subtype: 'highlight'} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'intent'} } ); const kept = await readBack(doc, strikeout.ref); expect(kept?.subtype).toBe('strikeout'); if (kept?.subtype === 'strikeout') expect(kept.intent).toBe('strikeout-text-edit'); await doc.apply({ ops: [{ type: 'annotations.update', ref: strikeout.ref, patch:{ intent: null} } , { type: 'annotations.update', ref: strikeout.ref, patch:{ subtype: 'highlight'} } , ], } ); const changed = await readBack(doc, strikeout.ref); expect(changed?.subtype).toBe('highlight'); expect(changed?.reply).toMatchObject({ type: 'group'} ); expect(changed?.reply && annotationKey(changed.reply.to)).toBe(annotationKey(caret.ref)); } finally{ await doc.close(); } } ); test('undo puts the old kind back, and so does an undo after a later change', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fix.pageObjectNumber)); const create = () => page.annotations.create({ subtype: 'highlight', color: '#ffff00', quadPoints: quad, } satisfies HighlightDraft); const mark = (await create()).annotation; const changed = await doc.apply({ ops: [{ type: 'annotations.update', ref: mark.ref, patch:{ subtype: 'underline'} } ], } ); expect((await readBack(doc, mark.ref))?.subtype).toBe('underline'); const undo = await doc.apply({ undoOf: changed.meta.opId} ); expect((await readBack(doc, mark.ref))?.subtype).toBe('highlight'); await doc.apply({ undoOf: undo.meta.opId} ); expect((await readBack(doc, mark.ref))?.subtype).toBe('underline'); const other = (await create()).annotation; const retyped = await doc.apply({ ops: [{ type: 'annotations.update', ref: other.ref, patch:{ subtype: 'underline'} } ], } ); await page.annotations.update(other.ref, { color: '#16a34a'} ); await doc.apply({ undoOf: retyped.meta.opId} ); const restored = await readBack(doc, other.ref); expect(restored?.subtype).toBe('highlight'); if (restored?.subtype === 'highlight') expect(restored.color).toBe('#16a34a'); } finally{ await doc.close(); } } ); } ); } runAnnotationPredictionConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationPredictionConformance.ts): export function runAnnotationPredictionConformance( runner: ConformanceTestRunner, options: AnnotationPredictionConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation prediction conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; let page: PageHandle; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine); const{ pages} = await doc.pages.list(); page = doc.page(toPageRef(pages[0]!.ref.objectNumber)); } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); for (const scenario of CASES){ test(scenario.name, async () =>{ const{ annotation: created} = await page.annotations.create(scenario.draft, { resources: scenario.resources, } ); const patch = typeof scenario.patch === 'function' ? scenario.patch(created) : scenario.patch; const predicted = applyAnnotationPatch(created, patch); const{ annotation: actual} = await page.annotations.update(created.ref, patch, { resources: scenario.updateResources, } ); expect(differences(predicted, actual)).toEqual([]); } ); } for (const [at, scenario] of WIDGET_CASES.entries()){ test(`widget: ${ scenario.name} `, async () =>{ const{ widgets} = await doc.forms.create({ kind: 'text', name: `predicted_${ at} `, widgets: [{ page: page.ref, rect: BOX} ], } ); const created = widgets[0]!; const predicted = applyAnnotationPatch(created, { subtype: 'widget', ...scenario.patch} ); const{ widget: actual} = await doc.forms.updateWidget(created.ref, scenario.patch); expect(differences(predicted, actual)).toEqual([]); } ); } for (const scenario of CREATE_CASES){ test(`create: ${ scenario.name} `, async () =>{ const{ annotation: actual} = await page.annotations.create(scenario.draft, { resources: scenario.resources, } ); if (!scenario.draft.nm) expect(actual.nm).toMatch(UUID_V7); const predicted = annotationOfDraft(scenario.draft, { ref: actual.ref, ...(actual.nm !== null ?{ nm: actual.nm} :{ } ), attribution:{ ...(actual.author !== null ?{ author: actual.author} :{ } ), ...(actual.userId !== null ?{ userId: actual.userId} :{ } ), ...(actual.createdBy !== null ?{ createdBy: actual.createdBy} :{ } ), ...(actual.modifiedBy !== null ?{ modifiedBy: actual.modifiedBy} :{ } ), ...(actual.createdAt !== null ?{ createdAt: actual.createdAt} :{ } ), ...(actual.modifiedAt !== null ?{ modifiedAt: actual.modifiedAt} :{ } ), } , ...(DRAWN_RECT_KINDS.has(actual.subtype) ?{ rect: actual.rect} :{ } ), } ); expect(differences(predicted, actual)).toEqual([]); } ); } } ); } runAnnotationReadConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationReadConformance.ts): export function runAnnotationReadConformance( runner: ConformanceTestRunner, options: AnnotationConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation read conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('list() returns every page, and each annotation names its page', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.annotations.list(); expect(AnnotationListSchema.safeParse(list).success).toBe(true); expect(list.pages.length >= 1).toBe(true); if (list.auditHead !== undefined){ expect(Number.isInteger(list.auditHead) && list.auditHead >= 0).toBe(true); } const target = list.pages.find((p) => p.objectNumber === options.fixture.pageObjectNumber); expect(target !== undefined).toBe(true); const onTarget = list.annotations.filter( (a) => a.page.objectNumber === options.fixture.pageObjectNumber, ); expect(onTarget.length).toBe(options.fixture.expectedAnnotationCount); } finally{ await doc.close(); } } ); test('list({ pages} ) on the test page returns the expected counts and DTO shape', async () =>{ const doc = await openFixture(engine, options); try{ const snap = await doc.annotations.list({ pages: [toPageRef(options.fixture.pageObjectNumber)], } ); expect(AnnotationListSchema.safeParse(snap).success).toBe(true); expect(snap.pages.map((p) => p.objectNumber)).toEqual([options.fixture.pageObjectNumber]); expect(snap.annotations.length).toBe(options.fixture.expectedAnnotationCount); const highlights = snap.annotations.filter((a) => a.subtype === 'highlight'); expect(highlights.length >= options.fixture.minHighlightCount).toBe(true); const unsupported = snap.annotations.filter((a) => a.subtype === 'unsupported'); expect(unsupported.length >= options.fixture.minUnsupportedCount).toBe(true); const circles = snap.annotations.filter((a) => a.subtype === 'circle'); expect(circles.length >= (options.fixture.minCircleCount ?? 0)).toBe(true); const squares = snap.annotations.filter((a) => a.subtype === 'square'); expect(squares.length >= (options.fixture.minSquareCount ?? 0)).toBe(true); const polygons = snap.annotations.filter((a) => a.subtype === 'polygon'); expect(polygons.length >= (options.fixture.minPolygonCount ?? 0)).toBe(true); const polylines = snap.annotations.filter((a) => a.subtype === 'polyline'); expect(polylines.length >= (options.fixture.minPolylineCount ?? 0)).toBe(true); const lines = snap.annotations.filter((a) => a.subtype === 'line'); expect(lines.length >= (options.fixture.minLineCount ?? 0)).toBe(true); const inks = snap.annotations.filter((a) => a.subtype === 'ink'); expect(inks.length >= (options.fixture.minInkCount ?? 0)).toBe(true); const freeTexts = snap.annotations.filter((a) => a.subtype === 'free-text'); expect(freeTexts.length >= (options.fixture.minFreeTextCount ?? 0)).toBe(true); const carets = snap.annotations.filter((a) => a.subtype === 'caret'); expect(carets.length >= (options.fixture.minCaretCount ?? 0)).toBe(true); } finally{ await doc.close(); } } ); test('shape/vertex/line annotations expose their family fields', async () =>{ const doc = await openFixture(engine, options); try{ const snap = await doc.annotations.list({ pages: [toPageRef(options.fixture.pageObjectNumber)], } ); for (const a of snap.annotations){ if (a.subtype === 'ink'){ expect(a.color !== undefined && a.color !== null).toBe(true); expect(typeof a.strokeWidth).toBe('number'); expect(typeof a.borderStyle).toBe('string'); expect(typeof a.opacity).toBe('number'); expect('interiorColor' in a).toBe(false); expect(Array.isArray(a.inkList)).toBe(true); expect(a.inkList.length >= 1).toBe(true); expect(Array.isArray(a.inkList[0])).toBe(true); expect(a.inkList[0]!.length >= 1).toBe(true); continue; } if (a.subtype === 'free-text'){ expect(typeof a.fontFamily).toBe('string'); expect(typeof a.fontSize).toBe('number'); expect(typeof a.textAlign).toBe('string'); expect(a.color !== undefined && a.color !== null).toBe(true); expect('interiorColor' in a).toBe(true); expect(a.intent === 'free-text' || a.intent === 'free-text-callout').toBe(true); if (a.intent === 'free-text-callout' && a.calloutLine){ expect(a.calloutLine.length === 2 || a.calloutLine.length === 3).toBe(true); } continue; } if (a.subtype === 'caret'){ expect(a.color !== undefined && a.color !== null).toBe(true); expect(typeof a.opacity).toBe('number'); expect('strokeWidth' in a).toBe(false); expect('quadPoints' in a).toBe(false); continue; } const isFilledStyle = a.subtype === 'circle' || a.subtype === 'square' || a.subtype === 'polygon' || a.subtype === 'polyline' || a.subtype === 'line'; if (!isFilledStyle) continue; expect(a.color !== undefined && a.color !== null).toBe(true); expect(typeof a.strokeWidth).toBe('number'); expect(typeof a.borderStyle).toBe('string'); expect(typeof a.opacity).toBe('number'); expect('interiorColor' in a).toBe(true); if (a.subtype === 'polygon' || a.subtype === 'polyline'){ expect(Array.isArray(a.vertices)).toBe(true); expect(a.vertices.length >= 2).toBe(true); } if (a.subtype === 'polyline'){ expect(typeof a.lineEndings.start).toBe('string'); expect(typeof a.lineEndings.end).toBe('string'); } if (a.subtype === 'line'){ expect(typeof a.linePoints.start.x).toBe('number'); expect(typeof a.linePoints.end.y).toBe('number'); expect(typeof a.lineEndings.start).toBe('string'); expect(typeof a.lineEndings.end).toBe('string'); } } } finally{ await doc.close(); } } ); test('page.annotations.list() is the document list of that page', async () =>{ const doc = await openFixture(engine, options); try{ const ref = toPageRef(options.fixture.pageObjectNumber); const onPage = await doc.page(ref).annotations.list(); expect(AnnotationListSchema.safeParse(onPage).success).toBe(true); expect(onPage.annotations.length).toBe(options.fixture.expectedAnnotationCount); expect(onPage).toEqual(await doc.annotations.list({ pages: [ref]} )); } finally{ await doc.close(); } } ); test('every annotation DTO satisfies AnnotationSchema (discriminated union)', async () =>{ const doc = await openFixture(engine, options); try{ const snap = await doc.annotations.list({ pages: [toPageRef(options.fixture.pageObjectNumber)], } ); for (const a of snap.annotations){ const result = AnnotationSchema.safeParse(a); expect(result.success).toBe(true); } } finally{ await doc.close(); } } ); test('AnnotationSchema reads a subtype it does not know as unsupported, and a malformed one it knows fails', async () =>{ const doc = await openFixture(engine, options); try{ const snap = await doc.annotations.list({ pages: [toPageRef(options.fixture.pageObjectNumber)], } ); for (const annotation of snap.annotations){ const newer ={ ...annotation, subtype: 'from-a-newer-server'} ; expect(AnnotationSchema.parse(newer)).toMatchObject({ subtype: 'unsupported', ref: annotation.ref, rect: annotation.rect, } ); expect(AnnotationSchema.safeParse({ ...annotation, rect: 'wide'} ).success).toBe(false); } } finally{ await doc.close(); } } ); if (options.fixture.expectsInlineAnnotation){ test('an annotation born inline is named by its baseIndex: its position in the file', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const{ annotations} = await page.annotations.list(); const inline = annotations.find((a) => a.ref.kind === 'baseIndex'); expect(inline !== undefined).toBe(true); const again = await page.annotations.list(); expect( again.annotations.find((a) => annotationKey(a.ref) === annotationKey(inline!.ref)), ).toEqual(inline); } finally{ await doc.close(); } } ); test('a baseIndex that names no inline annotation is NotFound', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const{ annotations} = await page.annotations.list(); const missing = await page.annotations .update({ kind: 'baseIndex', page: toPageRef(options.fixture.pageObjectNumber), baseIndex: annotations.length + 10, } , { contents: 'nobody'} , ) .then( () => null, (error: unknown) => error, ); expect(EngineError.is(missing, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); } test('abort() on listRaw rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const p = doc.annotations.list({ pages: [toPageRef(options.fixture.pageObjectNumber)]} ); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); test('listRaw on an unknown pageObjectNumber throws NotFound', async () =>{ const doc = await openFixture(engine, options); try{ let caught: unknown; try{ await doc.annotations.list({ pages: [toPageRef(999_999_999)]} ); } catch (err){ caught = err; } expect(caught).toBeTruthy(); expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); } ); } runAnnotationResourceConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationResourceConformance.ts): export function runAnnotationResourceConformance( runner: ConformanceTestRunner, options: AnnotationResourceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation resource conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const onPage = async ( fixture: AnnotationResourceFixture, run: (page: PageHandle, doc: DocumentHandle) => Promise, ): Promise =>{ const doc = await options.open(engine, fixture); try{ await run(doc.page(await firstPage(doc)), doc); } finally{ await doc.close(); } } ; const rasterOf = (page: PageHandle, ref: AnnotationRef) => appearanceRaster(page, ref); const expectSameDrawing = (actual: Raster, expected: Raster) =>{ expect([actual.width, actual.height]).toEqual([expected.width, expected.height]); expect(maxDifference(actual, expected) <= 3).toBe(true); } ; test("a stamp's appearance and its data make the same stamp", async () =>{ await onPage('authoring', async (page) =>{ const rect: PageBox ={ x: 100, y: 100, width: 160, height: 80} ; const{ annotation: created} = await page.annotations.create({ subtype: 'stamp', box: rect, rotation: 30, fit: 'cover', opacity: 0.5, name: 'Approved', } , { resources:{ appearance: BANDS_PDF} } , ); const appearance = await page.annotations.downloadResource(created.ref, 'appearance'); expect([...appearance.subarray(0, 4)]).toEqual(PDF_MAGIC); const data = copyOnItsPage(created); const copy = (await page.annotations.create(data, { resources:{ appearance} } )) .annotation; expect(dataOf(copy)).toEqual(dataOf(created)); expectSameDrawing(await rasterOf(page, copy.ref), await rasterOf(page, created.ref)); } ); } ); const acrobatStamps = async (page: PageHandle) =>{ const{ annotations} = await page.annotations.list(); const stamps = annotations.filter((annotation) => annotation.subtype === 'stamp'); expect(stamps.length).toBe(2); return stamps; } ; const expectPaintedOnce = (raster: Raster, opacity: number) =>{ expect(Math.abs(maxAlpha(raster) - opacity * 255) <= 3).toBe(true); } ; test('a copy of a stamp another tool made is drawn as the page shows it', async () =>{ await onPage('acrobat-stamps', async (page) =>{ for (const stamp of await acrobatStamps(page)){ expect(stamp.opacity! > 0.25 && stamp.opacity! < 0.35).toBe(true); const appearance = await page.annotations.downloadResource(stamp.ref, 'appearance'); const data = copyOnItsPage(stamp); const copy = (await page.annotations.create(data, { resources:{ appearance} } )) .annotation; expect(dataOf(copy)).toEqual({ ...dataOf(stamp), popup: null} ); const drawn = await rasterOf(page, copy.ref); expectPaintedOnce(drawn, stamp.opacity!); expectSameDrawing(drawn, await rasterOf(page, stamp.ref)); } } ); } ); test('a stamp another tool made keeps its opacity through a resize', async () =>{ await onPage('acrobat-stamps', async (page) =>{ for (const stamp of await acrobatStamps(page)){ const{ x, y, width, height} = stamp.box; const{ annotation: updated} = await page.annotations.update(stamp.ref, { box:{ x, y, width: width * 2, height: height * 2} , } ); expectPaintedOnce(await rasterOf(page, updated.ref), stamp.opacity!); } } ); } ); test('a new opacity on a stamp another tool made replaces its own', async () =>{ await onPage('acrobat-stamps', async (page) =>{ for (const stamp of await acrobatStamps(page)){ for (const opacity of [1, 0.5]){ const{ annotation: updated} = await page.annotations.update(stamp.ref, { opacity} ); expect(updated.subtype === 'stamp' && updated.opacity).toBe(opacity); expectPaintedOnce(await rasterOf(page, updated.ref), opacity); } } } ); } ); test('a turned stamp renders unturned as its unturned twin', async () =>{ await onPage('authoring', async (page) =>{ const box: PageBox ={ x: 100, y: 100, width: 160, height: 80} ; const common ={ subtype: 'stamp', fit: 'cover', opacity: 0.5} as const; const turned = ( await page.annotations.create({ ...common, box, rotation: 30} , { resources:{ appearance: BANDS_PDF} } , ) ).annotation; const flat = ( await page.annotations.create({ ...common, box} , { resources:{ appearance: BANDS_PDF} } , ) ).annotation; expectSameDrawing(await rasterOf(page, turned.ref), await rasterOf(page, flat.ref)); } ); } ); const rewrappedStamp = async (page: PageHandle, name: 'a' | 'b' | 'c') =>{ const{ annotations} = await page.annotations.list(); const stamp = annotations.find( (annotation): annotation is Extract => annotation.subtype === 'stamp' && annotation.nm === `rewrapped-${ name} `, ); if (!stamp) throw new Error(`no stamp rewrapped-${ name} `); return stamp; } ; test('a stamp we made is ours again after Acrobat wrapped it', async () =>{ await onPage('acrobat-rewrapped', async (page) =>{ const turned = await rewrappedStamp(page, 'a'); const opaque = await rewrappedStamp(page, 'b'); expect(turned).toMatchObject({ rotation: 330, fit: 'contain'} ); expect(Math.abs(turned.opacity! - 0.6) < 0.005).toBe(true); expect(opaque.opacity).toBe(1); for (const stamp of [turned, opaque]){ expectPaintedOnce(await rasterOf(page, stamp.ref), stamp.opacity!); const drawing = await page.annotations.downloadResource(stamp.ref, 'appearance'); expect(pageSize(drawing)).toEqual([200, 100]); } } ); } ); test('a resize of a turned stamp Acrobat wrapped turns it once', async () =>{ await onPage('acrobat-rewrapped', async (page) =>{ const turned = await rewrappedStamp(page, 'a'); const drawing = await page.annotations.downloadResource(turned.ref, 'appearance'); const{ box} = turned; const{ annotation: updated} = await page.annotations.update(turned.ref, { box:{ ...box, width: box.width + 60} , rotation: turned.rotation, } ); expect( pageSize(await page.annotations.downloadResource(updated.ref, 'appearance')), ).toEqual([200, 100]); const data = copyOnItsPage(updated); const twin = (await page.annotations.create(data, { resources:{ appearance: drawing} } )) .annotation; expectSameDrawing(await rasterOf(page, updated.ref), await rasterOf(page, twin.ref)); expectPaintedOnce(await rasterOf(page, updated.ref), turned.opacity!); } ); } ); test('a new opacity on a stamp Acrobat wrapped replaces the old one', async () =>{ await onPage('acrobat-rewrapped', async (page) =>{ for (const name of ['a', 'b'] as const){ const stamp = await rewrappedStamp(page, name); for (const opacity of [1, 0.5, 0.3]){ const{ annotation: updated} = await page.annotations.update(stamp.ref, { opacity} ); expectPaintedOnce(await rasterOf(page, updated.ref), opacity); } } } ); } ); for (const fixture of ['acrobat-roundtrip-60', 'acrobat-roundtrip-100'] as const){ test(`a turned stamp from here, edited in Acrobat, turns once (${ fixture} )`, async () =>{ await onPage(fixture, async (page) =>{ const{ annotations} = await page.annotations.list(); const stamp = annotations.find( (annotation): annotation is Extract => annotation.subtype === 'stamp', )!; expect(stamp.rotation !== null).toBe(true); expect( Math.abs(stamp.opacity - (fixture === 'acrobat-roundtrip-60' ? 0.6 : 1)) < 0.01, ).toBe(true); const drawing = await page.annotations.downloadResource(stamp.ref, 'appearance'); const twin = ( await page.annotations.create(copyOnItsPage(stamp), { resources:{ appearance: drawing, } , } ) ).annotation; expectSameDrawing(await rasterOf(page, stamp.ref), await rasterOf(page, twin.ref)); const{ box} = stamp; const{ annotation: updated} = await page.annotations.update(stamp.ref, { box:{ ...box, width: box.width + 40} , rotation: stamp.rotation, } ); const resized = ( await page.annotations.create(copyOnItsPage(updated), { resources:{ appearance: drawing, } , } ) ).annotation; expectSameDrawing(await rasterOf(page, updated.ref), await rasterOf(page, resized.ref)); } ); } ); } test('an opacity the data does not describe is part of the drawing', async () =>{ await onPage('acrobat-rewrapped', async (page) =>{ const stamp = await rewrappedStamp(page, 'c'); expect(stamp.opacity).toBe(1); const shown = await rasterOf(page, stamp.ref); expectPaintedOnce(shown, 0.35); const appearance = await page.annotations.downloadResource(stamp.ref, 'appearance'); expect(pageSize(appearance)).toEqual([300, 120]); const data = copyOnItsPage(stamp); const copy = (await page.annotations.create(data, { resources:{ appearance} } )) .annotation; expectSameDrawing(await rasterOf(page, copy.ref), shown); } ); } ); const exportCycles = async (page: PageHandle, stamp: Annotation, rounds: number) =>{ const drawings = [await page.annotations.downloadResource(stamp.ref, 'appearance')]; const data = copyOnItsPage(stamp); for (let round = 0; round < rounds; round++){ const appearance = drawings[drawings.length - 1]!; const copy = (await page.annotations.create(data, { resources:{ appearance} } )) .annotation; drawings.push(await page.annotations.downloadResource(copy.ref, 'appearance')); } return drawings; } ; test('a drawing exported again after an import is the same bytes', async () =>{ await onPage('authoring', async (page) =>{ const vector = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 20, width: 200, height: 100} , fit: 'contain', } , { resources:{ appearance: BANDS_PDF} } , ) ).annotation; const image = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 140, width: 100, height: 100} , fit: 'cover', } , { resources:{ appearance: BANDS_PNG} } , ) ).annotation; for (const stamp of [vector, image]){ const [first, ...again] = await exportCycles(page, stamp, 3); for (const drawing of again) expect(sameBytes(drawing, first!)).toBe(true); } } ); await onPage('acrobat-stamps', async (page) =>{ for (const stamp of await acrobatStamps(page)){ const [first, ...again] = await exportCycles(page, stamp, 2); for (const drawing of again) expect(sameBytes(drawing, first!)).toBe(true); } } ); } ); test('an image is the same drawing in any box', async () =>{ await onPage('authoring', async (page) =>{ const square = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 20, width: 100, height: 100} , fit: 'contain', } , { resources:{ appearance: BANDS_PNG} } , ) ).annotation; const wide = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 140, width: 300, height: 100} , fit: 'cover', } , { resources:{ appearance: BANDS_PNG} } , ) ).annotation; const a = await page.annotations.downloadResource(square.ref, 'appearance'); const b = await page.annotations.downloadResource(wide.ref, 'appearance'); expect(sameBytes(a, b)).toBe(true); expect(pageSize(a)).toEqual([30, 10]); } ); } ); test('a cover stamp set to contain shows the whole image', async () =>{ await onPage('authoring', async (page) =>{ const stamp = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 20, width: 100, height: 100} , fit: 'cover', } , { resources:{ appearance: BANDS_PNG} } , ) ).annotation; const{ annotation: updated} = await page.annotations.update(stamp.ref, { fit: 'contain', } ); const raster = await rasterOf(page, updated.ref); const y = Math.floor(raster.height / 2); const colour = (fx: number) =>{ const i = (y * raster.width + Math.floor(raster.width * fx)) * 4; return [raster.rgba[i], raster.rgba[i + 1], raster.rgba[i + 2]]; } ; expect(colour(0.15)).toEqual([255, 0, 0]); expect(colour(0.5)).toEqual([0, 255, 0]); expect(colour(0.85)).toEqual([0, 0, 255]); } ); } ); test('an exported drawing is the drawing and nothing else', async () =>{ await onPage('authoring', async (page) =>{ const stamp = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 20, width: 200, height: 100} , opacity: 0.5, } , { resources:{ appearance: BANDS_PDF} } , ) ).annotation; const text = new TextDecoder('latin1').decode( await page.annotations.downloadResource(stamp.ref, 'appearance'), ); expect(text.includes('/Info')).toBe(false); expect(text.includes('CreationDate')).toBe(false); expect(text.includes('EPDFOrigContentRect')).toBe(false); expect(text.includes('EPDFWRAP')).toBe(false); } ); } ); test('stamps with the same artwork place one drawing', async () =>{ await onPage('authoring', async (page, doc) =>{ for (let i = 0; i < 10; i++){ const x = 20 + 50 * i; await page.annotations.create({ subtype: 'stamp', box:{ x, y: 20, width: 40, height: 20} } , { resources:{ appearance: BANDS_PNG} } , ); await page.annotations.create({ subtype: 'stamp', box:{ x, y: 60, width: 40, height: 20} } , { resources:{ appearance: BANDS_PDF} } , ); } const saved = await rewrite(doc); expect(images(saved)).toBe(1); expect(occurrences(saved, BANDS_PDF_CONTENT)).toBe(1); } ); } ); test('an image and the drawing exported from it are one drawing', async () =>{ await onPage('authoring', async (page, doc) =>{ const stamp = ( await page.annotations.create({ subtype: 'stamp', box:{ x: 20, y: 20, width: 100, height: 100} } , { resources:{ appearance: BANDS_PNG} } , ) ).annotation; const appearance = await page.annotations.downloadResource(stamp.ref, 'appearance'); await page.annotations.create({ subtype: 'stamp', box:{ x: 200, y: 20, width: 60, height: 20} } , { resources:{ appearance} } , ); expect(images(await rewrite(doc))).toBe(1); } ); } ); test('new artwork for one stamp leaves a stamp sharing the old alone', async () =>{ await onPage('authoring', async (page, doc) =>{ const place = async (x: number) => ( await page.annotations.create({ subtype: 'stamp', box:{ x, y: 20, width: 100, height: 100} , opacity: 0.5, } , { resources:{ appearance: BANDS_PNG} } , ) ).annotation; const changed = await place(20); const kept = await place(200); const before = await page.annotations.downloadResource(kept.ref, 'appearance'); const shown = await rasterOf(page, kept.ref); await page.annotations.update(changed.ref, { } , { resources:{ appearance: BANDS_PDF} } ); expect( sameBytes(await page.annotations.downloadResource(kept.ref, 'appearance'), before), ).toBe(true); expectSameDrawing(await rasterOf(page, kept.ref), shown); const saved = await rewrite(doc); expect(images(saved)).toBe(1); expect(occurrences(saved, BANDS_PDF_CONTENT)).toBe(1); } ); } ); test('a role the kind does not take is refused', async () =>{ await onPage('authoring', async (page) =>{ const rect: PageBox ={ x: 300, y: 300, width: 60, height: 40} ; const refused ={ code: EngineErrorCode.InvalidArg} ; const square = (await page.annotations.create({ subtype: 'square', box: rect} )).annotation; await expect( page.annotations.downloadResource(square.ref, 'appearance'), ).rejects.toMatchObject(refused); const stamp = ( await page.annotations.create({ subtype: 'stamp', box: rect} , { resources:{ appearance: BANDS_PDF} } , ) ).annotation; await expect(page.annotations.downloadResource(stamp.ref, 'file')).rejects.toMatchObject( refused, ); } ); } ); } ); } runAnnotationRotationConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationRotationConformance.ts): export function runAnnotationRotationConformance( runner: ConformanceTestRunner, options: AnnotationRotationConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation rotation conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const onPage = async ( fixture: AnnotationRotationFixture, run: (page: PageHandle, layout: PageLayout) => Promise, ): Promise =>{ const doc = await options.open(engine, fixture); try{ const{ pages} = await doc.pages.list(); await run(doc.page(pages[0]!.ref), pages[0]!); } finally{ await doc.close(); } } ; const expectRect = (actual: PageBox | null, expected: PageBox, tolerance: number) =>{ expect(actual !== null).toBe(true); for (const edge of ['x', 'y', 'width', 'height'] as const){ expect(Math.abs(actual![edge] - expected[edge]) <= tolerance).toBe(true); } } ; const stampOf = async (page: PageHandle): Promise =>{ const{ annotations} = await page.annotations.list(); const stamp = annotations.find((a): a is Stamp => a.subtype === 'stamp'); if (!stamp) throw new Error('no stamp'); return stamp; } ; const textBoxOf = async (page: PageHandle, contents: string): Promise =>{ const{ annotations} = await page.annotations.list(); const box = annotations.find( (a): a is FreeText => a.subtype === 'free-text' && a.contents === contents, ); if (!box) throw new Error(`no text box ${ JSON.stringify(contents)} `); return box; } ; const appearanceOf = async (page: PageHandle, ref: Annotation['ref']): Promise =>{ const{ appearances} = await page.annotations.renderAppearances({ format: 'png'} ); const found = appearances.find( (a) => a.mode === 'normal' && annotationKey(a.ref) === annotationKey(ref), ); if (!found) throw new Error('no appearance'); const{ url, revoke} = await found.image.objectUrl(); try{ return await decodePng(new Uint8Array(await (await fetch(url)).arrayBuffer())); } finally{ revoke(); } } ; test('a stamp Acrobat turned reads its turn and its own box', async () =>{ await onPage('acrobat-stamp-rotated', async (page, layout) =>{ const stamp = await stampOf(page); expect(stamp.rotation).toBe(36); expectRect( stamp.box, pageBoxOf({ left: 155.784, bottom: 508.966, right: 466.366, top: 618.542} , layout.pdfCropBox, ), 0.02, ); expectRect( stamp.rect, pageBoxOf({ left: 153.238, bottom: 428.152, right: 468.912, top: 699.356} , layout.pdfCropBox, ), 0.01, ); } ); } ); test('a text box Acrobat turned a quarter reads its turn', async () =>{ await onPage('acrobat-freetext-rotated', async (page, layout) =>{ const turned = await textBoxOf(page, 'test 123'); expect(turned.rotation).toBe(270); expectRect( turned.box, pageBoxOf({ left: 233.423, bottom: 309.413, right: 341.423, top: 341.423} , layout.pdfCropBox, ), 0.01, ); const upright = await textBoxOf(page, 'test\ntest 123'); expect(upright.rotation).toBeNull(); expectRect(upright.box, upright.rect, 0); } ); } ); test('a change to a text box Acrobat turned keeps it turned', async () =>{ await onPage('acrobat-freetext-rotated', async (page) =>{ const turned = await textBoxOf(page, 'test 123'); const{ annotation} = await page.annotations.update(turned.ref, { subtype: 'free-text', color: '#c8e6ff', } ); const updated = annotation as FreeText; expect(updated.rotation).toBe(270); expectRect(updated.box, turned.box, 0.01); expectRect(updated.rect, turned.rect, 0.01); const raster = await appearanceOf(page, updated.ref); expect(raster.width > 2 * raster.height).toBe(true); } ); } ); test('moving a stamp Acrobat turned turns it once', async () =>{ await onPage('acrobat-stamp-rotated', async (page) =>{ const stamp = await stampOf(page); const moved ={ ...stamp.box, x: stamp.box.x + 40} ; const{ annotation} = await page.annotations.update(stamp.ref, { subtype: 'stamp', box: moved, rotation: stamp.rotation, } ); const updated = annotation as Stamp; expect(updated.rotation).toBe(36); expectRect(updated.box, moved, 0.02); expectRect(updated.rect, { ...stamp.rect, x: stamp.rect.x + 40} , 0.02); const drawing = await page.annotations.downloadResource(updated.ref, 'appearance'); const [width, height] = pageSize(drawing); expect(Math.abs(width / height - 906.89 / 319.96) < 0.01).toBe(true); } ); } ); test("a turned box's rect is the upright box around it", async () =>{ await onPage('authoring', async (page) =>{ const{ annotation} = await page.annotations.create({ subtype: 'square', box:{ x: 100, y: 100, width: 200, height: 200} , rotation: 30, } ); expectRect( annotation.rect, { x: 63.397, y: 63.397, width: 273.206, height: 273.206} , 0.01, ); expect((annotation as{ rotation: number | null} ).rotation).toBe(30); } ); } ); test('a create gives a quarter turn by where it stands: its rect, the box worked out', async () =>{ await onPage('authoring', async (page) =>{ const rect ={ x: 100, y: 100, width: 40, height: 160} ; const{ annotation: square} = await page.annotations.create({ subtype: 'square', rect, rotation: 90, } ); expectRect(square.rect, rect, 0.01); expect((square as{ rotation: number | null} ).rotation).toBe(90); expectRect( (square as{ box: PageBox} ).box, { x: 40, y: 160, width: 160, height: 40} , 0.01, ); const{ annotation: text} = await page.annotations.create({ subtype: 'free-text', rect:{ x: 300, y: 100, width: 30, height: 200} , rotation: 270, contents: 'Up the page', } ); expectRect(text.rect, { x: 300, y: 100, width: 30, height: 200} , 0.01); expectRect((text as FreeText).box, { x: 215, y: 185, width: 200, height: 30} , 0.01); } ); } ); test('a rect places a box at a quarter turn only, and a create gives one or the other', async () =>{ await onPage('authoring', async (page) =>{ const refusal = (draft: Record) => page.annotations.create({ subtype: 'square', ...draft} as never).then( () => null, (error: unknown) => error as{ code?: string; details?: Record} , ); const tilted = await refusal({ rect:{ x: 10, y: 10, width: 40, height: 40} , rotation: 20, } ); expect(tilted).toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'rect'} , } ); const neither = await refusal({ rotation: 90} ); expect(neither).toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'box'} , } ); const{ annotations} = await page.annotations.list(); expect(annotations).toHaveLength(0); } ); } ); test('a rect resizes a box at a quarter turn along its own sides', async () =>{ await onPage('authoring', async (page) =>{ const{ annotation} = await page.annotations.create({ subtype: 'square', box:{ x: 100, y: 100, width: 160, height: 40} , rotation: 90, } ); const rect ={ x: 120, y: 40, width: 60, height: 200} ; const{ annotation: resized} = await page.annotations.update(annotation.ref, { rect} ); expectRect(resized.rect, rect, 0.01); expect((resized as{ rotation: number | null} ).rotation).toBe(90); expectRect( (resized as{ box: PageBox} ).box, { x: 50, y: 110, width: 200, height: 60} , 0.01, ); } ); } ); test('a turned drawing that reaches past its box is drawn as the page shows it', async () =>{ await onPage('authoring', async (page) =>{ const box ={ x: 200, y: 400, width: 100, height: 60} ; const{ annotation: plain} = await page.annotations.create({ subtype: 'square', box, rotation: 30, } ); const{ annotation: cloudy} = await page.annotations.create({ subtype: 'square', box:{ ...box, y: 200} , rotation: 30, cloudyIntensity: 1, strokeWidth: 2, } ); const turned = turnedBounds(box, 30); expectRect(plain.rect, turned, 0.01); expect(cloudy.rect.width > turned.width + 2).toBe(true); const{ appearances} = await page.annotations.renderAppearances(); const rectOf = (ref: Annotation['ref']) => appearances.find( (a) => a.mode === 'normal' && annotationKey(a.ref) === annotationKey(ref), )!.rect; expectRect(rectOf(plain.ref), (plain as{ box: PageBox} ).box, 0.01); expectRect(rectOf(cloudy.ref), cloudy.rect, 0.01); } ); } ); test('rotation turns clockwise, as the page shows it', async () =>{ await onPage('authoring', async (page) =>{ const box ={ x: 200, y: 300, width: 100, height: 100} ; await page.annotations.create({ subtype: 'square', box, rotation: 30, color: '#0000ff', interiorColor: '#0000ff', } ); const area ={ x: 150, y: 250, width: 200, height: 200} ; const image = await page.render.image({ format: 'png', target:{ kind: 'rect', rect: area} , } ); const{ url, revoke} = await image.objectUrl(); let raster: Raster; try{ raster = await decodePng(new Uint8Array(await (await fetch(url)).arrayBuffer())); } finally{ revoke(); } const top = highestInk(raster); expect(top !== null).toBe(true); expect(top! < raster.width / 2).toBe(true); } ); } ); } ); } runAnnotationTransferConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAnnotationTransferConformance.ts): export function runAnnotationTransferConformance( runner: ConformanceTestRunner, options: AnnotationTransferConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`annotation transfer conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const exported = async (fixture: string) =>{ const doc = await options.open(engine, fixture); if (fixture === 'authoring') await fill(doc); return{ doc, bundle: await doc.annotations.export()} ; } ; const bare = async (fixture: string) =>{ const doc = await options.open(engine, fixture); const kept = new Set(); const pages = (await doc.pages.list()).pages.map((entry) => toPageRef(entry.ref.objectNumber), ); for (const pageRef of pages){ for (; ; ){ const{ annotations} = await doc.annotations.list({ pages: [pageRef]} ); const last = [...annotations].reverse().find((annotation) => !isFieldWidget(annotation)); if (!last) break; await doc.page(pageRef).annotations.delete(last.ref); } const{ annotations} = await doc.annotations.list({ pages: [pageRef]} ); for (const annotation of annotations) kept.add(annotationKey(annotation.ref)); } return{ doc, kept} ; } ; const roundTrip = async ( fixture: string, attribution: Attribution, check: (run:{ source: DocumentHandle; bundle: AnnotationBundle; copy: DocumentHandle; result: AnnotationImportResult; again: AnnotationBundle; kept: ReadonlySet; } ) => Promise, ) =>{ const{ doc: source, bundle} = await exported(fixture); const{ doc: copy, kept} = await bare(fixture); try{ const result = await copy.annotations.import(bundle, { attribution} ); const again = without(await copy.annotations.export(), kept); await check({ source, bundle, copy, result, again, kept} ); } finally{ await source.close(); await copy.close(); } } ; const expectFramesHoldGeometry = (bundle: AnnotationBundle) =>{ const epsilon = 0.01; for (const{ data} of bundle.items){ if (!FRAMED.has(data.subtype)) continue; const{ rect} = data; const outside = geometryOf(data).filter( ({ x, y} ) => x < rect.x - epsilon || x > rect.x + rect.width + epsilon || y < rect.y - epsilon || y > rect.y + rect.height + epsilon, ); expect({ key: annotationKey(data.ref), outside} ).toEqual({ key: annotationKey(data.ref), outside: [], } ); } } ; const expectTurnedRects = (bundle: AnnotationBundle) =>{ for (const{ data} of bundle.items){ const turn = turnOf(data); if (!turn) continue; const expected = pdfRectTurnedBounds(edgesOf(turn.box), turn.rotation); const actual = edgesOf(data.rect); const far = (['left', 'bottom', 'right', 'top'] as const).filter( (edge) => Math.abs(actual[edge] - expected[edge]) > 0.01, ); expect({ key: annotationKey(data.ref), far} ).toEqual({ key: annotationKey(data.ref), far: [], } ); } } ; const expectSameResources = (actual: AnnotationBundle, expected: AnnotationBundle) =>{ expect(Object.keys(actual.resources).sort()).toEqual(Object.keys(expected.resources).sort()); for (const [id, bytes] of Object.entries(expected.resources)){ expect(sameBytes(actual.resources[id as keyof typeof actual.resources]!, bytes)).toBe(true); } } ; for (const fixture of options.fixtures){ describe(fixture, () =>{ test('R1–R4: a restoring import exports as its source, as far as the import took it', async () =>{ await roundTrip(fixture, 'restore', async ({ bundle, result, again} ) =>{ const taken = asTaken(bundle, result.dropped); expect(normalized(again, 'restore')).toEqual(normalized(taken, 'restore')); expectFramesHoldGeometry(again); expectTurnedRects(again); expectSameResources(again, taken); } ); } ); test('R1–R2: a stamping import does too, apart from the attribution and names it stamps', async () =>{ await roundTrip(fixture, 'stamp', async ({ bundle, result, again} ) =>{ const taken = asTaken(bundle, result.dropped); for (const annotation of result.annotations) expect(annotation.nm).toMatch(UUID_V7); expect(normalized(again, 'stamp')).toEqual(normalized(taken, 'stamp')); expectFramesHoldGeometry(again); expectTurnedRects(again); expectSameResources(again, taken); } ); } ); test('R5: a stamp draws as its source, and in our own file every kind does', async () =>{ await roundTrip(fixture, 'restore', async ({ source, bundle, copy, result} ) =>{ const copyOf = new Map( result.refMap.map(({ from, to} ) => [annotationKey(from), to] as const), ); for (const entry of bundle.pages){ const drawn = await appearanceRasters(source.page(entry.page)); const copies = await appearanceRasters(copy.page(entry.page)); for (const{ data} of bundle.items){ if (data.ref.page.objectNumber !== entry.page.objectNumber) continue; if (fixture !== 'authoring' && data.subtype !== 'stamp') continue; const to = copyOf.get(annotationKey(data.ref)); const original = drawn.get(annotationKey(data.ref)); if (!to || !original) continue; const copied = copies.get(annotationKey(to)); const key = annotationKey(data.ref); expect({ key, size: copied && [copied.width, copied.height], same: !!copied && maxShiftedDifference(copied, original) <= 3, } ).toEqual({ key, size: [original.width, original.height], same: true} ); } } } ); } ); test('R7–R8: a second import names nothing twice and adds no drawing', async () =>{ await roundTrip(fixture, 'restore', async ({ bundle, copy, result, again, kept} ) =>{ const taken = asTaken(bundle, result.dropped); const second = await copy.annotations.import(bundle); const conflicts = new Set( second.dropped .filter((drop) => drop.reason === 'name-conflict') .map((drop) => annotationKey(drop.ref)), ); for (const{ data} of taken.items){ if (data.nm) expect(conflicts.has(annotationKey(data.ref))).toBe(true); } expect(second.annotations.every((created) => created.nm === null)).toBe(true); const third = without(await copy.annotations.export(), kept); expect(Object.keys(third.resources).sort()).toEqual( Object.keys(again.resources).sort(), ); } ); } ); } ); } } ); } runAppearanceStatesConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAppearanceStatesConformance.ts): export function runAppearanceStatesConformance( runner: ConformanceTestRunner, options: AppearanceStatesConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`appearance states conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; let page: PageHandle; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine); const{ pages} = await doc.pages.list(); page = doc.page(toPageRef(pages[0]!.ref.objectNumber)); } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); const annotations = async () =>{ const{ annotations: listed} = await page.annotations.list(); const{ widgets} = await doc.forms.list(); const box = widgets.find((widget) => widget.page.objectNumber === page.ref.objectNumber); const square = listed.find((annotation) => annotation.subtype === 'square'); if (!box || !square) throw new Error('the fixture has a check box and a square'); expect(listed.some((annotation) => annotation.subtype === 'widget')).toBe(false); return{ box, square} ; } ; const labelsOf = (appearances: readonly AnnotationAppearanceImage[]) =>{ const labels = new Map(); for (const{ ref, mode, state} of appearances){ const key = annotationKey(ref); labels.set(key, [...(labels.get(key) ?? []), `${ mode} :${ state ?? '-'} `].sort()); } return labels; } ; const render = async (modes?: AnnotationAppearanceMode[]) =>{ const options ={ format: 'png' as const, viewport:{ kind: 'scale' as const, scale: 1} , ...(modes ?{ modes} :{ } ), } ; const [annotationImages, widgetImages] = await Promise.all([ page.annotations.renderAppearances(options), page.forms.renderAppearances(options), ]); return{ appearances: [...annotationImages.appearances, ...widgetImages.appearances]} ; } ; test("each family's batch holds only its own pictures", async () =>{ const{ box, square} = await annotations(); const options ={ format: 'png' as const, viewport:{ kind: 'scale' as const, scale: 1} } ; const keys = async (batch: Promise<{ appearances: readonly AnnotationAppearanceImage[]} >) => new Set((await batch).appearances.map((appearance) => annotationKey(appearance.ref))); expect(await keys(page.annotations.renderAppearances(options))).toEqual( new Set([annotationKey(square.ref)]), ); expect(await keys(page.forms.renderAppearances(options))).toEqual( new Set([annotationKey(box.ref)]), ); } ); test('every mode and state an annotation stores comes back, labelled', async () =>{ const{ box, square} = await annotations(); const labels = labelsOf((await render()).appearances); expect(labels.get(annotationKey(box.ref))).toEqual([ 'down:Off', 'down:Yes', 'normal:Off', 'normal:Yes', 'rollover:Yes', ]); expect(labels.get(annotationKey(square.ref))).toEqual(['normal:-']); } ); test('each picture draws its own state, whatever the check box shows', async () =>{ const{ box} = await annotations(); const expected: Record ={ 'normal:Yes': RED, 'normal:Off': GREEN, 'down:Yes': BLUE, 'down:Off': YELLOW, 'rollover:Yes': BLACK, } ; const pictures = (await render()).appearances.filter( (appearance) => annotationKey(appearance.ref) === annotationKey(box.ref), ); for (const picture of pictures){ const raster = await decode(picture.image); const middle = pixel(raster, raster.width >> 1, raster.height >> 1).slice(0, 3); expect([`${ picture.mode} :${ picture.state} `, middle]).toEqual([ `${ picture.mode} :${ picture.state} `, expected[`${ picture.mode} :${ picture.state} `], ]); } } ); test('appearanceState names the state an annotation shows', async () =>{ const{ box, square} = await annotations(); expect(box.appearanceState).toBe('Off'); expect(square.appearanceState).toBeNull(); } ); test('modes asks for some modes only; every mode is the same as none', async () =>{ const{ box, square} = await annotations(); const normal = labelsOf((await render(['normal'])).appearances); expect(normal.get(annotationKey(box.ref))).toEqual(['normal:Off', 'normal:Yes']); expect(normal.get(annotationKey(square.ref))).toEqual(['normal:-']); const every = labelsOf((await render(['down', 'normal', 'rollover'])).appearances); expect(every).toEqual(labelsOf((await render()).appearances)); } ); test('an empty modes list is refused', async () =>{ const options ={ format: 'png' as const, modes: []} ; await expect(page.annotations.renderAppearances(options)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); await expect(page.forms.renderAppearances(options)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } ); test('a page picture draws its annotations and its form fields, each without the other', async () =>{ const middleOf = async (options:{ includeAnnotations?: boolean; includeFormFields?: boolean; } ) =>{ const raster = await decode( await page.render.image({ format: 'png', viewport:{ kind: 'scale', scale: 1} , ...options, } ), ); return{ box: pixel(raster, 40, 160).slice(0, 3), square: pixel(raster, 120, 160).slice(0, 3), } ; } ; expect(await middleOf({ } )).toEqual({ box: GREEN, square: CYAN} ); expect(await middleOf({ includeAnnotations: true, includeFormFields: true} )).toEqual({ box: GREEN, square: CYAN, } ); expect(await middleOf({ includeFormFields: false} )).toEqual({ box: WHITE, square: CYAN} ); expect(await middleOf({ includeAnnotations: false, includeFormFields: true} )).toEqual({ box: GREEN, square: WHITE, } ); expect(await middleOf({ includeAnnotations: false} )).toEqual({ box: WHITE, square: WHITE} ); } ); } ); } runAttachmentConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runAttachmentConformance.ts): export function runAttachmentConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`attachment conformance: ${ options.label} `, () =>{ let engine: Engine; let firstPageObjectNumber: PageObjectNumber; beforeAll(async () =>{ engine = await options.makeEngine(); const probe = await openFixture(engine, options); const pages = await probe.pages.list(); firstPageObjectNumber = pages.pages[0].ref.objectNumber; await probe.close(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('attachments.list() reflects the /EmbeddedFiles name tree and is a stable read', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.attachments.list(); expect(AttachmentListSchema.safeParse(list).success).toBe(true); const items = list.attachments; expect(items.length > 0).toBe(true); items.forEach((item, position) =>{ expect(item.index).toBe(position); expect(item.ref.key.length > 0).toBe(true); expect(item.name.length > 0).toBe(true); } ); expect(new Set(items.map((i) => i.ref.key)).size).toBe(items.length); expect(await doc.attachments.list()).toEqual(list); } finally{ await doc.close(); } } ); test('attachments.download() returns the listed decoded size', async () =>{ const doc = await openFixture(engine, options); try{ const{ attachments} = await doc.attachments.list(); for (const item of attachments){ const bytes = await doc.attachments.download(item.ref); expect(bytes).toBeInstanceOf(Uint8Array); if (item.sizeBytes !== null){ expect(bytes.length).toBe(item.sizeBytes); } } } finally{ await doc.close(); } } ); test('attachments.download() rejects an unknown key', async () =>{ const doc = await openFixture(engine, options); try{ await expect( doc.attachments.download(toAttachmentRef('conformance-no-such-key.bin')), ).rejects.toBeInstanceOf(EngineError); } finally{ await doc.close(); } } ); test('a File brings its name and type, and a file without a type has none', async () =>{ const doc = await openFixture(engine, options); try{ const picked = new File([new Uint8Array([1, 2, 3])], '0-picked.csv', { type: 'text/csv'} ); const{ attachment: fromFile} = await doc.attachments.create({ data: picked} ); expect(fromFile.name).toBe('0-picked.csv'); expect(fromFile.mimeType).toBe('text/csv'); const{ attachment: untyped} = await doc.attachments.create({ data: new Uint8Array([4, 5, 6]), name: '0-untyped.bin', } ); expect(untyped.mimeType).toBe(null); const listed = (await doc.attachments.list()).attachments; expect(listed.find((item) => item.ref.key === '0-untyped.bin')?.mimeType).toBe(null); expect(listed.find((item) => item.ref.key === '0-picked.csv')?.mimeType).toBe('text/csv'); await expect(doc.attachments.create({ data: new Uint8Array([7])} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } finally{ await doc.close(); } } ); test('create() and delete() round-trip the name tree; keys survive index shifts', async () =>{ const doc = await openFixture(engine, options); try{ const{ attachments: before} = await doc.attachments.list(); const data = new Uint8Array(512); for (let i = 0; i < data.length; i++) data[i] = (i * 7 + 3) & 0xff; const createdResult = await doc.attachments.create({ data: data.buffer, name: '0-conformance.bin', mimeType: 'application/octet-stream', description: 'added by conformance', } ); expect(AttachmentCreateResultSchema.safeParse(createdResult).success).toBe(true); const created = createdResult.attachment; expect(created.ref).toEqual(toAttachmentRef('0-conformance.bin')); expect(createdResult.meta.changedRefs).toEqual([created.ref]); expect(created.name).toBe('0-conformance.bin'); expect(created.mimeType).toBe('application/octet-stream'); expect(created.description).toBe('added by conformance'); expect(created.sizeBytes).toBe(data.length); const{ attachments: after} = await doc.attachments.list(); expect(after.length).toBe(before.length + 1); for (const item of before){ const match = after.find((i) => i.ref.key === item.ref.key); expect(match !== undefined).toBe(true); } await expect( doc.attachments.create({ data, name: '0-conformance.bin'} ), ).rejects.toBeInstanceOf(EngineError); const bytes = await doc.attachments.download(created.ref); expect(bytes.length).toBe(data.length); expect(bytes.every((byte, i) => byte === data[i])).toBe(true); const removed = await doc.attachments.delete(created.ref); expect(Object.keys(removed)).toEqual(['meta']); expect(deletedAttachmentOf(removed)).toEqual(created.ref); const{ attachments: final} = await doc.attachments.list(); expect(final.map((i) => i.ref)).toEqual(before.map((i) => i.ref)); await expect(doc.attachments.delete(created.ref)).rejects.toBeInstanceOf(EngineError); } finally{ await doc.close(); } } ); test('a file-attachment annotation takes a File as it is, and never guesses a type', async () =>{ const doc = await openFixture(engine, options); try{ const annotations = doc.page(toPageRef(firstPageObjectNumber)).annotations; const rect ={ x: 80, y: 40, width: 20, height: 20} ; const picked = new File([new Uint8Array([1, 2, 3])], 'figures.csv', { type: 'text/csv'} ); const{ annotation: fromFile} = await annotations.create({ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y)} , { resources:{ file: picked} } , ); const file = (fromFile as FileAttachmentAnnotation).file!; expect(file.name).toBe('figures.csv'); expect(file.mimeType).toBe('text/csv'); const{ annotation: untyped} = await annotations.create({ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y), file:{ name: 'raw.bin'} , } , { resources:{ file: new Uint8Array([4, 5])} } , ); expect((untyped as FileAttachmentAnnotation).file!.mimeType).toBe(null); await expect( annotations.create({ subtype: 'file-attachment', rect: iconRect(rect.x, rect.y)} , { resources:{ file: new Uint8Array([6])} } , ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'file.name'} , } ); } finally{ await doc.close(); } } ); test('a created file-attachment annotation round-trips its file as its file resource', async () =>{ const doc = await openFixture(engine, options); try{ const annotations = doc.page(toPageRef(firstPageObjectNumber)).annotations; const data = new Uint8Array(2048); for (let i = 0; i < data.length; i++) data[i] = (i * 31 + 7) & 0xff; const{ annotation: created} = await annotations.create({ subtype: 'file-attachment', rect: iconRect(40, 60), file:{ name: 'conformance.bin', mimeType: 'application/octet-stream', description: 'attachment conformance payload', } , icon: 'paperclip', color: '#dc2626', contents: 'conformance attachment', } , { resources:{ file: data} } , ); const dto = created as FileAttachmentAnnotation; expect(dto.subtype).toBe('file-attachment'); expect(dto.icon).toBe('paperclip'); expect(dto.color).toEqual('#dc2626'); const file = dto.file!; expect(file.name).toBe('conformance.bin'); expect(file.mimeType).toBe('application/octet-stream'); expect(file.description).toBe('attachment conformance payload'); expect(file.sizeBytes).toBe(data.length); const bytes = await annotations.downloadResource(dto.ref, 'file'); expect(bytes.length).toBe(data.length); expect(Array.from(bytes.slice(0, 16))).toEqual(Array.from(data.slice(0, 16))); expect(bytes.every((byte, i) => byte === data[i])).toBe(true); const{ nm: _name, ...unnamed} = dto; const{ annotation: copy} = await annotations.create(unnamed, { resources:{ file: bytes} , } ); expect((copy as FileAttachmentAnnotation).file).toMatchObject({ name: 'conformance.bin', mimeType: 'application/octet-stream', description: 'attachment conformance payload', sizeBytes: data.length, } ); const{ annotation: updated} = await annotations.update(dto.ref, { ...dto, contents: 'changed', } ); expect((updated as FileAttachmentAnnotation).file?.name).toBe('conformance.bin'); expect(updated.contents).toBe('changed'); } finally{ await doc.close(); } } ); test('a created text annotation round-trips icon, color, and contents', async () =>{ const doc = await openFixture(engine, options); try{ const annotations = doc.page(toPageRef(firstPageObjectNumber)).annotations; const{ annotation: created} = await annotations.create({ subtype: 'text', rect: iconRect(100, 120), icon: 'comment', color: '#facc15', contents: 'conformance note', } ); const dto = created as TextAnnotation; expect(dto.subtype).toBe('text'); expect(dto.icon).toBe('comment'); expect(dto.color).toEqual('#facc15'); expect(dto.contents).toBe('conformance note'); const{ annotation: updated} = await annotations.update(dto.ref, { subtype: 'text', icon: 'help', } ); expect((updated as TextAnnotation).icon).toBe('help'); } finally{ await doc.close(); } } ); } ); async function openFixture(engine: Engine, options: ConformanceOptions): Promise{ if (options.openKind === 'bytes'){ return engine.open({ kind: 'bytes', id: options.fixture.id, bytes: await options.fixture.bytes(), } , EVERY_PERMISSION, ); } return engine.open({ kind: 'id', id: options.fixture.cloudId ?? options.fixture.id} ); } } runChangeConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runChangeConformance.ts): export function runChangeConformance( runner: ConformanceTestRunner, options: ChangeConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`change conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDocument = async (body: (doc: DocumentHandle) => Promise, pdf?: Uint8Array) =>{ const doc = await options.open(engine, pdf); try{ await body(doc); } finally{ await doc.close(); } } ; const take = async (doc: DocumentHandle, count: number): Promise =>{ await doc.objectNumbers.reserve(count); return Array.from({ length: count} , () => doc.objectNumbers.take()!); } ; const factsOf = async (doc: DocumentHandle) =>{ const pages = await doc.pages.list(); const [annotations, form, metadata, custom, outline, attachments] = await Promise.all([ Promise.all(pages.pages.map((page) => doc.page(page.ref).annotations.list())), doc.forms.list(), doc.metadata.get(), doc.metadata.custom.get(), doc.outline.get(), doc.attachments.list(), ]); return{ pages, annotations: annotations.map((list) => list.annotations), fields: form.fields, widgets: form.widgets, calculationOrder: form.calculationOrder, metadata:{ title: metadata.title, subject: metadata.subject} , custom, outline, attachments: attachments.attachments, } ; } ; const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); const colorOf = async (doc: DocumentHandle, ref: AnnotationRef) =>{ const{ annotations} = await doc.page(PAGE).annotations.list(); const found = annotations.find( (annotation) => annotation.ref.kind === 'objectNumber' && ref.kind === 'objectNumber' && annotation.ref.objectNumber === ref.objectNumber, ); return found && 'color' in found ? found.color : undefined; } ; const nmOf = async (doc: DocumentHandle, ref: AnnotationRef) =>{ const{ annotations} = await doc.page(ref.page).annotations.list(); return annotations.find((annotation) => annotationKey(annotation.ref) === annotationKey(ref)) ?.nm; } ; const recordEvents = (doc: DocumentHandle) =>{ const events: DocumentEvent[] = []; const stop = doc.events.subscribe((event) => events.push(event)); return{ events, stop} ; } ; const txOf = (event: DocumentEvent) => 'origin' in event ? event.origin.transaction : undefined; const itemOfType = ( result: ChangeResult, type: T, ): Extract | SkippedChangeItem =>{ const item = result.items.find((candidate) => isSkippedItem(candidate) ? candidate.op === type : candidate.type === type, ); if (!item) throw new Error(`no ${ type} item`); return item as Extract | SkippedChangeItem; } ; const appliedOfType = ( result: ChangeResult, type: T, ): Extract =>{ const item = itemOfType(result, type); if (isSkippedItem(item)) throw new Error(`${ type} was left alone`); return item as Extract; } ; for (const [type, trip] of Object.entries(ROUND_TRIPS) as [ChangeOp['type'], RoundTrip][]){ test(`${ type} : undo gives the state before, the undo's undo the state after`, async () =>{ await withDocument(async (doc) =>{ const numbers = await take(doc, 4); if (trip.setup) await doc.apply({ ops: trip.setup(numbers)} ); const before = await factsOf(doc); const applied = await doc.apply({ ops: trip.ops(numbers)} ); expect(applied.meta.undoable).toBe(true); expect(applied.items.map((item) => item.type)).toEqual([type]); const after = await factsOf(doc); expect(same(after, before)).toBe(false); const undo = await doc.apply({ undoOf: applied.meta.opId} ); expect(undo.meta.undoable).toBe(true); expect(undo.items.some((item) => isSkippedItem(item) || 'skipped' in item)).toBe(false); expect(await factsOf(doc)).toEqual(before); await doc.apply({ undoOf: undo.meta.opId} ); expect(await factsOf(doc)).toEqual(after); } ); } ); } test('ops apply in order as one write; a later op names an earlier create', async () =>{ await withDocument(async (doc) =>{ const [square] = await take(doc, 1); const recorded = recordEvents(doc); const result = await doc.apply({ ops: [{ type: 'annotations.create', page: EMPTY_PAGE, data:{ subtype: 'square', box: box(20)} , objectNumber: square, } , { type: 'annotations.update', ref: at(square!, EMPTY_PAGE), patch:{ color: '#e11d48'} , } , { type: 'forms.setValue', field: NAME, value:{ value: 'Bea'} } , ], } , { opId: 'change-conformance-order'} , ); recorded.stop(); expect(result.meta.opId).toBe('change-conformance-order'); expect(result.meta.undoable).toBe(true); expect(result.items.map((item) => item.type)).toEqual([ 'annotations.create', 'annotations.update', 'forms.setValue', ]); const update = appliedOfType(result, 'annotations.update'); expect(update.annotation.ref).toEqual(at(square!, EMPTY_PAGE)); expect('color' in update.annotation && update.annotation.color).toBe('#e11d48'); expect(recorded.events.map((event) => event.type)).toEqual([ 'annotations.created', 'annotations.updated', 'forms.valueSet', ]); expect(recorded.events.map(txOf)).toEqual([{ id: 'change-conformance-order', index: 0, count: 3} , { id: 'change-conformance-order', index: 1, count: 3} , { id: 'change-conformance-order', index: 2, count: 3} , ]); } ); } ); test('a reply can answer a note created earlier in the same change', async () =>{ await withDocument(async (doc) =>{ const [note, reply] = await take(doc, 2); const result = await doc.apply({ ops: [{ type: 'annotations.create', page: EMPTY_PAGE, data:{ subtype: 'text', rect: box(20), contents: 'Question'} , objectNumber: note, } , { type: 'annotations.create', page: EMPTY_PAGE, data:{ subtype: 'text', rect: box(20), contents: 'Answer', reply:{ to: at(note!, EMPTY_PAGE)} , } , objectNumber: reply, } , ], } ); const created = result.items.filter((item) => item.type === 'annotations.create'); const answer = created[1]; if (!answer || isSkippedItem(answer) || answer.type !== 'annotations.create'){ throw new Error('expected a create'); } expect(answer.annotation.reply?.to).toEqual(at(note!, EMPTY_PAGE)); } ); } ); test('a failing op leaves nothing: no write, no events', async () =>{ await withDocument(async (doc) =>{ const [square] = await take(doc, 1); const before = await factsOf(doc); const recorded = recordEvents(doc); await expect( doc.apply({ ops: [{ type: 'annotations.create', page: PAGE, data:{ subtype: 'square', box: box(20)} , objectNumber: square, } , { type: 'annotations.update', ref: at(4000), patch:{ color: '#e11d48'} } , ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.NotFound} ); recorded.stop(); expect(recorded.events).toHaveLength(0); expect(await factsOf(doc)).toEqual(before); } ); } ); test('an empty change writes nothing and is not undoable', async () =>{ await withDocument(async (doc) =>{ const recorded = recordEvents(doc); const result = await doc.apply({ ops: []} ); recorded.stop(); expect(result.items).toEqual([]); expect(result.meta.undoable).toBe(false); expect(recorded.events).toHaveLength(0); } ); } ); test('two writes to one field undo in reverse order, back to the first value', async () =>{ await withDocument(async (doc) =>{ const [square] = await take(doc, 1); const before = await factsOf(doc); const result = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#00ff00'} } , { type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#ffff00'} } , { type: 'annotations.create', page: PAGE, data:{ subtype: 'square', box: box(140)} , objectNumber: square, } , { type: 'annotations.update', ref: at(square!), patch:{ color: '#e11d48'} } , ], } ); await doc.apply({ undoOf: result.meta.opId} ); expect(await factsOf(doc)).toEqual(before); } ); } ); test("undo leaves a colleague's later change alone and reports it", async () =>{ await withDocument(async (doc) =>{ const mine = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48', contents: 'Mine'} , } , ], } ); await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#00ff00'} } ], } ); const undo = await doc.apply({ undoOf: mine.meta.opId} ); const update = appliedOfType(undo, 'annotations.update'); expect(update.skipped).toEqual(['color']); expect(await colorOf(doc, FILE_SQUARE)).toBe('#00ff00'); const{ annotations} = await doc.page(PAGE).annotations.list(); const square = annotations.find( (annotation) => annotation.ref.kind === 'objectNumber' && annotation.ref.objectNumber === 5, )!; expect(square.contents).toBe(null); } ); } ); test('undo goes by value: a field set back to what the change set is undone', async () =>{ await withDocument(async (doc) =>{ const mine = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } ], } ); await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: BLUE} } ], } ); await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } ], } ); const undo = await doc.apply({ undoOf: mine.meta.opId} ); expect(appliedOfType(undo, 'annotations.update').skipped).toBe(undefined); expect(await colorOf(doc, FILE_SQUARE)).toBe(BLUE); } ); } ); test('a new name is checked against the page as the ops before it left it', async () =>{ await withDocument(async (doc) =>{ await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ nm: 'a'} } , { type: 'annotations.update', ref: FILE_NOTE, patch:{ nm: 'b'} } , ], } ); const before = await factsOf(doc); await expect( doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ nm: 'b'} } , { type: 'annotations.update', ref: FILE_NOTE, patch:{ nm: 'a'} } , ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(await factsOf(doc)).toEqual(before); await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ nm: 'free'} } , { type: 'annotations.update', ref: FILE_NOTE, patch:{ nm: 'a'} } , { type: 'annotations.update', ref: FILE_SQUARE, patch:{ nm: 'b'} } , ], } ); expect(await nmOf(doc, FILE_SQUARE)).toBe('b'); expect(await nmOf(doc, FILE_NOTE)).toBe('a'); } ); } ); test('undo puts back the name a rename replaced, even one another annotation took since', async () =>{ for (const squareWrittenSince of [false, true]){ await withDocument(async (doc) =>{ await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ nm: 'x'} } ], } ); const mine = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ nm: 'y'} } ], } ); await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_NOTE, patch:{ nm: 'x'} } , ...(squareWrittenSince ? [{ type: 'annotations.update' as const, ref: FILE_SQUARE, patch:{ contents: 'Theirs'} , } , ] : []), ], } ); const undo = await doc.apply({ undoOf: mine.meta.opId} ); expect(appliedOfType(undo, 'annotations.update').skipped).toBe(undefined); expect(await nmOf(doc, FILE_SQUARE)).toBe('x'); expect(await nmOf(doc, FILE_NOTE)).toBe('x'); } ); } } ); test('names missing or shared on a page are set in place; another page is no conflict', async () =>{ await withDocument(async (doc) =>{ const result = await doc.apply({ ops: [{ type: 'annotations.update', ref: UNNAMED, patch:{ nm: 'repaired-missing'} } , { type: 'annotations.update', ref: OTHER_DUP, patch:{ nm: 'elsewhere'} } , ], } ); expect(result.items.map((item) => item.type)).toEqual([ 'annotations.update', 'annotations.update', ]); expect(await nmOf(doc, UNNAMED)).toBe('repaired-missing'); expect(await nmOf(doc, OTHER_DUP)).toBe('elsewhere'); expect(await nmOf(doc, DUP)).toBe('dup'); } , NAMES_FIXTURE_PDF); } ); test('a name another annotation on the page has is refused, and the change writes nothing', async () =>{ await withDocument(async (doc) =>{ const before = await factsOf(doc); await expect( doc.apply({ ops: [{ type: 'annotations.update', ref: OTHER_DUP, patch:{ nm: 'free'} } , { type: 'annotations.update', ref: UNNAMED, patch:{ nm: 'dup'} } , ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(await factsOf(doc)).toEqual(before); } , NAMES_FIXTURE_PDF); } ); test('a rename writes /NM on the same object: its reply, appearance and other keys stay', async () =>{ await withDocument(async (doc) =>{ const result = await doc.apply({ ops: [{ type: 'annotations.update', ref: DUP, patch:{ nm: 'repaired'} } ], } ); const update = appliedOfType(result, 'annotations.update'); expect(update.annotation.ref).toEqual(DUP); expect(update.annotation.nm).toBe('repaired'); expect(update.appearance.changed).toBe(false); const{ annotations} = await doc.page(PAGE).annotations.list(); const reply = annotations.find( (annotation) => annotationKey(annotation.ref) === annotationKey(DUP_REPLY), ); expect(reply?.reply?.to).toEqual(DUP); const square = objectIn(latin1(await doc.download()), 6) ?? ''; expect(square).toContain('/OC 11 0 R'); expect(square).toContain('/AP'); expect(square).toContain('/EPDFTest_Kept'); } , NAMES_FIXTURE_PDF); } ); test('a name sent back as it reads is no change, even a shared one; null removes it', async () =>{ await withDocument(async (doc) =>{ await doc.apply({ ops: [{ type: 'annotations.update', ref: DUP, patch:{ nm: 'dup', contents: 'Checked'} } , { type: 'annotations.update', ref: OTHER_DUP, patch:{ nm: null} } , ], } ); expect(await nmOf(doc, DUP)).toBe('dup'); expect(await nmOf(doc, OTHER_DUP)).toBe(null); } , NAMES_FIXTURE_PDF); } ); test('the undo of a repaired name brings the shared name back', async () =>{ await withDocument(async (doc) =>{ const before = await factsOf(doc); const repair = await doc.apply({ ops: [{ type: 'annotations.update', ref: OTHER_DUP, patch:{ nm: 'repaired'} } ], } ); await doc.apply({ undoOf: repair.meta.opId} ); expect(await factsOf(doc)).toEqual(before); expect(await nmOf(doc, OTHER_DUP)).toBe('dup'); } , NAMES_FIXTURE_PDF); } ); test("undo of a field's properties puts back each one still holding what it set", async () =>{ await withDocument(async (doc) =>{ const mine = await doc.apply({ ops: [{ type: 'forms.update', field: NAME, patch:{ required: true, noExport: true} } ], } ); await doc.apply({ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Bea'} } ], } ); await doc.apply({ ops: [{ type: 'forms.update', field: NAME, patch:{ noExport: false} } ], } ); const undo = await doc.apply({ undoOf: mine.meta.opId} ); expect(appliedOfType(undo, 'forms.update').skipped).toEqual(['noExport']); const undone = await doc.forms.get(NAME); expect(undone.required).toBe(false); expect(undone.noExport).toBe(false); expect(undone.kind === 'text' && undone.value).toBe('Bea'); await doc.apply({ undoOf: undo.meta.opId} ); const redone = await doc.forms.get(NAME); expect(redone.required).toBe(true); expect(redone.noExport).toBe(false); expect(redone.kind === 'text' && redone.value).toBe('Bea'); } ); } ); test('expect refuses the whole change with ChangeConflict', async () =>{ await withDocument(async (doc) =>{ const before = await factsOf(doc); await expect( doc.apply({ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Bea'} } , { type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} , expect:{ color: '#ff0000'} , } , ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.ChangeConflict, details:{ opIndex: 1, fields: ['color']} , } ); expect(await factsOf(doc)).toEqual(before); } ); } ); test('the undo of a create is skipped when someone replied to it', async () =>{ await withDocument(async (doc) =>{ const [note, reply] = await take(doc, 2); const mine = await doc.apply({ ops: [{ type: 'annotations.create', page: EMPTY_PAGE, data:{ subtype: 'text', rect: box(20), contents: 'Question'} , objectNumber: note, } , ], } ); await doc.apply({ ops: [{ type: 'annotations.create', page: EMPTY_PAGE, data:{ subtype: 'text', rect: box(20), contents: 'Answer', reply:{ to: at(note!, EMPTY_PAGE)} , } , objectNumber: reply, } , ], } ); const undo = await doc.apply({ undoOf: mine.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'annotations.delete'))).toBe(true); const{ annotations} = await doc.page(EMPTY_PAGE).annotations.list(); expect(annotations).toHaveLength(2); } ); } ); test('a restore brings back the same objects with their owner, popup and reply', async () =>{ await withDocument(async (doc) =>{ const deleted = await doc.apply({ ops: [{ type: 'annotations.delete', ref: FILE_NOTE} ]} ); const recorded = recordEvents(doc); const undo = await doc.apply({ undoOf: deleted.meta.opId} ); recorded.stop(); const restore = appliedOfType(undo, 'annotations.restore'); expect(restore.annotations.map((annotation) => annotation.ref)).toEqual([ FILE_NOTE, FILE_POPUP, FILE_REPLY, ]); const [note, , reply] = restore.annotations; expect(note!.author).toBe('Ann'); expect(note!.popup).toEqual(FILE_POPUP); expect(reply!.author).toBe('Bea'); expect(reply!.reply?.to).toEqual(FILE_NOTE); const{ annotations} = await doc.page(PAGE).annotations.list(); expect(annotations.map((annotation) => annotation.ref)).toEqual([ FILE_SQUARE, FILE_NOTE, FILE_POPUP, FILE_REPLY, ]); expect(recorded.events.map((event) => event.type)).toEqual(['annotations.restored']); expect(txOf(recorded.events[0]!)).toEqual({ id: undo.meta.opId, index: 0, count: 1} ); } ); } ); test('an edited annotation from the file comes back with its edits', async () =>{ await withDocument(async (doc) =>{ await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } ], } ); const deleted = await doc.apply({ ops: [{ type: 'annotations.delete', ref: FILE_SQUARE} ], } ); await doc.apply({ undoOf: deleted.meta.opId} ); expect(await colorOf(doc, FILE_SQUARE)).toBe('#e11d48'); } ); } ); const pageOrderOf = async (doc: DocumentHandle) => (await doc.pages.list()).pages.map((page) => page.ref); const blankPage = (objectNumber: number): ChangeOp => ({ type: 'pages.insertBlank', spec:{ size:{ width: 300, height: 300} } , objectNumbers: [objectNumber], } ); test('the undo of a page insert is skipped when someone annotated the page since', async () =>{ await withDocument(async (doc) =>{ const [page, square] = await take(doc, 2); const inserted = await doc.apply({ ops: [blankPage(page!)]} ); const added = toPageRef(page!); await doc.apply({ ops: [{ type: 'annotations.create', page: added, data:{ subtype: 'square', box: box(20)} , objectNumber: square, } , ], } ); const undo = await doc.apply({ undoOf: inserted.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'pages.delete'))).toBe(true); expect(await pageOrderOf(doc)).toEqual([PAGE, EMPTY_PAGE, added]); } ); } ); test('the undo of a page insert still applies after pages moved around it', async () =>{ await withDocument(async (doc) =>{ const [page] = await take(doc, 1); const inserted = await doc.apply({ ops: [blankPage(page!)]} ); await doc.apply({ ops: [{ type: 'pages.reorder', pages: [EMPTY_PAGE], position: 'end'} ]} ); const undo = await doc.apply({ undoOf: inserted.meta.opId} ); expect(appliedOfType(undo, 'pages.delete').pages).toEqual([toPageRef(page!)]); expect(await pageOrderOf(doc)).toEqual([PAGE, EMPTY_PAGE]); } ); } ); test('the undo of a page move leaves a page someone moved since', async () =>{ await withDocument(async (doc) =>{ const moved = await doc.apply({ ops: [{ type: 'pages.reorder', pages: [EMPTY_PAGE], position: 'start'} ], } ); await doc.apply({ ops: [{ type: 'pages.reorder', pages: [EMPTY_PAGE], position: 'end'} ]} ); const undo = await doc.apply({ undoOf: moved.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'pages.reorder'))).toBe(true); expect(await pageOrderOf(doc)).toEqual([PAGE, EMPTY_PAGE]); } ); } ); test('the undo of a page rotate leaves a page someone turned since', async () =>{ await withDocument(async (doc) =>{ const turned = await doc.apply({ ops: [{ type: 'pages.rotate', pages: [PAGE, EMPTY_PAGE], rotation: 90} ], } ); await doc.apply({ ops: [{ type: 'pages.rotate', pages: [EMPTY_PAGE], rotation: 180} ]} ); const undo = await doc.apply({ undoOf: turned.meta.opId} ); expect(appliedOfType(undo, 'pages.rotate').pages).toEqual([PAGE]); const{ pages} = await doc.pages.list(); expect(pages.map((page) => page.rotation)).toEqual([0, 180]); } ); } ); test('a deleted page comes back at its place, with its name', async () =>{ await withDocument(async (doc) =>{ await doc.pages.setName({ name: 'Appendix', page: EMPTY_PAGE} ); await doc.apply({ ops: [{ type: 'pages.reorder', pages: [EMPTY_PAGE], position: 'start'} ], } ); const deleted = await doc.apply({ ops: [{ type: 'pages.delete', pages: [EMPTY_PAGE]} ]} ); expect((await doc.pages.list()).namedPages).toEqual([]); const recorded = recordEvents(doc); const undo = await doc.apply({ undoOf: deleted.meta.opId} ); recorded.stop(); expect(appliedOfType(undo, 'pages.restore').pages).toEqual([EMPTY_PAGE]); expect(await pageOrderOf(doc)).toEqual([EMPTY_PAGE, PAGE]); expect((await doc.pages.list()).namedPages).toEqual([{ name: 'Appendix', target:{ kind: 'page', page: EMPTY_PAGE} } , ]); expect(recorded.events.map((event) => event.type)).toEqual(['pages.restored']); } ); } ); test('an op meets the pages as the ops before it in the change left them', async () =>{ await withDocument(async (doc) =>{ const deleted = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } , { type: 'pages.delete', pages: [PAGE]} , ], } ); expect(deleted.items.map((item) => item.type)).toEqual([ 'annotations.update', 'pages.delete', ]); expect(await pageOrderOf(doc)).toEqual([EMPTY_PAGE]); const [page, square] = await take(doc, 2); const added = toPageRef(page!); await doc.apply({ ops: [ blankPage(page!), { type: 'annotations.create', page: added, data:{ subtype: 'square', box: box(20)} , objectNumber: square, } , ], } ); const{ annotations} = await doc.page(added).annotations.list(); expect(annotations.map((annotation) => annotation.ref)).toEqual([at(square!, added)]); } ); } ); test('the undo of a page insert applies after the page was turned and turned back', async () =>{ await withDocument(async (doc) =>{ const inserted = await doc.apply({ ops: [{ type: 'pages.insert', source: SIGNATURE_ARTWORK_PDF, position: 'end'} ], } ); const [added] = appliedOfType(inserted, 'pages.insert').insertedPages; const turned = await doc.apply({ ops: [{ type: 'pages.rotate', pages: [added!], rotation: 90} ], } ); await doc.apply({ undoOf: turned.meta.opId} ); const undo = await doc.apply({ undoOf: inserted.meta.opId} ); expect(appliedOfType(undo, 'pages.delete').pages).toEqual([added]); expect(await pageOrderOf(doc)).toEqual([PAGE, EMPTY_PAGE]); } ); } ); test('the undo of a page insert is skipped when someone turned the page since', async () =>{ await withDocument(async (doc) =>{ const inserted = await doc.apply({ ops: [{ type: 'pages.insert', source: SIGNATURE_ARTWORK_PDF, position: 'end'} ], } ); const [added] = appliedOfType(inserted, 'pages.insert').insertedPages; await doc.apply({ ops: [{ type: 'pages.rotate', pages: [added!], rotation: 90} ]} ); const undo = await doc.apply({ undoOf: inserted.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'pages.delete'))).toBe(true); expect(await pageOrderOf(doc)).toEqual([PAGE, EMPTY_PAGE, added]); } ); } ); test('a page op naming no pages is refused', async () =>{ await withDocument(async (doc) =>{ for (const op of [{ type: 'pages.rotate', pages: [], rotation: 90} , { type: 'pages.delete', pages: []} , { type: 'pages.reorder', pages: [], position: 'start'} , ] as ChangeOp[]){ await expect(doc.apply({ ops: [op]} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } expect(await pageOrderOf(doc)).toEqual([PAGE, EMPTY_PAGE]); } ); } ); test('the undo of opening an item counts the items above it again', async () =>{ await withDocument(async (doc) =>{ const [parent, child, grandchild] = await take(doc, 3); await doc.apply({ ops: [ outlineItem(parent, 'Parent'), outlineItem(child, 'Child', parent), outlineItem(grandchild, 'Grandchild', child), { type: 'outline.update', ref: toOutlineItemRef(parent!), patch:{ open: true} } , ], } ); const opened = await doc.apply({ ops: [{ type: 'outline.update', ref: toOutlineItemRef(child!), patch:{ open: true} } ], } ); expect(countIn(latin1(await doc.download()), parent!)).toBe(2); await doc.apply({ undoOf: opened.meta.opId} ); expect(countIn(latin1(await doc.download()), parent!)).toBe(1); } ); } ); test('the undo of a delete or a move that emptied an open item opens it again', async () =>{ await withDocument(async (doc) =>{ const [parent, child] = await take(doc, 2); await doc.apply({ ops: [ outlineItem(parent, 'Parent'), outlineItem(child, 'Child', parent), { type: 'outline.update', ref: toOutlineItemRef(parent!), patch:{ open: true} } , ], } ); const openOf = async (item: number) => (await doc.outline.get()).items.find((read) => read.ref.objectNumber === item)?.open; const deleted = await doc.apply({ ops: [{ type: 'outline.delete', ref: toOutlineItemRef(child!)} ], } ); expect(await openOf(parent!)).toBe(false); const undoDelete = await doc.apply({ undoOf: deleted.meta.opId} ); expect(undoDelete.items.map((item) => item.type)).toEqual([ 'outline.restore', 'outline.update', ]); expect(await openOf(parent!)).toBe(true); const moved = await doc.apply({ ops: [{ type: 'outline.move', refs: [toOutlineItemRef(child!)], parent: null, position: 'end', } , ], } ); expect(await openOf(parent!)).toBe(false); await doc.apply({ undoOf: moved.meta.opId} ); expect(await openOf(parent!)).toBe(true); } ); } ); test('the undo of an item made applies after the page it goes to was deleted', async () =>{ await withDocument(async (doc) =>{ const [item] = await take(doc, 1); const created = await doc.apply({ ops: [{ type: 'outline.create', parent: null, data:{ title: 'Appendix', target:{ kind: 'goto', destination:{ kind: 'fit', page: EMPTY_PAGE} } , } , objectNumber: item, } , ], } ); await doc.apply({ ops: [{ type: 'pages.delete', pages: [EMPTY_PAGE]} ]} ); const undo = await doc.apply({ undoOf: created.meta.opId} ); expect(appliedOfType(undo, 'outline.delete')).toBeTruthy(); expect((await doc.outline.get()).items).toEqual([]); } ); } ); test('the undo of a new target leaves it when the old one goes to a page that is gone', async () =>{ await withDocument(async (doc) =>{ const [item] = await take(doc, 1); const ref = toOutlineItemRef(item!); await doc.apply({ ops: [outlineItem(item, 'Chapter')]} ); const retargeted = await doc.apply({ ops: [{ type: 'outline.update', ref, patch:{ target:{ kind: 'goto', destination:{ kind: 'fit', page: EMPTY_PAGE} } } , } , ], } ); await doc.apply({ ops: [{ type: 'outline.update', ref, patch:{ title: 'Renamed'} } ]} ); await doc.apply({ ops: [{ type: 'pages.delete', pages: [PAGE]} ]} ); const undo = await doc.apply({ undoOf: retargeted.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'outline.update'))).toBe(true); const [read] = (await doc.outline.get()).items; expect(read?.target).toEqual({ kind: 'goto', destination:{ kind: 'fit', page: EMPTY_PAGE} , } ); } ); } ); test('no item is made under the deepest item a read shows', async () =>{ await withDocument(async (doc) =>{ const numbers = await take(doc, OUTLINE_READ_LIMITS.depth); await doc.apply({ ops: numbers.map((item, level) => outlineItem(item, `Level ${ level} `, level ? numbers[level - 1] : undefined), ), } ); const deepest = toOutlineItemRef(numbers[numbers.length - 1]!); await expect( doc.apply({ ops: [{ type: 'outline.create', parent: deepest, data:{ title: 'Deeper'} } ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const{ items} = await doc.outline.get(); expect(items).toHaveLength(OUTLINE_READ_LIMITS.depth); } ); } ); test('a deleted file comes back with its bytes, its description and its dates', async () =>{ await withDocument(async (doc) =>{ await doc.apply({ ops: [embedNotes()]} ); const [embedded] = (await doc.attachments.list()).attachments; const deleted = await doc.apply({ ops: [{ type: 'attachments.delete', ref: NOTES_REF} ], } ); expect((await doc.attachments.list()).attachments).toEqual([]); const recorded = recordEvents(doc); const undo = await doc.apply({ undoOf: deleted.meta.opId} ); recorded.stop(); expect(appliedOfType(undo, 'attachments.restore').attachment).toEqual(embedded); expect((await doc.attachments.list()).attachments).toEqual([embedded]); expect(await doc.attachments.download(NOTES_REF)).toEqual(NOTES); expect(recorded.events.map((event) => event.type)).toEqual(['attachments.restored']); } ); } ); test('the undo of a file added is skipped when someone added another under its name', async () =>{ await withDocument(async (doc) =>{ const added = await doc.apply({ ops: [embedNotes()]} ); const other = new TextEncoder().encode('Other notes.'); await doc.apply({ ops: [{ type: 'attachments.delete', ref: NOTES_REF} ]} ); await doc.apply({ ops: [embedNotes(other)]} ); const undo = await doc.apply({ undoOf: added.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'attachments.delete'))).toBe(true); expect(await doc.attachments.download(NOTES_REF)).toEqual(other); } ); } ); test('the undo of a file removed is skipped when another file has its name', async () =>{ await withDocument(async (doc) =>{ await doc.apply({ ops: [embedNotes()]} ); const deleted = await doc.apply({ ops: [{ type: 'attachments.delete', ref: NOTES_REF} ], } ); const other = new TextEncoder().encode('Other notes.'); await doc.apply({ ops: [embedNotes(other)]} ); const undo = await doc.apply({ undoOf: deleted.meta.opId} ); expect(isSkippedItem(itemOfType(undo, 'attachments.restore'))).toBe(true); expect((await doc.attachments.list()).attachments).toHaveLength(1); expect(await doc.attachments.download(NOTES_REF)).toEqual(other); } ); } ); test('a file whose name another file has is refused, and the change writes nothing', async () =>{ await withDocument(async (doc) =>{ await doc.apply({ ops: [embedNotes()]} ); const before = await factsOf(doc); await expect( doc.apply({ ops: [{ type: 'metadata.update', patch:{ title: 'Changed'} } , embedNotes()], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(await factsOf(doc)).toEqual(before); } ); } ); test('undoing a change twice is harmless', async () =>{ await withDocument(async (doc) =>{ const before = await factsOf(doc); const mine = await doc.apply({ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Bea'} } ], } ); await doc.apply({ undoOf: mine.meta.opId} ); const again = await doc.apply({ undoOf: mine.meta.opId} ); expect(again.items.every(isSkippedItem)).toBe(true); expect(await factsOf(doc)).toEqual(before); } ); } ); test('only the user who made a change may undo it', async () =>{ if (!options.openAsAnotherUser) return; await withDocument(async (doc) =>{ const mine = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } ], } ); const other = await options.openAsAnotherUser!(engine, doc); try{ await expect(other.apply({ undoOf: mine.meta.opId} )).rejects.toMatchObject({ code: EngineErrorCode.Forbidden, } ); } finally{ await other.close(); } expect(await colorOf(doc, FILE_SQUARE)).toBe('#e11d48'); } ); } ); test('a redaction apply ends undo for the changes before it', async () =>{ await withDocument(async (doc) =>{ const before = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } ], } ); await doc.page(EMPTY_PAGE).annotations.create({ subtype: 'redact', rect: box(20)} ); const redaction = await doc.redaction.apply({ pages: [EMPTY_PAGE]} ); expect(redaction.meta.undoable).toBe(false); await expect(doc.apply({ undoOf: before.meta.opId} )).rejects.toMatchObject({ code: EngineErrorCode.UndoUnavailable, details:{ reason: 'final-change'} , } ); const after = await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: BLUE} } ], } ); expect(after.meta.undoable).toBe(true); } ); } ); test('a refused change asked again answers its refusal, even when it would now apply', async () =>{ await withDocument(async (doc) =>{ const refused ={ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#00ff00'} , expect:{ color: '#e11d48'} , } , ], } satisfies{ ops: ChangeOp[]} ; const options ={ opId: 'change-conformance-refused'} ; await expect(doc.apply(refused, options)).rejects.toMatchObject({ code: EngineErrorCode.ChangeConflict, } ); await doc.apply({ ops: [{ type: 'annotations.update', ref: FILE_SQUARE, patch:{ color: '#e11d48'} } ], } ); await expect(doc.apply(refused, options)).rejects.toMatchObject({ code: EngineErrorCode.ChangeConflict, } ); expect(await colorOf(doc, FILE_SQUARE)).toBe('#e11d48'); } ); } ); test('asking again answers the first result and publishes nothing new', async () =>{ await withDocument(async (doc) =>{ const change ={ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Bea'} } ], } satisfies{ ops: ChangeOp[]} ; const options ={ opId: 'change-conformance-retry'} ; const recorded = recordEvents(doc); const first = await doc.apply(change, options); const second = await doc.apply(change, options); recorded.stop(); expect(second).toEqual(first); expect(recorded.events).toHaveLength(1); } ); } ); test('a different change under a used opId is IdempotencyKeyReused', async () =>{ await withDocument(async (doc) =>{ const options ={ opId: 'change-conformance-reused'} ; await doc.apply({ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Bea'} } ]} , options, ); await expect( doc.apply({ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Cy'} } ]} , options, ), ).rejects.toMatchObject({ code: EngineErrorCode.IdempotencyKeyReused} ); } ); } ); test('a single verb is a one-op change: its opId undoes it', async () =>{ await withDocument(async (doc) =>{ const before = await factsOf(doc); const updated = await doc.page(PAGE).annotations.update(FILE_SQUARE, { color: '#e11d48'} ); expect(updated.meta.undoable).toBe(true); await doc.apply({ undoOf: updated.meta.opId} ); expect(await factsOf(doc)).toEqual(before); } ); } ); test('adding and removing a file are one-op changes: their opIds undo them', async () =>{ await withDocument(async (doc) =>{ const before = await factsOf(doc); const picked = new File([NOTES], 'notes.txt', { type: 'text/plain'} ); const created = await doc.attachments.create({ data: picked} ); expect(created.attachment.ref).toEqual(NOTES_REF); expect(created.meta.undoable).toBe(true); const withFile = await factsOf(doc); const deleted = await doc.attachments.delete(NOTES_REF); expect(deleted.meta.undoable).toBe(true); await doc.apply({ undoOf: deleted.meta.opId} ); expect(await factsOf(doc)).toEqual(withFile); await doc.apply({ undoOf: created.meta.opId} ); expect(await factsOf(doc)).toEqual(before); } ); } ); } ); } runColorConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runColorConformance.ts): export function runColorConformance( runner: ConformanceTestRunner, options: ColorConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`color conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const squareOf = async (doc: DocumentHandle) =>{ const{ pages} = await doc.pages.list(); const page = doc.page(toPageRef(pages[0]!.ref.objectNumber)); const{ annotations} = await page.annotations.list(); const square = annotations.find((a) => a.nm === 'colored'); if (!square || square.subtype !== 'square') throw new Error('no square in the fixture'); return{ page, square} ; } ; test('a gray or CMYK color reads as its sRGB value, lowercase', async () =>{ const doc = await options.open(engine); try{ const{ square} = await squareOf(doc); expect(square.color).toMatch(/^#([0-9a-f]{ 2} )\1\1$/); expect(square.interiorColor).toBe('#000000'); } finally{ await doc.close(); } } ); test('a color sent back unchanged stays as the file stores it', async () =>{ const doc = await options.open(engine); try{ const{ page, square} = await squareOf(doc); await page.annotations.update(square.ref, { ...square, color: square.color?.toUpperCase() ?? null, interiorColor: square.interiorColor?.toUpperCase() ?? null, contents: 'kept', } ); const text = new TextDecoder('latin1').decode(await doc.download()); expect(lastArray(text, 'C')).toEqual([0.5]); expect(lastArray(text, 'IC')).toEqual([0, 0, 0, 1]); const{ square: after} = await squareOf(doc); expect(after.contents).toBe('kept'); expect(after.color).toBe(square.color); } finally{ await doc.close(); } } ); test('a new color is written as given, in either case, and reads back lowercase', async () =>{ const doc = await options.open(engine); try{ const{ page, square} = await squareOf(doc); const{ annotation} = await page.annotations.update(square.ref, { color: '#1A2B3C'} ); expect(annotation.subtype === 'square' && annotation.color).toBe('#1a2b3c'); const text = new TextDecoder('latin1').decode(await doc.download()); expect(lastArray(text, 'C')).toHaveLength(3); } finally{ await doc.close(); } } ); } ); } runDateConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runDateConformance.ts): export function runDateConformance( runner: ConformanceTestRunner, options: DateConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`date conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDocument = async (run: (doc: DocumentHandle) => Promise) =>{ const doc = await options.open(engine); try{ await run(doc); } finally{ await doc.close(); } } ; const annotationsOf = async (doc: DocumentHandle) =>{ const{ annotations} = await doc.page(toPageRef(3)).annotations.list(); const byName = (nm: string): Annotation =>{ const found = annotations.find((annotation) => annotation.nm === nm); if (!found) throw new Error(`no annotation named ${ nm} `); return found; } ; return byName; } ; test('an annotation reads its dates with the offset they were written with', async () =>{ await withDocument(async (doc) =>{ const byName = await annotationsOf(doc); expect(byName('dates-offset')).toMatchObject({ createdAt: '2017-07-12T21:44:38-07:00', modifiedAt: '2017-07-13T09:15:00+05:30', } ); expect(byName('dates-local')).toMatchObject({ createdAt: '2017-07-12T21:44:38', modifiedAt: '2017-07-12T21:44:38Z', } ); expect(byName('dates-odd')).toMatchObject({ createdAt: null, modifiedAt: '2017-01-01T00:00:00', } ); } ); } ); test('a read goes back into an update through JSON, and keeps its creation date', async () =>{ await withDocument(async (doc) =>{ const page = doc.page(toPageRef(3)); const read = (await annotationsOf(doc))('dates-offset'); const before = Date.now(); const{ annotation: updated} = await page.annotations.update( read.ref, JSON.parse(JSON.stringify(read)), ); expect(updated.createdAt).toBe('2017-07-12T21:44:38-07:00'); expect(updated.modifiedAt).toMatch(/Z$/); expect(Date.parse(updated.modifiedAt!) >= Math.floor(before / 1000) * 1000).toBe(true); } ); } ); test('document metadata keeps offsets, and a write takes the string or a Date', async () =>{ await withDocument(async (doc) =>{ const read = await doc.metadata.get(); expect(read.createdAt).toBe('2017-07-12T21:44:38-07:00'); expect(read.modifiedAt).toBe('2019-02-03T04:05:06+09:00'); await doc.metadata.update({ createdAt: '2020-01-02T03:04:05+05:30'} ); expect((await doc.metadata.get()).createdAt).toBe('2020-01-02T03:04:05+05:30'); await doc.metadata.update({ modifiedAt: new Date('2021-06-07T10:09:10.500+02:00')} ); expect((await doc.metadata.get()).modifiedAt).toBe('2021-06-07T08:09:10Z'); const current = await doc.metadata.get(); const{ createdAt, modifiedAt} = JSON.parse(JSON.stringify(current)) as typeof current; await doc.metadata.update({ createdAt, modifiedAt} ); expect(await doc.metadata.get()).toMatchObject({ createdAt, modifiedAt} ); await doc.metadata.update({ createdAt: null} ); expect((await doc.metadata.get()).createdAt).toBe(null); } ); } ); test('an attached file reads the dates of its /Params', async () =>{ await withDocument(async (doc) =>{ const file = (await annotationsOf(doc))('dates-file') as Annotation &{ file:{ createdAt?: string; modifiedAt?: string} | null; } ; expect(file.file).toMatchObject({ createdAt: '2017-07-12T21:44:38-07:00', modifiedAt: '2018-01-01T12:00:00+01:00', } ); const [embedded] = (await doc.attachments.list()).attachments; expect(embedded).toMatchObject({ name: 'a.txt', createdAt: '2017-07-12T21:44:38-07:00', modifiedAt: '2018-01-01T12:00:00+01:00', } ); } ); } ); } ); } runDocumentEventsConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runDocumentEventsConformance.ts): export function runDocumentEventsConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`document events conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('every confirmed mutation publishes exactly one event, results verbatim', async () =>{ const doc = await openFixture(engine, options); try{ const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const list = await doc.pages.list(); if (list.pages.length < 3) return; const pageObjectNumber = list.pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); const draft: HighlightDraft ={ subtype: 'highlight', contents: 'events conformance', quadPoints: QUAD, } ; const created = await page.annotations.create(draft); const updated = await page.annotations.update(created.annotation.ref, { subtype: 'highlight', contents: 'updated', } ); const rotated = await doc.pages.rotate([toPageRef(pageObjectNumber)], 90); const victim = list.pages[2].ref.objectNumber; const deleted = await doc.pages.delete([toPageRef(victim)]); const meta = await doc.metadata.update({ title: 'events conformance'} ); const custom = await doc.metadata.custom.update({ EventsConformance: 'yes'} ); expect(events.map((event) => event.type)).toEqual([ 'annotations.created', 'annotations.updated', 'pages.rotated', 'pages.deleted', 'metadata.updated', 'metadata.customUpdated', ]); const [evCreated, evUpdated, evRotated, evDeleted, evMeta, evCustom] = events; if (evCreated.type === 'annotations.created'){ expect(evCreated.page).toEqual(toPageRef(pageObjectNumber)); expect(evCreated.annotation).toEqual(created.annotation); expect(evCreated.meta).toEqual(created.meta); } if (evUpdated.type === 'annotations.updated'){ expect(evUpdated.annotation).toEqual(updated.annotation); } if (evRotated.type === 'pages.rotated'){ expect(evRotated.pages).toEqual([toPageRef(pageObjectNumber)]); expect(evRotated.rotation).toBe(90); expect(evRotated.layout).toEqual(rotated.layout); expect(evRotated.meta).toEqual(rotated.meta); } if (evDeleted.type === 'pages.deleted'){ expect(evDeleted.pages).toEqual([toPageRef(victim)]); expect(evDeleted.layout).toEqual(deleted.layout); } if (evMeta.type === 'metadata.updated'){ expect(evMeta.metadata).toEqual(meta.metadata); } if (evCustom.type === 'metadata.customUpdated'){ expect(evCustom.custom).toEqual(custom.custom); expect(evCustom.meta).toEqual(custom.meta); } const first = events[0]; expect(first !== undefined && 'origin' in first).toBe(true); if (first === undefined || !('origin' in first)) return; for (const event of events){ expect('origin' in event).toBe(true); if (!('origin' in event)) continue; expect(event.origin.kind).toBe('local'); expect(typeof event.origin.sessionId).toBe('string'); expect(event.origin.sessionId.length > 0).toBe(true); expect(event.origin.sessionId).toBe(first.origin.sessionId); expect(Number.isNaN(Date.parse(event.origin.at))).toBe(false); } } finally{ await doc.close(); } } ); test('pages.inserted rides verbatim', async () =>{ const doc = await openFixture(engine, options); try{ const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const inserted = await doc.pages.insertBlank({ size:{ width: 396, height: 612} } , 'start', ); expect(events.map((event) => event.type)).toEqual(['pages.inserted']); const [evInserted] = events; if (evInserted.type === 'pages.inserted'){ expect(evInserted.insertedPages).toEqual(inserted.insertedPages); expect(evInserted.layout).toEqual(inserted.layout); expect(evInserted.meta).toEqual(inserted.meta); expect(evInserted.origin.kind).toBe('local'); } } finally{ await doc.close(); } } ); test('a FAILED mutation publishes nothing (events are ground truth)', async () =>{ const doc = await openFixture(engine, options); try{ const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const list = await doc.pages.list(); let caught: unknown; try{ await doc.pages.delete(list.pages.map((p) => p.ref)); } catch (err){ caught = err; } expect(caught !== undefined).toBe(true); expect(events.length).toBe(0); } finally{ await doc.close(); } } ); test('own mutations are published before their promise settles', async () =>{ const doc = await openFixture(engine, options); try{ const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const seenAtSettlement: number[] = []; await doc.metadata .update({ title: 'published before settlement'} ) .then(() => seenAtSettlement.push(events.length)); const list = await doc.pages.list(); await doc .page(list.pages[0].ref) .annotations.create({ subtype: 'highlight', contents: 'ordering', quadPoints: QUAD} ) .then(() => seenAtSettlement.push(events.length)); expect(seenAtSettlement).toEqual([1, 2]); } finally{ await doc.close(); } } ); test('on(type) hears only that type, typed by it; its unsubscriber stops it', async () =>{ const doc = await openFixture(engine, options); try{ const rotated: number[] = []; const stop = doc.events.on('pages.rotated', (event) => rotated.push(event.rotation)); const list = await doc.pages.list(); await doc.metadata.update({ title: 'on(type)'} ); await doc.pages.rotate([list.pages[0].ref], 90); expect(rotated).toEqual([90]); stop(); await doc.pages.rotate([list.pages[0].ref], 180); expect(rotated).toEqual([90]); } finally{ await doc.close(); } } ); test('unsubscribe stops delivery', async () =>{ const doc = await openFixture(engine, options); try{ const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) => events.push(event)); unsubscribe(); const list = await doc.pages.list(); await doc.pages.rotate([list.pages[0].ref], 180); expect(events.length).toBe(0); } finally{ await doc.close(); } } ); } ); } runDocumentFontsConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runDocumentFontsConformance.ts): export function runDocumentFontsConformance( runner: ConformanceTestRunner, options: DocumentFontsConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const{ servedFont, fixtures} = options; describe(`doc.fonts conformance: ${ options.label} `, () =>{ let engine: Engine | undefined; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ await engine?.destroy(); engine = undefined; } ); const open = (bytes: Uint8Array) => options.open(engine!, bytes.slice()); const firstPage = async (doc: DocumentHandle) => (await doc.pages.list()).pages[0]!.ref; async function fieldIn(doc: DocumentHandle, fontFamily: string, value: string, name: string){ const page = await firstPage(doc); const{ field} = await doc.forms.create({ kind: 'text', name, widgets: [{ page, rect:{ x: 40, y: 40, width: 200, height: 24} , fontFamily} ], } ); await doc.forms.setValue(field.ref, { value} ); return field; } test('lists the 14 standard fonts, then the engine’s with its fallbacks, and the last resort apart', async () =>{ const doc = await open(fixtures.page); const list = await doc.fonts.list(); expect(list.fonts.slice(0, 14).map((font) => font.source)).toEqual( Array(14).fill('standard'), ); const helvetica = fontNamed(list.fonts, 'helvetica')!; expect(helvetica).toMatchObject({ builtIn: true, canChoose: true, restrictions: [], familyName: 'Helvetica', } ); expect(helvetica.programs[0]!.displaySha256).toMatch(HEX_SHA256); const served = fontNamed(list.fonts, servedFont.key)!; expect(served).toMatchObject({ source: 'engine', builtIn: false, canChoose: true, restrictions: [], } ); expect(served.programs[0]).toMatchObject({ displaySha256: servedFont.sha256, sourceSha256: servedFont.sha256, format: 'truetype', canDownload: true, } ); expect(list.fallbacks[0]).toBe(servedFont.key); for (const key of list.fallbacks){ expect(fontNamed(list.fonts, key)?.source).toBe('engine'); } expect(list.lastResort).toMatchObject({ canDownload: true, embedded: 'none'} ); expect(list.lastResort.displaySha256).toMatch(HEX_SHA256); await doc.close(); } ); test('resolve says which program draws each run, and the characters no font has', async () =>{ const doc = await open(fixtures.page); const list = await doc.fonts.list(); const answer = await doc.fonts.resolve({ runs: [{ text: 'Hi 中', fontFamily: 'helvetica'} , { text: 'X', family: 'NoSuchFamily', weight: 700, italic: false} , ], } ); expect(answer.runs[0]).toMatchObject({ font: 'helvetica', program: fontNamed(list.fonts, 'helvetica')!.programs[0]!.displaySha256, substituted: false, } ); expect(answer.runs[0]!.fallbacks[0]).toBe(servedFont.sha256); expect(answer.runs[1]).toMatchObject({ font: 'helvetica-bold', substituted: true} ); expect(answer.missingCharacters).toEqual(['中']); await doc.close(); } ); test('a write that draws a character no font has says so, as resolve for its box does', async () =>{ const doc = await open(fixtures.page); const page = await firstPage(doc); const{ meta} = await doc.page(page).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 20, width: 200, height: 40} , contents: 'Hello 中', } ); expect(meta.missingCharacters).toEqual(['中']); const plain = await doc.page(page).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 80, width: 200, height: 40} , contents: 'Hello', } ); expect(plain.meta.missingCharacters).toBe(undefined); const{ field} = await doc.forms.create({ kind: 'text', name: 'missing', widgets: [{ page, rect:{ x: 40, y: 140, width: 200, height: 24} , fontFamily: 'helvetica'} , ], } ); const widget = (await doc.forms.list()).widgets.find( (candidate) => candidate.ref.kind === 'objectNumber' && candidate.ref.objectNumber === field.widgets[0]!.objectNumber, )!; const answer = await doc.fonts.resolve({ annotation: widget.ref, runs: [{ text: 'A中B', fontFamily: 'helvetica'} ], } ); expect(answer.missingCharacters).toEqual(['中']); const filled = await doc.forms.setValue(field.ref, { value: 'A中B'} ); expect(filled.meta.missingCharacters).toEqual(answer.missingCharacters); const label = await doc.page(page).annotations.create({ subtype: 'redact', rect:{ x: 40, y: 200, width: 200, height: 40} , overlayText: 'X中', fontFamily: 'helvetica', } ); expect(label.meta.missingCharacters).toEqual(['中']); const applied = await doc.redaction.apply({ annotations: [label.annotation.ref]} ); expect(applied.meta.missingCharacters).toBe(undefined); await doc.close(); } ); test('a character no font has is drawn with the last resort, which the list keeps apart', async () =>{ const doc = await open(fixtures.page); await doc.page(await firstPage(doc)).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 20, width: 200, height: 40} , contents: 'Hello 中', } ); const saved = new TextDecoder('latin1').decode(await doc.download({ mode: 'rewrite'} )); expect(saved).toContain('/EmbedPDFLastResort-Regular'); const list = await doc.fonts.list(); expect(list.fonts.some((font) => font.familyName === 'EmbedPDF Last Resort')).toBe(false); await doc.close(); } ); test('a write that embeds a font ends its events with fonts.changed; one that doesn’t, doesn’t', async () =>{ const doc = await open(fixtures.page); const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) => events.push(event)); await doc.fonts.list(); const page = await firstPage(doc); const fontsChangedBy = (opId: string) => events.filter( (event) => event.type === 'fonts.changed' && 'transaction' in event.origin && event.origin.transaction?.id === opId, ); const square = await doc.page(page).annotations.create({ subtype: 'square', rect:{ x: 10, y: 10, width: 20, height: 20} , } ); expect(fontsChangedBy(square.meta.opId)).toHaveLength(0); const text = await doc.page(page).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 60, width: 200, height: 40} , contents: 'Hello', fontFamily: servedFont.key, } ); expect(fontsChangedBy(text.meta.opId)).toHaveLength(1); const list = await doc.fonts.list(); expect( list.fonts.some((font) => font.source === 'document' && font.familyName === 'Roboto'), ).toBe(true); unsubscribe(); await doc.close(); } ); test('a document’s whole program is listed, named, downloaded and written with', async () =>{ const doc = await open(fixtures.page); await fieldIn(doc, servedFont.key, 'hello', 'first'); const list = await doc.fonts.list(); const roboto = list.fonts.find( (font) => font.source === 'document' && font.familyName === 'Roboto', )!; expect(roboto).toMatchObject({ canChoose: true, restrictions: [], weight: 400} ); expect(roboto.name).toBe(roboto.postScriptName); const program = roboto.programs[0]!; expect(program).toMatchObject({ embedded: 'whole', format: 'truetype', canDownload: true} ); expect(program.displaySha256).toBe(servedFont.sha256); expect(await sha256(await doc.fonts.downloadProgram(program.displaySha256!))).toBe( program.displaySha256, ); const info = await doc.fonts.getProgram(program.displaySha256!); expect(covers(info.covers, 'A')).toBe(true); expect(info.ascent > 500 && info.descent < 0).toBe(true); const field = await fieldIn(doc, roboto.name, 'Ωmega', 'second'); const form = await doc.forms.list(); const widgetNumber = form.fields.find((candidate) => candidate.name === field.name)! .widgets[0]!.objectNumber; const widget = form.widgets.find( (candidate) => candidate.ref.kind === 'objectNumber' && candidate.ref.objectNumber === widgetNumber, )!; const readBack = fontNamed(list.fonts, widget.fontFamily!); expect(readBack?.programs[0]?.displaySha256).toBe(program.displaySha256); await doc.close(); } ); test('one program two dictionaries read differently is two display programs, each served by its hash', async () =>{ const doc = await open(fixtures.sharedProgram); const font = (await doc.fonts.list()).fonts.find( (candidate) => candidate.source === 'document' && candidate.name === 'FoxitFixed', )!; expect(font.programs).toHaveLength(2); expect(new Set(font.programs.map((program) => program.sourceSha256)).size).toBe(1); const hashes = font.programs.map((program) => program.displaySha256!); expect(new Set(hashes).size).toBe(2); for (const hash of hashes){ expect(await sha256(await doc.fonts.downloadProgram(hash))).toBe(hash); const info = await doc.fonts.getProgram(hash); expect(covers(info.covers, 'A')).toBe(true); } await doc.close(); } ); test('a field in a program two dictionaries read differently resolves to the one its own reads', async () =>{ const doc = await open(fixtures.sharedProgram); const{ widgets} = await doc.forms.list(); const programs: (string | null)[] = []; for (const [index, width] of [600, 900].entries()){ const widget = widgets[index]!; expect(widget.fontFamily).toBe('FoxitFixed'); const answer = await doc.fonts.resolve({ annotation: widget.ref!, runs: [{ text: 'HELLO', fontFamily: widget.fontFamily!} ], } ); const run = answer.runs[0]!; expect(run).toMatchObject({ font: 'FoxitFixed', substituted: false} ); const advances = advancesOf(await doc.fonts.downloadProgram(run.program!)); expect([600, 900].filter((advance) => advances.has(advance))).toEqual([width]); programs.push(run.program); } expect(new Set(programs).size).toBe(2); await doc.close(); } ); test('downloads the built-in programs and the served font, and refuses a hash it doesn’t name', async () =>{ const doc = await open(fixtures.page); const list = await doc.fonts.list(); const helvetica = fontNamed(list.fonts, 'helvetica')!.programs[0]!.displaySha256!; expect(await sha256(await doc.fonts.downloadProgram(helvetica))).toBe(helvetica); const lastResort = list.lastResort.displaySha256!; expect(await sha256(await doc.fonts.downloadProgram(lastResort))).toBe(lastResort); expect(await sha256(await doc.fonts.downloadProgram(servedFont.sha256))).toBe( servedFont.sha256, ); expect((await rejection(doc.fonts.downloadProgram('0'.repeat(64)))).code).toBe( EngineErrorCode.NotFound, ); const info = await doc.fonts.getProgram(helvetica); expect(covers(info.covers, 'A')).toBe(true); await doc.close(); } ); test('a program’s bytes go only to a token that may write text', async () =>{ const doc = await options.openReadOnly(engine!, fixtures.page.slice()); const list = await doc.fonts.list(); const helvetica = fontNamed(list.fonts, 'helvetica')!.programs[0]!.displaySha256!; const refused = await rejection(doc.fonts.downloadProgram(helvetica)); expect(refused.code).toBe(EngineErrorCode.Forbidden); expect((refused.details as{ anyOf?: string[]} ).anyOf).toContain('doc.annotate.modify'); await doc.close(); } ); test('a form font a browser can’t load goes to it as a display program of what the engine writes', async () =>{ const doc = await open(fixtures.keptFonts); const list = await doc.fonts.list(); for (const [name, format] of [ ['FoxitFixed', 'cff'], ['Roboto2-Regular', 'type1'], ] as const){ const font = fontNamed(list.fonts, name)!; expect(font).toMatchObject({ source: 'document', canChoose: false, restrictions: ['unsupported-format'], } ); const program = font.programs[0]!; expect(program).toMatchObject({ format, embedded: 'whole', canDownload: true} ); expect(program.displaySha256 === program.sourceSha256).toBe(false); const bytes = await doc.fonts.downloadProgram(program.displaySha256!); expect(String.fromCharCode(...bytes.slice(0, 4))).toBe('OTTO'); expect(await sha256(bytes)).toBe(program.displaySha256); } const hello = fontNamed(list.fonts, 'Roboto2-Regular')!.programs[0]!; const info = await doc.fonts.getProgram(hello.displaySha256!); expect(['H', 'E', 'L', 'O', 'W', 'R', 'D'].every((c) => covers(info.covers, c))).toBe(true); expect(covers(info.covers, ' ')).toBe(false); expect(covers(info.covers, 'A')).toBe(false); const widget = (await doc.forms.list()).widgets.find( (candidate) => candidate.fontFamily === 'Roboto2-Regular', )!; const answer = await doc.fonts.resolve({ annotation: widget.ref, runs: [{ text: 'HELLO', fontFamily: widget.fontFamily!} ], } ); expect(answer.runs[0]).toMatchObject({ font: 'Roboto2-Regular', substituted: false, program: hello.displaySha256, } ); await doc.close(); } ); test('a name that is no font fails, and a document subset can’t be chosen', async () =>{ const doc = await open(fixtures.page); const unknown = await rejection( doc.page(await firstPage(doc)).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 20, width: 200, height: 40} , contents: 'x', fontFamily: 'NoSuchFont', } ), ); expect(unknown.code).toBe(EngineErrorCode.InvalidArg); await doc.close(); const subsetDoc = await open(fixtures.documentSubset); const subset = (await subsetDoc.fonts.list()).fonts.find( (font) => font.source === 'document' && font.programs[0]?.embedded === 'subset', )!; expect(subset).toMatchObject({ canChoose: false} ); expect(subset.restrictions).toContain('subset'); const refused = await rejection( subsetDoc.page(await firstPage(subsetDoc)).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 20, width: 200, height: 40} , contents: 'x', fontFamily: subset.name, } ), ); expect(refused.code).toBe(EngineErrorCode.InvalidArg); expect((refused.details as{ restrictions?: string[]} ).restrictions).toContain('subset'); await subsetDoc.close(); } ); describe('a document font is everything the PDF draws under one name', () =>{ const documentFonts = async (doc: DocumentHandle) => (await doc.fonts.list()).fonts.filter((font) => font.source === 'document'); const namesOf = (fonts: readonly Font[]) => fonts.map((font) => font.name); const expectUnique = (fonts: readonly Font[]) => expect(new Set(namesOf(fonts)).size).toBe(fonts.length); test('copies of one font under one name are one font, however each editor described it', async () =>{ const doc = await open( pdfWithFontDictionaries(fixtures.fontProgram, [{ baseFont: 'Same-Regular', family: 'Same', weight: 400} , { baseFont: 'Same-Regular', family: 'Same', weight: 400} , { baseFont: 'ArialMT', family: 'Arial', weight: 400} , { baseFont: 'ArialMT'} , { baseFont: 'Grotesk-SemiBold', family: 'Grotesk', weight: 600} , { baseFont: 'Grotesk-SemiBold'} , { baseFont: 'Grotesk-Thin', family: 'Grotesk', weight: 100} , { baseFont: 'Grotesk-Thin'} , ]), ); const fonts = await documentFonts(doc); expectUnique(fonts); expect(namesOf(fonts).sort()).toEqual([ 'ArialMT', 'Grotesk-SemiBold', 'Grotesk-Thin', 'Same-Regular', ]); for (const font of fonts){ expect(font.programs).toHaveLength(2); expect(font).toMatchObject({ canChoose: true, restrictions: []} ); } await doc.close(); } ); async function boxIn(doc: DocumentHandle, fontFamily: string){ const page = await firstPage(doc); const{ meta} = await doc.page(page).annotations.create({ subtype: 'free-text', box:{ x: 20, y: 20, width: 200, height: 40} , contents: 'שלום', fontFamily, } ); const{ annotations} = await doc.page(page).annotations.list(); const box = annotations.find((candidate) => candidate.subtype === 'free-text'); if (box?.subtype !== 'free-text') throw new Error('no free text box'); const drawn = await drawnTextOf(await doc.download()); const resolved = await doc.fonts.resolve({ annotation: box.ref, runs: [{ text: 'שלום', fontFamily} ], } ); return{ fontFamily: box.fontFamily, body: box.richText?.body, drawnIn: [...new Set(drawn.flatMap((form) => form.runs.map((run) => run.font)))], resolvedTo: resolved.runs[0]!.font, missingCharacters: meta.missingCharacters, } ; } test('a box written in a document font is drawn in it, its family and weight its own', async () =>{ const doc = await open( pdfWithFontDictionaries(fixtures.fontProgram, [{ baseFont: 'BrandSans-SemiBold', family: 'Brand Sans', weight: 600} , ]), ); const box = await boxIn(doc, 'BrandSans-SemiBold'); expect(box.fontFamily).toBe('BrandSans-SemiBold'); expect(box.body).toMatchObject({ family: 'Brand Sans', weight: 600, italic: false} ); expect(box.drawnIn).toEqual(['BrandSans-SemiBold']); expect(box.resolvedTo).toBe('BrandSans-SemiBold'); expect(box.missingCharacters).toBe(undefined); await doc.close(); } ); test('two fonts described alike keep their own names, and a box in one is drawn in that one', async () =>{ const doc = await open( pdfWithFontDictionaries(fixtures.fontProgram, [{ baseFont: 'Mono-Regular'} , { baseFont: 'Mono-Thin'} , ]), ); expect(namesOf(await documentFonts(doc))).toEqual(['Mono-Regular', 'Mono-Thin']); const box = await boxIn(doc, 'Mono-Thin'); expect(box.fontFamily).toBe('Mono-Thin'); expect(box.body).toMatchObject({ family: 'Mono', weight: 400} ); expect(box.drawnIn).toEqual(['Mono-Thin']); expect(box.resolvedTo).toBe('Mono-Thin'); const after = await documentFonts(doc); expectUnique(after); expect(namesOf(after).sort()).toEqual(['Mono-Regular', 'Mono-Thin']); await doc.close(); } ); test('a font without a PostScript name is named by its family and exact style', async () =>{ const doc = await open( pdfWithFontDictionaries(fixtures.fontProgram, [{ family: 'Inter', weight: 400} , { family: 'Inter', weight: 500} , { family: 'Inter', weight: 800} , { family: 'Inter', weight: 400, italic: true} , ]), ); const fonts = await documentFonts(doc); expect(namesOf(fonts)).toEqual([ 'Inter', 'Inter, Medium', 'Inter, ExtraBold', 'Inter, Italic', ]); expect(fonts.every((font) => !font.canChoose)).toBe(true); await doc.close(); } ); } ); } ); } runDrawingDetailsConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runDrawingDetailsConformance.ts): export function runDrawingDetailsConformance( runner: ConformanceTestRunner, options: DrawingDetailsConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`drawing details conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const firstPage = async (doc: DocumentHandle) =>{ const{ pages} = await doc.pages.list(); return{ page: doc.page(pages[0]!.ref), pageRef: pages[0]!.ref} ; } ; const byNm = async (doc: DocumentHandle, nm: string): Promise =>{ const{ page} = await firstPage(doc); const found = (await page.annotations.list()).annotations.find((a) => a.nm === nm); if (!found) throw new Error(`no annotation '${ nm} ' in the fixture`); return found; } ; const invalid ={ code: EngineErrorCode.InvalidArg} ; test("Acrobat's text box: the text is its rich text's color, the border its /DA color", async () =>{ const doc = await options.open(engine, 'acrobat-freetext'); try{ const{ page} = await firstPage(doc); const box = await byNm(doc, ACROBAT_TEXT_BOX); if (box.subtype !== 'free-text') throw new Error('expected a free text'); expect(box.fontColor).toBe('#000000'); expect(box.color).toBe('#ff6200'); expect(box.intent).toBe('free-text'); expect(box.verticalAlign).toBe('top'); const bordered = await page.annotations.update(box.ref, { color: '#0000ff'} ); if (bordered.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(bordered.annotation.color).toBe('#0000ff'); expect(bordered.annotation.fontColor).toBe('#000000'); const colored = await page.annotations.update(box.ref, { fontColor: '#00aa00'} ); if (colored.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(colored.annotation.fontColor).toBe('#00aa00'); expect(colored.annotation.color).toBe('#0000ff'); expect(colored.annotation.richText.body.family).toBe(box.richText.body.family); expect(colored.annotation.fontSize).toBe(box.fontSize); } finally{ await doc.close(); } } ); test('a free text create takes defaults, and prints', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const{ annotation} = await page.annotations.create({ subtype: 'free-text', box: BOX, contents: 'Defaults', } ); if (annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(annotation).toMatchObject({ intent: 'free-text', fontFamily: 'helvetica', fontSize: 12, textAlign: 'left', verticalAlign: 'top', fontColor: '#000000', color: '#000000', print: true, } ); } finally{ await doc.close(); } } ); test('a callout line makes a callout; another box refuses one', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const calloutLine: [{ x: number; y: number} , { x: number; y: number} ] = [{ x: 20, y: 150} , { x: 40, y: 100} , ]; const callout = await page.annotations.create({ subtype: 'free-text', box: BOX, contents: 'Look', calloutLine, } ); if (callout.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(callout.annotation.intent).toBe('free-text-callout'); await expect( page.annotations.create({ subtype: 'free-text', box: BOX, intent: 'free-text', calloutLine, } ), ).rejects.toMatchObject(invalid); const plain = await page.annotations.create({ subtype: 'free-text', box: BOX} ); await expect( page.annotations.update(plain.annotation.ref, { calloutLine} ), ).rejects.toMatchObject(invalid); const became = await page.annotations.update(plain.annotation.ref, { intent: 'free-text-callout', calloutLine, } ); if (became.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(became.annotation.intent).toBe('free-text-callout'); } finally{ await doc.close(); } } ); test('the text style given by itself wins over the rich body; a given body is replaced whole', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const created = await page.annotations.create({ subtype: 'free-text', box: BOX, fontColor: '#ff0000', richText:{ body:{ color: '#0000ff', size: 20} , paragraphs: [{ runs: [{ text: 'styled'} ]} ], } , } ); if (created.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(created.annotation.fontColor).toBe('#ff0000'); expect(created.annotation.fontSize).toBe(20); const retyped = await page.annotations.update(created.annotation.ref, { richText:{ paragraphs: [{ runs: [{ text: 'retyped'} ]} ]} , } ); if (retyped.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(retyped.annotation.fontSize).toBe(20); expect(retyped.annotation.fontColor).toBe('#ff0000'); const italic = await page.annotations.update(created.annotation.ref, { richText:{ body:{ italic: true} , paragraphs: [{ runs: [{ text: 'restyled'} ]} ]} , } ); if (italic.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(italic.annotation.richText.body.italic).toBe(true); expect(italic.annotation.fontSize).toBe(12); expect(italic.annotation.fontColor).toBe('#000000'); } finally{ await doc.close(); } } ); test('free text justifies, sits in its box, and takes a cloudy border', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const created = await page.annotations.create({ subtype: 'free-text', box:{ ...BOX, height: 120} , contents: 'A line long enough to wrap onto a second line in its box', textAlign: 'justify', verticalAlign: 'middle', cloudyIntensity: 1, } ); if (created.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(created.annotation.textAlign).toBe('justify'); expect(created.annotation.verticalAlign).toBe('middle'); expect(created.annotation.cloudyIntensity).toBe(1); const moved = await page.annotations.update(created.annotation.ref, { verticalAlign: 'bottom', cloudyIntensity: null, } ); if (moved.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(moved.annotation.verticalAlign).toBe('bottom'); expect(moved.annotation.cloudyIntensity).toBe(null); } finally{ await doc.close(); } } ); test("another app's typewriter box is read and kept, not created", async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const typewriter = await byNm(doc, 'typewriter'); if (typewriter.subtype !== 'free-text') throw new Error('expected a free text'); expect(typewriter.intent).toBe('free-text-typewriter'); const retyped = await page.annotations.update(typewriter.ref, { intent: typewriter.intent, contents: 'retyped', } ); if (retyped.annotation.subtype !== 'free-text') throw new Error('expected a free text'); expect(retyped.annotation.intent).toBe('free-text-typewriter'); await expect( page.annotations.create({ subtype: 'free-text', box: BOX, intent: 'free-text-typewriter', } as never), ).rejects.toMatchObject(invalid); } finally{ await doc.close(); } } ); test('borders: only a widget writes beveled or inset; a pattern alone keeps a border solid; dashed states its pattern, never an empty one', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); await expect( page.annotations.create({ subtype: 'square', box: BOX, borderStyle: 'beveled'} as never), ).rejects.toMatchObject(invalid); const beveled = await byNm(doc, 'beveled'); if (beveled.subtype !== 'square') throw new Error('expected a square'); expect(beveled.borderStyle).toBe('beveled'); const kept = await page.annotations.update(beveled.ref, { borderStyle: beveled.borderStyle, contents: 'kept', } ); if (kept.annotation.subtype !== 'square') throw new Error('expected a square'); expect(kept.annotation.borderStyle).toBe('beveled'); await expect( page.annotations.update(beveled.ref, { borderStyle: 'inset'} as never), ).rejects.toMatchObject(invalid); const patterned = await page.annotations.create({ subtype: 'square', box: BOX, borderStyle: 'solid', dashArray: [2, 2], } ); if (patterned.annotation.subtype !== 'square') throw new Error('expected a square'); expect(patterned.annotation.borderStyle).toBe('solid'); expect(patterned.annotation.dashArray).toEqual([2, 2]); const dashed = await page.annotations.create({ subtype: 'square', box: BOX, borderStyle: 'dashed', } ); if (dashed.annotation.subtype !== 'square') throw new Error('expected a square'); expect(dashed.annotation.borderStyle).toBe('dashed'); expect(dashed.annotation.dashArray).toEqual([3, 3]); const none = await page.annotations.create({ subtype: 'square', box: BOX, borderStyle: 'dashed', dashArray: null, } ); if (none.annotation.subtype !== 'square') throw new Error('expected a square'); expect(none.annotation.borderStyle).toBe('dashed'); expect(none.annotation.dashArray).toBe(null); const cleared = await page.annotations.update(patterned.annotation.ref, { borderStyle: 'dashed', dashArray: null, } ); if (cleared.annotation.subtype !== 'square') throw new Error('expected a square'); expect(cleared.annotation.borderStyle).toBe('dashed'); expect(cleared.annotation.dashArray).toBe(null); await expect( page.annotations.create({ subtype: 'square', box: BOX, borderStyle: 'dashed', dashArray: [], } ), ).rejects.toMatchObject(invalid); await expect( page.annotations.update(dashed.annotation.ref, { dashArray: []} ), ).rejects.toMatchObject(invalid); const noPattern = await byNm(doc, 'dashed-no-pattern'); if (noPattern.subtype !== 'square') throw new Error('expected a square'); expect(noPattern.borderStyle).toBe('dashed'); expect(noPattern.dashArray).toBe(null); const emptyPattern = await byNm(doc, 'dashed-empty-pattern'); if (emptyPattern.subtype !== 'square') throw new Error('expected a square'); expect(emptyPattern.borderStyle).toBe('solid'); expect(emptyPattern.dashArray).toBe(null); } finally{ await doc.close(); } } ); test('too few points to draw is InvalidArg', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const point ={ x: 50, y: 50} ; const other ={ x: 90, y: 90} ; for (const draft of [{ subtype: 'polyline', vertices: [point]} , { subtype: 'polygon', vertices: [point, other]} , { subtype: 'ink', inkList: []} , { subtype: 'ink', inkList: [[point, other], []]} , { subtype: 'ink', inkList: [[point, other]], strokeWidth: 0} , ]){ await expect(page.annotations.create(draft as never)).rejects.toMatchObject(invalid); } } finally{ await doc.close(); } } ); test('a new annotation prints, a popup does not', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const square = await page.annotations.create({ subtype: 'square', box: BOX} ); expect(square.annotation.print).toBe(true); const unprinted = await page.annotations.create({ subtype: 'square', box: BOX, print: false, } ); expect(unprinted.annotation.print).toBe(false); const popup = await page.annotations.create({ subtype: 'popup', parent: square.annotation.ref, rect:{ x: 210, y: 40, width: 80, height: 60} , } ); expect(popup.annotation.print).toBe(false); } finally{ await doc.close(); } } ); test('a note and its popup share one open; a second popup is refused', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page} = await firstPage(doc); const note = await page.annotations.create({ subtype: 'text', rect: iconRect(40, 40), open: true, } ); if (note.annotation.subtype !== 'text') throw new Error('expected a note'); expect(note.annotation.open).toBe(true); const popup = await page.annotations.create({ subtype: 'popup', parent: note.annotation.ref, rect:{ x: 70, y: 40, width: 120, height: 80} , } ); if (popup.annotation.subtype !== 'popup') throw new Error('expected a popup'); expect(popup.annotation.open).toBe(true); const readBoth = async () =>{ const{ annotations} = await page.annotations.list(); const find = (ref: Annotation['ref']) => annotations.find((a) => JSON.stringify(a.ref) === JSON.stringify(ref)); return{ note: find(note.annotation.ref), popup: find(popup.annotation.ref)} ; } ; const closed = await page.annotations.update(note.annotation.ref, { open: false} ); expect(closed.meta.changedRefs).toHaveLength(2); let both = await readBoth(); expect(both.note?.subtype === 'text' && both.note.open).toBe(false); expect(both.popup?.subtype === 'popup' && both.popup.open).toBe(false); await page.annotations.update(popup.annotation.ref, { open: true} ); both = await readBoth(); expect(both.note?.subtype === 'text' && both.note.open).toBe(true); await expect( page.annotations.create({ subtype: 'popup', parent: note.annotation.ref, rect:{ x: 70, y: 140, width: 120, height: 80} , } ), ).rejects.toMatchObject(invalid); } finally{ await doc.close(); } } ); test('links: page verbs are written, a missing fit coordinate stays missing, no border', async () =>{ const doc = await options.open(engine, 'drawing'); try{ const{ page, pageRef} = await firstPage(doc); const next = await page.annotations.create({ subtype: 'link', rect: BOX, target:{ kind: 'named', name: 'NextPage'} , } ); if (next.annotation.subtype !== 'link') throw new Error('expected a link'); expect(next.annotation.target).toEqual({ kind: 'named', name: 'NextPage'} ); const fit = await page.annotations.create({ subtype: 'link', rect:{ ...BOX, y: 120} , target:{ kind: 'goto', destination:{ kind: 'fitH', page: pageRef, y: null} } , } ); if (fit.annotation.subtype !== 'link') throw new Error('expected a link'); expect(fit.annotation.target).toEqual({ kind: 'goto', destination:{ kind: 'fitH', page: pageRef, y: null} , } ); const text = new TextDecoder('latin1').decode(await doc.download()); expect(text).toMatch(/\/Border\s*\[\s*0\s+0\s+0\s*\]/); expect(/\/FitH\s+0\s*\]/.test(text)).toBe(false); } finally{ await doc.close(); } } ); } ); } runFieldGroupsConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFieldGroupsConformance.ts): export function runFieldGroupsConformance( runner: ConformanceTestRunner, options: FieldGroupsConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`field groups conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const as = async ( token: FieldGroupToken, body: (doc: DocumentHandle) => Promise, bytes?: Uint8Array, ) =>{ const{ scope, identity} = FIELD_GROUP_TOKENS[token]; const doc = await options.open(engine, scope, identity, bytes); try{ await body(doc); } finally{ await doc.close(); } } ; const refusal = (attempt: Promise): Promise => attempt.then( () => null, (error: unknown) => error, ); const codeOf = (error: unknown) => EngineError.is(error) ? error.code : error === null ? 'resolved' : String(error); const valueOf = async (doc: DocumentHandle, name: string) => ( (await doc.forms.list()).fields.find((f) => f.name === name) as |{ value?: string} | undefined )?.value; test('each token lists the groups it may fill in, sign and assign', async () =>{ const rights: Record ={ } ; for (const token of Object.keys(FIELD_GROUP_TOKENS) as FieldGroupToken[]){ await as(token, async (doc) =>{ rights[token] = doc.security.fieldRights(); const listed = doc.security.fieldRights(); for (const groupId of ['buyer', 'seller', 'legal', null]){ for (const action of ['fill', 'sign'] as const){ const right = listed[action]; const inList = right.all || (groupId !== null && right.groups.includes(groupId)); expect(inList).toBe(doc.security.allowsField(action, { groupId} )); } } for (const groupId of ['buyer', 'seller', 'legal']){ const right = listed.setGroup; const inList = right.all || right.groups.includes(groupId); expect(inList).toBe(doc.security.allowsField('set-group', { groupId} )); } } ); } expect(rights).toEqual({ buyer:{ fill:{ all: false, groups: ['buyer']} , sign:{ all: false, groups: ['buyer']} , setGroup:{ all: false, groups: []} , } , seller:{ fill:{ all: false, groups: ['seller']} , sign:{ all: false, groups: ['seller']} , setGroup:{ all: false, groups: ['seller']} , } , designer:{ fill:{ all: true} , sign:{ all: false, groups: []} , setGroup:{ all: false, groups: ['buyer', 'legal']} , } , everything:{ fill:{ all: true} , sign:{ all: true} , setGroup:{ all: true} } , } ); } ); test("a field's group reads from its /EMBD_Metadata; its widget has none", async () =>{ await as('everything', async (doc) =>{ const{ fields, widgets} = await doc.forms.list(); const groups = Object.fromEntries(fields.map((f) => [f.name, f.groupId])); expect(groups).toEqual({ buyer_name: 'buyer', buyer_price: 'buyer', seller_name: 'seller', total: null, buyer_sig: 'buyer', seller_sig: 'seller', } ); expect(widgets.every((w) => w.groupId === null)).toBe(true); } ); } ); test('each signer fills in only their own fields', async () =>{ await as('buyer', async (doc) =>{ await doc.forms.setValue(field('buyer_name'), { value: 'Alice'} ); expect(await valueOf(doc, 'buyer_name')).toBe('Alice'); const refused = await refusal(doc.forms.setValue(field('seller_name'), { value: 'x'} )); expect(codeOf(refused)).toBe(EngineErrorCode.Forbidden); expect((refused as EngineError).details).toMatchObject({ required: 'fields:fill:group=seller', } ); expect(codeOf(await refusal(doc.forms.setValue(field('total'), { value: '9'} )))).toBe( EngineErrorCode.Forbidden, ); expect(doc.security.allowsField('fill', { groupId: 'buyer'} )).toBe(true); expect(doc.security.allowsField('fill', { groupId: 'seller'} )).toBe(false); } ); await as('seller', async (doc) =>{ await doc.forms.setValue(field('seller_name'), { value: 'Bob'} ); expect(codeOf(await refusal(doc.forms.setValue(field('buyer_name'), { value: 'x'} )))).toBe( EngineErrorCode.Forbidden, ); } ); } ); test("a calculated field moves with a fill of the signer's own, never alone", async () =>{ await as('buyer', async (doc) =>{ await doc.apply({ ops: [{ type: 'forms.setValue', field: field('buyer_price'), value:{ value: '1200'} } , { type: 'forms.setValue', field: field('total'), value:{ value: '1452'} } , ], } ); expect(await valueOf(doc, 'total')).toBe('1452'); const alone = await refusal( doc.apply({ ops: [{ type: 'forms.setValue', field: field('total'), value:{ value: '1'} } ], } ), ); expect(codeOf(alone)).toBe(EngineErrorCode.Forbidden); const across = await refusal( doc.apply({ ops: [{ type: 'forms.setValue', field: field('buyer_price'), value:{ value: '1'} } , { type: 'forms.setValue', field: field('seller_name'), value:{ value: 'x'} } , ], } ), ); expect(codeOf(across)).toBe(EngineErrorCode.Forbidden); expect(await valueOf(doc, 'buyer_price')).toBe('1200'); } ); } ); test('a reset puts back only fields the signer may fill', async () =>{ await as('buyer', async (doc) =>{ await doc.forms.setValue(field('buyer_name'), { value: 'Alice'} ); await doc.forms.reset([field('buyer_name')]); expect(await valueOf(doc, 'buyer_name')).toBe(''); expect(codeOf(await refusal(doc.forms.reset()))).toBe(EngineErrorCode.Forbidden); } ); } ); test('each signer signs only their own signature field', async () =>{ await as('buyer', async (doc) =>{ const refused = await refusal(doc.signatures.prepare({ field: field('seller_sig')} )); expect(codeOf(refused)).toBe(EngineErrorCode.Forbidden); const prepared = await doc.signatures.prepare({ field: field('buyer_sig')} ); await doc.signatures.cancel(prepared.signingId); expect(doc.security.allowsField('sign', { groupId: 'buyer'} )).toBe(true); expect(doc.security.allowsField('sign', { groupId: 'seller'} )).toBe(false); } ); } ); test('a signer who also holds doc.sign adds a document timestamp, and signs no more fields for it', async () =>{ await as('buyer', async (doc) =>{ const refused = await refusal(doc.signatures.prepare({ kind: 'timestamp'} )); expect(codeOf(refused)).toBe(EngineErrorCode.Forbidden); } ); const{ scope, identity} = FIELD_GROUP_TOKENS.buyer; const doc = await options.open(engine, [...scope, 'doc.sign'], identity); try{ const prepared = await doc.signatures.prepare({ kind: 'timestamp'} ); expect(prepared.subFilter).toBe('ETSI.RFC3161'); if (options.completesSignings === false){ await doc.signatures.cancel(prepared.signingId); } else{ const result = await doc.signatures.complete({ signingId: prepared.signingId, cms: PLACEHOLDER_CMS, expectedVersion: prepared.expectedVersion, } ); expect(result.signature.kind).toBe('timestamp'); } const other = await refusal(doc.signatures.prepare({ field: field('seller_sig')} )); expect(codeOf(other)).toBe(EngineErrorCode.Forbidden); expect(doc.security.allowsField('sign', { groupId: 'seller'} )).toBe(false); expect(doc.security.allowsField('sign', { groupId: null} )).toBe(false); } finally{ await doc.close(); } } ); test('signing a grouped field locks the rest of its group, for everyone', async () =>{ if (options.completesSignings === false) return; await as('everything', async (doc) =>{ await doc.forms.setValue(field('buyer_name'), { value: 'Alice'} ); const prepared = await doc.signatures.prepare({ field: field('buyer_sig')} ); await doc.signatures.complete({ signingId: prepared.signingId, cms: PLACEHOLDER_CMS, expectedVersion: prepared.expectedVersion, } ); const locked = await refusal(doc.forms.setValue(field('buyer_name'), { value: 'x'} )); expect(codeOf(locked)).toBe(EngineErrorCode.ProtectedDocument); await doc.forms.setValue(field('seller_name'), { value: 'Bob'} ); const next = await doc.signatures.prepare({ field: field('seller_sig')} ); await doc.signatures.cancel(next.signingId); } ); } ); test('a designer puts fields in her own group, or one she may set', async () =>{ await as('designer', async (doc) =>{ const own = await doc.forms.create({ kind: 'text', name: 'clause', widgets: [{ page: PAGE, rect:{ x: 20, y: 200, width: 100, height: 20} } ], } ); expect(own.field.groupId).toBe('legal'); const buyers = await doc.forms.create({ kind: 'text', name: 'buyer_address', groupId: 'buyer', widgets: [{ page: PAGE, rect:{ x: 140, y: 200, width: 100, height: 20} } ], } ); expect(buyers.field.groupId).toBe('buyer'); const refused = await refusal( doc.forms.create({ kind: 'text', name: 'seller_address', groupId: 'seller', widgets: [{ page: PAGE, rect:{ x: 260, y: 200, width: 100, height: 20} } ], } ), ); expect(codeOf(refused)).toBe(EngineErrorCode.Forbidden); expect((refused as EngineError).details).toMatchObject({ required: 'fields:set-group:group=seller', } ); const moved = await doc.forms.update(own.field.ref, { groupId: 'buyer'} ); expect(moved.field.groupId).toBe('buyer'); expect(codeOf(await refusal(doc.forms.update(own.field.ref, { groupId: 'seller'} )))).toBe( EngineErrorCode.Forbidden, ); expect(doc.security.allowsField('set-group', { groupId: 'buyer'} )).toBe(true); expect(doc.security.allowsField('set-group', { groupId: 'seller'} )).toBe(false); } ); } ); test('a copied form keeps the groups the importer may set; a restore keeps every one', async () =>{ let buyers: Awaited> | null = null; let everyone: Awaited> | null = null; await as('everything', async (doc) =>{ buyers = await doc.forms.export({ fields: [field('buyer_name')]} ); everyone = await doc.forms.export(); } ); const blank = await (async () =>{ let bytes: Uint8Array | null = null; await as('everything', async (doc) =>{ for (const{ ref} of (await doc.forms.list()).fields) await doc.forms.delete(ref); bytes = await doc.download(); } ); return bytes!; } )(); await as( 'designer', async (doc) =>{ const copied = await doc.forms.import(buyers!, { attribution: 'stamp'} ); expect(copied.fields.map((f) => [f.name, f.groupId])).toEqual([['buyer_name', 'buyer']]); const refused = await refusal(doc.forms.import(everyone!, { attribution: 'stamp'} )); expect(codeOf(refused)).toBe(EngineErrorCode.Forbidden); } , blank, ); await as( 'everything', async (doc) =>{ const restored = await doc.forms.import(everyone!, { attribution: 'restore'} ); expect(Object.fromEntries(restored.fields.map((f) => [f.name, f.groupId]))).toMatchObject({ buyer_name: 'buyer', seller_name: 'seller', total: null, } , ); } , blank, ); } ); test('a values import leaves out the fields the signer may not fill', async () =>{ let bundle: Awaited> | null = null; await as('everything', async (doc) =>{ await doc.forms.setValue(field('buyer_name'), { value: 'Alice'} ); await doc.forms.setValue(field('seller_name'), { value: 'Bob'} ); bundle = await doc.forms.export(); } ); await as('buyer', async (doc) =>{ const result = await doc.forms.importValues(bundle!, { attribution: 'stamp'} ); expect(result.fields.map((f) => f.name)).toEqual(['buyer_name']); expect(result.dropped.some((drop) => drop.reason === 'fill-not-allowed')).toBe(true); expect(await valueOf(doc, 'seller_name')).toBe(''); } ); } ); } ); } runFormAttributionConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFormAttributionConformance.ts): export function runFormAttributionConformance( runner: ConformanceTestRunner, options: FormAttributionConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`form attribution conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const open = (identity: Identity, scope: readonly string[] = FILL, from?: DocumentHandle) => options.openAs(engine, { scope, identity} , from); const continueAs = async (from: DocumentHandle, identity: Identity) =>{ const next = await open(identity, FILL, from); await from.close(); return next; } ; const fieldOf = async (doc: DocumentHandle, name: string): Promise =>{ const{ fields} = await doc.forms.list(); const field = fields.find((f) => f.name === name); if (!field) throw new Error(`no field '${ name} '`); return field; } ; const expectStampedSince = (value: string | null, before: number) =>{ expect(value !== null).toBe(true); const at = Date.parse(value!); expect(at >= Math.floor(before / 1000) * 1000 && at <= Date.now()).toBe(true); } ; test('create names who created the field, and when', async () =>{ const doc = await open(ALICE, DESIGN); try{ const before = Date.now(); const{ field} = await doc.forms.create({ kind: 'text', name: 'extra'} ); expect(field.createdBy).toBe('alice'); expectStampedSince(field.createdAt, before); expect(field.filledBy).toBe(null); expect(field.importedBy).toBe(null); expect((await fieldOf(doc, 'extra')).createdBy).toBe('alice'); expect((await fieldOf(doc, 'name')).createdBy).toBe(null); } finally{ await doc.close(); } } ); test('a fill names who filled the value in; one that changes nothing names nobody new', async () =>{ let doc = await open(ALICE); const before = Date.now(); const{ field} = await doc.forms.setValue(NAME, { value: 'Cleo'} ); expect(field.filledBy).toBe('alice'); expect(field.filledByName).toBe('Alice Author'); expectStampedSince(field.filledAt, before); doc = await continueAs(doc, BOB); try{ const same = await doc.forms.setValue(NAME, { value: 'Cleo'} ); expect(same.field.filledBy).toBe('alice'); const changed = await doc.forms.setValue(NAME, { value: 'Bea'} ); expect(changed.field.filledBy).toBe('bob'); expect(changed.field.filledByName).toBe('Bob Builder'); expect((await fieldOf(doc, 'name')).filledBy).toBe('bob'); } finally{ await doc.close(); } } ); test('a reset, and an anonymous fill, name nobody', async () =>{ let doc = await open(ALICE); await doc.forms.setValue(NAME, { value: 'Cleo'} ); const reset = await doc.forms.reset(NAME); const cleared = reset.fields.find((field) => field.name === 'name')!; expect([cleared.filledBy, cleared.filledByName, cleared.filledAt]).toEqual([ null, null, null, ]); await doc.forms.setValue(NAME, { value: 'Cleo'} ); doc = await continueAs(doc, ANONYMOUS); try{ const{ field} = await doc.forms.setValue(NAME, { value: 'Someone'} ); expect([field.filledBy, field.filledByName, field.filledAt]).toEqual([null, null, null]); } finally{ await doc.close(); } } ); test("a script's value counts as filled in by the user whose fill ran it", async () =>{ const doc = await open(ALICE); try{ await doc.apply({ ops: [{ type: 'forms.setValue', field: NAME, value:{ value: 'Calculated'} } ], } ); expect((await fieldOf(doc, 'name')).filledBy).toBe('alice'); } finally{ await doc.close(); } } ); test('undoing a fill puts the previous filler back', async () =>{ let doc = await open(ALICE); await doc.forms.setValue(NAME, { value: 'Cleo'} ); doc = await continueAs(doc, BOB); try{ const filled = await doc.forms.setValue(NAME, { value: 'Bea'} ); expect(filled.field.filledBy).toBe('bob'); await doc.apply({ undoOf: filled.meta.opId} ); const field = await fieldOf(doc, 'name'); expect(field.filledBy).toBe('alice'); expect(field.filledByName).toBe('Alice Author'); } finally{ await doc.close(); } } ); test('a widget row reports no attribution: the field holds it', async () =>{ const doc = await open(ALICE); try{ await doc.forms.setValue(NAME, { value: 'Cleo'} ); const{ widgets} = await doc.forms.list(); const row = widgets.find( (w) => w.ref.kind === 'objectNumber' && w.ref.objectNumber === WIDGET, ); expect(row !== undefined).toBe(true); expect([row!.createdBy, row!.userId, row!.groupId, row!.importedBy]).toEqual([ null, null, null, null, ]); } finally{ await doc.close(); } } ); } ); } runFormConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFormConformance.ts): export function runFormConformance( runner: ConformanceTestRunner, options: FormConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`forms conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ await engine.destroy(); } ); async function open(fixture: ConformanceFixture, idSuffix = ''): Promise{ if (options.openKind === 'bytes'){ const bytes = await fixture.bytes(); return engine.open({ kind: 'bytes', id: fixture.id + idSuffix, bytes} , EVERY_PERMISSION); } return engine.open({ kind: 'id', id: fixture.cloudId ?? fixture.id} ); } function fieldByName(fields: FormField[], name: string): FormField{ const field = fields.find((f) => f.name === name); expect(Boolean(field)).toBe(true); return field!; } test('lists the reconciled field tree with per-family DTOs', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const snapshot = await doc.forms.list(); FormSnapshotSchema.parse(snapshot); expect(snapshot.formKind).toBe('acroform'); const text = fieldByName(snapshot.fields, 'maxlen_text'); if (text.kind !== 'text') throw new Error('expected text family'); expect(text.value).toBe('abc'); expect(text.valueEntry).toEqual({ kind: 'scalar', value: 'abc'} ); expect(text.defaultValueEntry).toEqual({ kind: 'none'} ); expect(text.maxLength).toBe(5); expect(text.widgets.length).toBe(1); const radio = fieldByName(snapshot.fields, 'ntto_radio'); if (radio.kind !== 'radio') throw new Error('expected radio family'); expect(radio.noToggleToOff).toBe(true); expect(radio.value).toBe('x'); expect(radio.valueEntry).toEqual({ kind: 'scalar', value: 'x'} ); expect(radio.defaultValueEntry).toEqual({ kind: 'scalar', value: 'x'} ); expect(radio.widgets.map((w) => w.onState)).toEqual(['x', 'y']); expect(radio.widgets.map((w) => w.checked)).toEqual([true, false]); const unison = fieldByName(snapshot.fields, 'unison_radio'); if (unison.kind !== 'radio') throw new Error('expected radio family'); expect(unison.radiosInUnison).toBe(true); const check = fieldByName(snapshot.fields, 'opt_check'); if (check.kind !== 'checkbox') throw new Error('expected checkbox family'); expect(check.checked).toBe(false); expect(check.exportValue).toBe('Alpha'); const nested = fieldByName(snapshot.fields, 'billing.name'); expect(nested.kind).toBe('text'); expect(snapshot.calculationOrder).toEqual([]); } finally{ await doc.close(); } } ); test('writes text values and truncates to /MaxLen', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const result = await doc.forms.setValue({ kind: 'fqn', name: 'maxlen_text'} , { value: 'abcde'} , ); FormSetValueResultSchema.parse(result); expect(result.field.kind).toBe('text'); if (result.field.kind === 'text') expect(result.field.value).toBe('abcde'); expect(result.meta.changedWidgets.length).toBe(1); expect(result.meta.changedFields).toEqual([result.field.ref]); expect(result.meta.affectedPages).toEqual([result.meta.changedWidgets[0]!.page]); const truncated = await doc.forms.setValue({ kind: 'fqn', name: 'maxlen_text'} , { value: 'abcdef'} , ); if (truncated.field.kind !== 'text') throw new Error('expected text family'); expect(truncated.field.value).toBe('abcde'); expect(truncated.meta.changedWidgets).toHaveLength(0); const after = await doc.forms.get({ kind: 'fqn', name: 'maxlen_text'} ); if (after.kind === 'text') expect(after.value).toBe('abcde'); } finally{ await doc.close(); } } ); test('toggles radio groups and honors NoToggleToOff', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const radioRef ={ kind: 'fqn', name: 'ntto_radio'} as const; const result = await doc.forms.setValue(radioRef, { value: 'y'} ); if (result.field.kind !== 'radio') throw new Error('expected radio family'); expect(result.field.value).toBe('y'); expect(result.field.widgets.map((w) => w.checked)).toEqual([false, true]); expect(result.meta.changedWidgets.length).toBe(2); await expect(doc.forms.setValue(radioRef, { value: null} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); await expect(doc.forms.setValue(radioRef, { value: 'z'} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const optCheck ={ kind: 'fqn', name: 'opt_check'} as const; await expect(doc.forms.setValue(optCheck, { value: 'On'} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const byValue = await doc.forms.setValue(optCheck, { value: 'Alpha'} ); if (byValue.field.kind !== 'checkbox') throw new Error('expected checkbox family'); expect(byValue.field.checked).toBe(true); const cleared = await doc.forms.setValue(optCheck, { checked: false} ); if (cleared.field.kind !== 'checkbox') throw new Error('expected checkbox family'); expect(cleared.field.checked).toBe(false); const check = await doc.forms.setValue(optCheck, { checked: true} ); if (check.field.kind !== 'checkbox') throw new Error('expected checkbox family'); expect(check.field.checked).toBe(true); expect(check.field.exportValue).toBe('Alpha'); } finally{ await doc.close(); } } ); test('rejects family/value mismatches without touching the field', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const before = await doc.forms.get({ kind: 'fqn', name: 'maxlen_text'} ); if (before.kind !== 'text') throw new Error('expected text family'); await expect( doc.forms.setValue({ kind: 'fqn', name: 'maxlen_text'} , { checked: true} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const field = await doc.forms.get({ kind: 'fqn', name: 'maxlen_text'} ); if (field.kind === 'text') expect(field.value).toBe(before.value); } finally{ await doc.close(); } } ); test("a script run's effects are one change: all of it, or none of it", async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const events: Extract[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type === 'forms.valueSet') events.push(event); } ); const text ={ kind: 'fqn', name: 'maxlen_text'} as const; const before = await doc.forms.get(text); const refusal = await doc .apply({ ops: formEffectOps([{ kind: 'setValue', ref: text, value:{ value: 'abcdef'} } , { kind: 'setValue', ref:{ kind: 'fqn', name: 'missing.effect.field'} , value:{ value: 'ignored'} , } , ]), } ) .then( () => null, (error: unknown) => error, ); expect(refusal === null).toBe(false); const untouched = await doc.forms.get(text); if (untouched.kind === 'text' && before.kind === 'text'){ expect(untouched.value).toBe(before.value); } expect(events).toHaveLength(0); const result = await doc.apply({ ops: formEffectOps([{ kind: 'setValue', ref: text, value:{ value: 'abcdef'} } , { kind: 'setValue', ref: text, value:{ value: 'xyz'} } , ]), } ); expect(result.items.map((item) => item.type)).toEqual(['forms.setValue', 'forms.setValue']); const after = await doc.forms.get(text); if (after.kind !== 'text') throw new Error('expected text family'); expect(after.value).toBe('xyz'); expect(new Set(events.map((event) => event.origin.transaction?.id))).toEqual( new Set([result.meta.opId]), ); unsubscribe(); } finally{ await doc.close(); } } ); test('a value, reset or display that changes nothing has nothing to undo', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const text ={ kind: 'fqn', name: 'maxlen_text'} as const; const fill ={ ops: formEffectOps([{ kind: 'setValue', ref: text, value:{ value: 'abc'} } ]), } ; const hide ={ ops: formEffectOps([{ kind: 'setDisplay', ref: text, display: 'hidden'} ])} ; const reset ={ ops: formEffectOps([{ kind: 'reset', refs: [text]} ])} ; await doc.forms.setValue(text, { value: 'xyz'} ); expect((await doc.apply(fill)).meta.undoable).toBe(true); expect((await doc.apply(hide)).meta.undoable).toBe(true); expect((await doc.apply(reset)).meta.undoable).toBe(true); await doc.forms.setValue(text, { value: 'abc'} ); expect((await doc.apply(fill)).meta.undoable).toBe(false); expect((await doc.apply(hide)).meta.undoable).toBe(false); await doc.apply(reset); expect((await doc.apply(reset)).meta.undoable).toBe(false); } finally{ await doc.close(); } } ); test('selects multi-select list box options by export value', async () =>{ const doc = await open(options.fixtures.choiceFields); try{ const multiRef ={ kind: 'fqn', name: 'Listbox_MultiSelect'} as const; const result = await doc.forms.setValue(multiRef, { selectedValues: ['Cherry', 'Apple']} ); if (result.field.kind !== 'listbox') throw new Error('expected listbox family'); expect(result.field.selectedValues).toEqual(['Apple', 'Cherry']); expect(result.field.valueEntry.kind).toBe('array'); await expect( doc.forms.setValue({ kind: 'fqn', name: 'Listbox_SingleSelect'} , { selectedValues: ['foo', 'bar']} , ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } finally{ await doc.close(); } } ); test('reset restores /DV or clears the value, and reports only the fields it changed', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const radioRef = toFieldRef('ntto_radio'); const textRef = toFieldRef('maxlen_text'); await doc.forms.setValue(radioRef, { value: 'y'} ); const radio = await doc.forms.reset(radioRef); FormResetResultSchema.parse(radio); expect(radio.fields.map((field) => field.name)).toEqual(['ntto_radio']); const [restored] = radio.fields; if (restored?.kind === 'radio') expect(restored.value).toBe('x'); expect(radio.meta.changedFields).toEqual([restored!.ref]); await doc.forms.setValue(textRef, { value: 'zzz'} ); const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type.startsWith('forms.')) events.push(event); } ); const both = await doc.forms.reset([radioRef, textRef]); unsubscribe(); expect(both.fields.map((field) => field.name)).toEqual(['maxlen_text']); const [text] = both.fields; if (text?.kind === 'text') expect(text.value).toBe(''); expect(events.map((event) => event.type)).toEqual(['forms.valueSet']); const again = await doc.forms.reset([radioRef, textRef]); expect(again.fields).toEqual([]); expect(again.meta.changedWidgets).toEqual([]); await expect(doc.forms.reset(toFieldRef('no.such.field'))).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); } finally{ await doc.close(); } } ); test('reset without refs resets the whole form as one change', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ await doc.forms.setValue(toFieldRef('ntto_radio'), { value: 'y'} ); await doc.forms.setValue(toFieldRef('billing.name'), { value: 'Ada'} ); const events: Extract[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type === 'forms.valueSet') events.push(event); } ); const result = await doc.forms.reset(); unsubscribe(); const names = result.fields.map((field) => field.name); expect(names).toContain('ntto_radio'); expect(names).toContain('billing.name'); expect(events.length).toBe(result.fields.length); const txIds = new Set(events.map((event) => event.origin.transaction?.id)); expect(txIds.size).toBe(1); expect(events.map((event) => event.origin.transaction?.index)).toEqual( events.map((_, i) => i), ); expect(events.every((event) => event.origin.transaction?.count === events.length)).toBe( true, ); const after = await doc.forms.list(); const radio = after.fields.find((field) => field.name === 'ntto_radio'); if (radio?.kind === 'radio') expect(radio.value).toBe('x'); } finally{ await doc.close(); } } ); test('emits form events on mutations', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type.startsWith('forms.')) events.push(event); } ); await doc.forms.setValue({ kind: 'fqn', name: 'maxlen_text'} , { value: 'ok'} ); unsubscribe(); expect(events.length).toBe(1); expect(events[0]!.type).toBe('forms.valueSet'); } finally{ await doc.close(); } } ); test('repair makes recovered fields durable and is idempotent', async () =>{ const doc = await open(options.fixtures.orphanWidgets); try{ const before = await doc.forms.list(); expect(before.fields.length).toBe(3); expect(before.fields.filter((f) => f.origin === 'recovered').length).toBe(2); const repair = await doc.forms.repair(); FormRepairResultSchema.parse(repair); expect(repair.fieldsLinked).toBe(2); expect(repair.acroformCreated).toBe(false); expect(repair.fieldsUnrepairable).toBe(0); const after = await doc.forms.list(); expect(after.fields.every((f) => f.origin === 'acroform')).toBe(true); const again = await doc.forms.repair(); expect(again.fieldsLinked).toBe(0); expect(again.widgetsLinked).toBe(0); } finally{ await doc.close(); } } ); test('widgets live the full form loop', async () =>{ const doc = await open(options.fixtures.toggleFields); const pageRef = toPageRef(options.fixtures.toggleFields.pageObjectNumber); const page = doc.page(pageRef); try{ const field = await doc.forms.create({ kind: 'text', name: 'loop_field'} ); expect(field.field.widgets).toEqual([]); const rect ={ x: 20, y: 20, width: 180, height: 24} ; const added = await doc.forms.addWidget(field.field.ref, { page: pageRef, rect, interiorColor: '#f6f8fa', color: '#1f6feb', strokeWidth: 1, fontSize: 10, } ); FormWidgetLinkResultSchema.parse(added); expect(added.widgets.map((widget) => widget.rect)).toEqual([rect]); expect(added.meta.changedWidgets.length).toBe(1); const widgetRef = added.field.widgets[0]?.ref; if (widgetRef?.kind !== 'objectNumber') throw new Error('expected durable ref'); const widgetRow = (await doc.forms.list()).widgets.find( (w) => annotationKey(w.ref) === annotationKey(widgetRef), ); if (!widgetRow) throw new Error('expected a widget row'); expect(widgetRow.field).toEqual(field.field.ref); expect(widgetRow.fieldKind).toBe('text'); expect(widgetRow.rect).toEqual(rect); expect(widgetRow.interiorColor).toEqual('#f6f8fa'); expect( (await page.annotations.list()).annotations.some((a) => a.subtype === 'widget'), ).toBe(false); const patched = await doc.forms.updateWidget(widgetRef, { interiorColor: '#fff7db', rect:{ ...rect, y: 40} , } ); expect(patched.widget.interiorColor).toEqual('#fff7db'); expect(patched.widget.rect).toEqual({ ...rect, y: 40} ); await expect( page.annotations.update(widgetRef, { subtype: 'widget', interiorColor: '#ffffff'} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await expect(page.annotations.delete(widgetRef)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const removed = await doc.forms.removeWidget(field.field.ref, widgetRef); expect(removed.widgets.map((w) => w.field)).toEqual([null]); const inert = (await doc.forms.list()).widgets.find( (w) => annotationKey(w.ref) === annotationKey(widgetRef), ); expect(inert?.field).toBeNull(); const after = await doc.forms.get(field.field.ref); expect(after.widgets.length).toBe(0); } finally{ await doc.close(); } } ); test('deleteWidget takes a widget off its page, and out of its field', async () =>{ const doc = await open(options.fixtures.toggleFields); const pageRef = toPageRef(options.fixtures.toggleFields.pageObjectNumber); const page = doc.page(pageRef); const events: DocumentEvent[] = []; const stop = doc.events.subscribe((event) => events.push(event)); try{ const created = await doc.forms.create({ kind: 'text', name: 'delete_me', widgets: [{ page: pageRef, rect:{ x: 20, y: 300, width: 120, height: 20} } , { page: pageRef, rect:{ x: 20, y: 330, width: 120, height: 20} } , ], } ); const [first, second] = created.field.widgets.map((w) => w.ref!) as [ AnnotationRef, AnnotationRef, ]; const onPage = async (ref: AnnotationRef) => (await doc.forms.list()).widgets.some((w) => annotationKey(w.ref) === annotationKey(ref)); const deleted = await doc.forms.deleteWidget(first); expect(annotationKey(deleted.widget)).toBe(annotationKey(first)); expect(deleted.page).toEqual(pageRef); expect(deleted.field?.widgets.map((w) => w.ref && annotationKey(w.ref))).toEqual([ annotationKey(second), ]); expect(await onPage(first)).toBe(false); expect(events.some((event) => event.type === 'forms.widgetDeleted')).toBe(true); await doc.forms.removeWidget(created.field.ref, second); const inert = await doc.forms.deleteWidget(second); expect(inert.field).toBeNull(); expect(await onPage(second)).toBe(false); expect((await doc.forms.get(created.field.ref)).widgets).toEqual([]); const merged = await doc.forms.get(toFieldRef('opt_check')); const mergedRefusal = await doc.forms.deleteWidget(merged.widgets[0]!.ref!).then( () => null, (error: unknown) => error as{ code?: unknown; message?: unknown} , ); expect(mergedRefusal).toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(String(mergedRefusal?.message)).toMatch(/doc\.forms\.delete/); const square = ( await page.annotations.create({ subtype: 'square', box:{ x: 300, y: 300, width: 40, height: 40} , } ) ).annotation.ref; const notWidget = await doc.forms.deleteWidget(square).then( () => null, (error: unknown) => error as{ code?: unknown; message?: unknown} , ); expect(notWidget).toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(String(notWidget?.message)).toMatch(/annotations\.delete/); } finally{ stop(); await doc.close(); } } ); test('widgets and annotations each keep their own stacking order', async () =>{ const doc = await open(options.fixtures.toggleFields); const pageRef = toPageRef(options.fixtures.toggleFields.pageObjectNumber); const page = doc.page(pageRef); const events: DocumentEvent[] = []; const stop = doc.events.subscribe((event) => events.push(event)); try{ const widgetOrder = async () => (await doc.forms.list()).widgets .filter((w) => w.page.objectNumber === pageRef.objectNumber) .map((w) => w.ref); const annotationOrder = async () => (await page.annotations.list()).annotations.map((a) => a.ref); const keys = (refs: readonly AnnotationRef[]) => refs.map(annotationKey); const square = ( await page.annotations.create({ subtype: 'square', box:{ x: 300, y: 300, width: 40, height: 40} , } ) ).annotation.ref; const widgets = await widgetOrder(); const annotations = await annotationOrder(); expect(widgets.length >= 2).toBe(true); const [bottom, next] = widgets as [AnnotationRef, AnnotationRef]; const toTop = await doc.forms.reorderWidgets([bottom], 'end'); FormWidgetsReorderResultSchema.parse(toTop); expect(toTop.page).toEqual(pageRef); expect(keys(toTop.order)).toEqual(keys([...widgets.slice(1), bottom])); expect(toTop.meta.changedWidgets.map((w) => w.ref && annotationKey(w.ref))).toEqual( keys([bottom]), ); expect(keys(await widgetOrder())).toEqual(keys(toTop.order)); expect(keys(await annotationOrder())).toEqual(keys(annotations)); const reordered = events.find((event) => event.type === 'forms.widgetsReordered'); expect(reordered?.type === 'forms.widgetsReordered' && keys(reordered.order)).toEqual( keys(toTop.order), ); const back = await doc.forms.reorderWidgets([bottom], { before: next} ); expect(keys(back.order)).toEqual(keys(widgets)); const toBottom = await page.annotations.reorder([square], 'start'); expect(keys(toBottom.order)).toEqual( keys([square, ...annotations.filter((a) => annotationKey(a) !== annotationKey(square))]), ); expect(keys(await widgetOrder())).toEqual(keys(widgets)); const refusal = (attempt: Promise) => attempt.then( () => null, (error: unknown) => error as{ code?: unknown; message?: unknown} , ); const widgetAsAnnotation = await refusal(page.annotations.reorder([bottom], 'start')); expect(widgetAsAnnotation).toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(String(widgetAsAnnotation?.message)).toMatch(/doc\.forms\.reorderWidgets/); await expect(page.annotations.reorder([square], { after: bottom} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const annotationAsWidget = await refusal(doc.forms.reorderWidgets([square], 'end')); expect(annotationAsWidget).toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(String(annotationAsWidget?.message)).toMatch(/annotations\.reorder/); await expect(doc.forms.reorderWidgets([bottom], { before: square} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); expect(keys(await widgetOrder())).toEqual(keys(widgets)); } finally{ stop(); await doc.close(); } } ); test('createField composes styled widgets atomically', async () =>{ const doc = await open(options.fixtures.toggleFields); const pageObjectNumber = options.fixtures.toggleFields.pageObjectNumber; try{ const created = await doc.forms.create({ kind: 'radio', name: 'authored_radio', noToggleToOff: true, widgets: [{ page: toPageRef(pageObjectNumber), rect:{ x: 20, y: 60, width: 20, height: 20} , exportValue: 'yes', color: '#000000', strokeWidth: 1, } , { page: toPageRef(pageObjectNumber), rect:{ x: 60, y: 60, width: 20, height: 20} , exportValue: 'no', } , ], } ); if (created.field.kind !== 'radio') throw new Error('expected radio'); expect(created.field.noToggleToOff).toBe(true); expect(created.field.widgets.map((w) => w.exportValue)).toEqual(['yes', 'no']); const rects = [{ x: 20, y: 60, width: 20, height: 20} , { x: 60, y: 60, width: 20, height: 20} , ]; expect(created.widgets.map((w) => w.rect)).toEqual(rects); const placed = (await doc.forms.list()).widgets; const rowOf = (ref: AnnotationRef | null) => placed.find((w) => ref && annotationKey(w.ref) === annotationKey(ref)); expect(created.field.widgets.map((w) => rowOf(w.ref)?.rect)).toEqual(rects); expect(rowOf(created.field.widgets[0]!.ref)?.color).toEqual('#000000'); const third = await doc.forms.addWidget(created.field.ref, { page: toPageRef(pageObjectNumber), rect:{ x: 100, y: 60, width: 20, height: 20} , exportValue: 'maybe', } ); if (third.field.kind !== 'radio') throw new Error('expected radio'); expect(third.field.widgets.map((w) => w.exportValue)).toEqual(['yes', 'no', 'maybe']); const countBefore = (await doc.forms.list()).widgets.length; await expect( doc.forms.addWidget(created.field.ref, { page: toPageRef(pageObjectNumber), rect:{ x: 140, y: 60, width: 20, height: 20} , } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const countAfter = (await doc.forms.list()).widgets.length; expect(countAfter).toBe(countBefore); expect((await doc.forms.get(created.field.ref)).widgets.length).toBe(3); const filled = await doc.forms.setValue(created.field.ref, { value: 'yes'} ); if (filled.field.kind !== 'radio') throw new Error('expected radio'); expect(filled.field.value).toBe('yes'); await doc.forms.update(created.field.ref, { name: 'renamed_radio'} ); await expect( doc.forms.update(created.field.ref, { name: 'unison_radio'} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await expect( doc.forms.update(created.field.ref, { multiline: true} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await expect( doc.forms.update(created.field.ref, { kind: 'text', name: 'x'} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const before = (await doc.forms.list()).widgets; const removed = await doc.forms.delete(created.field.ref); expect(Object.keys(removed)).toEqual(['meta']); expect(removed.meta.changedFields).toEqual([created.field.ref]); expect(removed.meta.changedWidgets.length).toBe(3); const after = (await doc.forms.list()).widgets; expect(after.length).toBe(before.length - 3); await expect(doc.forms.get({ kind: 'fqn', name: 'renamed_radio'} )).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); } finally{ await doc.close(); } } ); test("a widget's colour change keeps its font and size", async () =>{ const doc = await open(options.fixtures.toggleFields); const page = toPageRef(options.fixtures.toggleFields.pageObjectNumber); try{ const{ field} = await doc.forms.create({ kind: 'text', name: 'styled', widgets: [{ page, rect:{ x: 20, y: 160, width: 160, height: 24} , fontFamily: 'courier', fontSize: 9, } , ], } ); const widget = field.widgets[0]!.ref!; const{ widget: recoloured} = await doc.forms.updateWidget(widget, { fontColor: '#cc0000', } ); expect(recoloured).toMatchObject({ fontFamily: 'courier', fontSize: 9, fontColor: '#cc0000', } ); const{ widget: resized} = await doc.forms.updateWidget(widget, { fontSize: 11} ); expect(resized).toMatchObject({ fontFamily: 'courier', fontSize: 11, fontColor: '#cc0000', } ); const{ widget: refonted} = await doc.forms.updateWidget(widget, { fontFamily: 'times-roman', } ); expect(refonted).toMatchObject({ fontFamily: 'times-roman', fontSize: 11, fontColor: '#cc0000', } ); await expect(doc.forms.updateWidget(widget, { fontSize: null} )).rejects.toMatchObject({ code: 'InvalidArg', } ); } finally{ await doc.close(); } } ); test('a push button has a caption and an action, and holds no value', async () =>{ const doc = await open(options.fixtures.toggleFields); const page = toPageRef(options.fixtures.toggleFields.pageObjectNumber); try{ const{ field} = await doc.forms.create({ kind: 'pushbutton', name: 'clear', widgets: [{ page, rect:{ x: 20, y: 120, width: 120, height: 28} , caption: 'Clear form', interiorColor: '#f6f8fa', actions:{ activate:{ type: 'reset-form', fields: null, exclude: false} } , } , ], } ); expect(field.kind).toBe('pushbutton'); const widget = field.widgets[0]!.ref!; const rowOf = async (ref: AnnotationRef) => (await doc.forms.list()).widgets.find( (w) => annotationKey(w.ref) === annotationKey(ref), )!; let row = await rowOf(widget); expect(row).toMatchObject({ fieldKind: 'pushbutton', caption: 'Clear form', interiorColor: '#f6f8fa', hasAppearance: true, } ); expect(row.actions?.activate?.root?.type).toBe('reset-form'); await expect(doc.forms.setValue(field.ref, { value: 'x'} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); await doc.forms.update(field.ref, { alternateName: 'Clears every field'} ); await expect(doc.forms.update(field.ref, { multiline: true} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const moved = await doc.forms.updateWidget(widget, { rect:{ x: 30, y: 130, width: 120, height: 28} , } ); const restyled = await doc.forms.updateWidget(widget, { actions:{ focus:{ type: 'reset-form', fields: null, exclude: false} } , } ); const sentBack = await doc.forms.updateWidget(widget, { ...(await rowOf(widget))} ); expect([moved, restyled, sentBack].map((result) => result.appearance.action)).toEqual([ 'preserved', 'preserved', 'preserved', ]); const renamed = await doc.forms.updateWidget(widget, { caption: 'Start over'} ); expect(renamed.appearance.action).toBe('regenerated'); expect((await rowOf(widget)).caption).toBe('Start over'); await doc.apply({ undoOf: renamed.meta.opId} ); expect((await rowOf(widget)).caption).toBe('Clear form'); await doc.forms.updateWidget(widget, { caption: null} ); row = await rowOf(widget); expect([row.caption, row.hasAppearance]).toEqual([null, true]); const checkbox = (await doc.forms.list()).widgets.find((w) => w.fieldKind === 'checkbox')!; expect(checkbox.caption).toBeNull(); await doc.forms.updateWidget(checkbox.ref, { ...checkbox} ); await expect( doc.forms.updateWidget(checkbox.ref, { caption: 'Yes'} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await expect( doc.forms.create({ kind: 'text', name: 'captioned', widgets: [{ page, rect:{ x: 20, y: 160, width: 120, height: 20} , caption: 'x'} ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } finally{ await doc.close(); } } ); test('create is one change: a rejected draft creates nothing', async () =>{ const doc = await open(options.fixtures.toggleFields); const page = toPageRef(options.fixtures.toggleFields.pageObjectNumber); const names = async () => (await doc.forms.list()).fields.map((field) => field.name); const widgetCount = async () => (await doc.forms.list()).widgets.filter((w) => w.page.objectNumber === page.objectNumber) .length; try{ const namesBefore = await names(); const widgetsBefore = await widgetCount(); const placed ={ page, rect:{ x: 20, y: 100, width: 100, height: 20} } ; await expect( doc.forms.create({ kind: 'text', name: 'rejected_text', maxLength: -5, widgets: [placed], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await expect( doc.forms.create({ kind: 'text', name: 'rejected_text', widgets: [{ ...placed, page: toPageRef(999_999)} ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.NotFound} ); await expect( doc.forms.create({ kind: 'combobox', name: 'rejected_choice', options: [{ label: 'A', value: 'a'} ], defaultValue: 'not-an-option', widgets: [placed], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(await names()).toEqual(namesBefore); expect(await widgetCount()).toBe(widgetsBefore); const created = await doc.forms.create({ kind: 'text', name: 'rejected_text', widgets: [placed], } ); expect(created.field.name).toBe('rejected_text'); await doc.forms.delete(created.field.ref); } finally{ await doc.close(); } } ); test('flags, list box defaults and signature fields are written like any other member', async () =>{ const doc = await open(options.fixtures.toggleFields); const page = toPageRef(options.fixtures.toggleFields.pageObjectNumber); try{ const list = await doc.forms.create({ kind: 'listbox', name: 'defaults_list', multiSelect: true, options: [{ label: 'A', value: 'a'} , { label: 'B', value: 'b'} , { label: 'C', value: 'c'} , ], defaultValue: ['a', 'c'], required: true, widgets: [{ page, rect:{ x: 20, y: 140, width: 100, height: 60} } ], } ); if (list.field.kind !== 'listbox') throw new Error('expected listbox'); expect(list.field.defaultValue).toEqual(['a', 'c']); expect(list.field).toMatchObject({ readOnly: false, required: true, noExport: false} ); await expect( doc.forms.update(list.field.ref, { defaultValue: ['z']} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await doc.forms.update(list.field.ref, { defaultValue: ['b']} ); await doc.forms.setValue(list.field.ref, { selectedValues: ['a']} ); const reset = await doc.forms.reset(list.field.ref); const [restored] = reset.fields; if (restored?.kind !== 'listbox') throw new Error('expected listbox'); expect(restored.selectedValues).toEqual(['b']); await doc.forms.update(list.field.ref, { readOnly: true} ); expect(await doc.forms.get(list.field.ref)).toMatchObject({ readOnly: true, required: true, } ); await doc.forms.update(list.field.ref, { required: false} ); expect(await doc.forms.get(list.field.ref)).toMatchObject({ readOnly: true, required: false, } ); await expect( doc.forms.update(list.field.ref, { flags:{ required: true} } as never), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const signature = await doc.forms.create({ kind: 'signature', name: 'sign_here', widgets: [{ page, rect:{ x: 20, y: 220, width: 150, height: 40} } ], } ); await doc.forms.update(signature.field.ref, { name: 'signed_here', alternateName: 'Sign here', required: true, } ); const renamed = await doc.forms.get(signature.field.ref); expect(renamed.kind).toBe('signature'); expect(renamed.name).toBe('signed_here'); expect(renamed.alternateName).toBe('Sign here'); expect(renamed.required).toBe(true); await expect( doc.forms.update(signature.field.ref, { multiline: true} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); await doc.forms.delete(list.field.ref); await doc.forms.delete(signature.field.ref); } finally{ await doc.close(); } } ); test('delete removes a merged field/widget from the tree and its page in one mutation', async () =>{ const doc = options.fixtures.deleteTarget ? await open(options.fixtures.deleteTarget) : await open(options.fixtures.toggleFields, '-delete-target'); const placed = async () => (await doc.forms.list()).widgets.flatMap((w) => w.ref.kind === 'objectNumber' ? [w.ref.objectNumber] : [], ); try{ const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) => events.push(event)); for (const name of ['maxlen_text', 'billing.name']){ const field = await doc.forms.get(toFieldRef(name)); if (field.ref.kind !== 'objectNumber') throw new Error('expected an object-number ref'); const merged = field.ref.objectNumber; expect(field.widgets.map((w) => w.objectNumber)).toEqual([merged]); expect(await placed()).toContain(merged); const removed = await doc.forms.delete(field.ref); expect(removed.meta.changedFields).toEqual([field.ref]); expect(removed.meta.changedWidgets.map((w) => w.objectNumber)).toEqual([merged]); expect((await placed()).includes(merged)).toBe(false); await expect(doc.forms.get(toFieldRef(name))).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); } unsubscribe(); expect(events.map((event) => event.type)).toEqual(['forms.deleted', 'forms.deleted']); const names = (await doc.forms.list()).fields.map((f) => f.name); expect(names.includes('maxlen_text') || names.includes('billing.name')).toBe(false); expect(names).toContain('opt_check'); } finally{ await doc.close(); } } ); test('a merged field/widget cannot be removed from its field or deleted as an annotation', async () =>{ const doc = await open(options.fixtures.toggleFields); const page = doc.page(toPageRef(options.fixtures.toggleFields.pageObjectNumber)); try{ const field = await doc.forms.get(toFieldRef('opt_check')); const widgetRef = field.widgets[0]?.ref; if (field.ref.kind !== 'objectNumber' || widgetRef?.kind !== 'objectNumber'){ throw new Error('expected object-number refs'); } expect(widgetRef.objectNumber).toBe(field.ref.objectNumber); const detach = await doc.forms.removeWidget(field.ref, widgetRef).then( () => null, (error: unknown) => error as{ code?: unknown; message?: unknown} , ); expect(detach).toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(String(detach?.message)).toMatch(/merged field\/widget/); const remove = await page.annotations.delete(widgetRef).then( () => null, (error: unknown) => error as{ code?: unknown; message?: unknown} , ); expect(remove).toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(String(remove?.message)).toMatch(/doc\.forms\.delete/); expect(String(remove?.message).includes('removeWidget')).toBe(false); const after = await doc.forms.get(field.ref); expect(after.widgets.map((w) => w.objectNumber)).toEqual([widgetRef.objectNumber]); const{ widgets} = await doc.forms.list(); expect( widgets.some( (w) => w.ref.kind === 'objectNumber' && w.ref.objectNumber === widgetRef.objectNumber, ), ).toBe(true); } finally{ await doc.close(); } } ); test('unknown refs fail with NotFound', async () =>{ const doc = await open(options.fixtures.toggleFields); try{ await expect(doc.forms.get({ kind: 'fqn', name: 'no.such.field'} )).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); } finally{ await doc.close(); } } ); } ); } runFormCopyConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFormCopyConformance.ts): export function runFormCopyConformance( runner: ConformanceTestRunner, options: AnnotationResourceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`form copy conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDocument = async ( run: (doc: DocumentHandle, page: PageRef, other: PageRef) => Promise, ): Promise =>{ const doc = await options.open(engine, 'authoring'); try{ const{ pages} = await doc.pages.list(); const page = toPageRef(pages[0]!.ref.objectNumber); const{ insertedPages} = await doc.pages.insertBlank({ size:{ width: 300, height: 500} } , { after: page} , ); await run(doc, page, insertedPages[0]!); } finally{ await doc.close(); } } ; const rect = (x: number, y = 100) => ({ x, y, width: 120, height: 20} ); const OFFSET ={ x: 12, y: 18} ; const rowsOf = async (doc: DocumentHandle, field: FormField): Promise =>{ const{ widgets} = await doc.forms.list(); const byKey = new Map(widgets.map((row) => [annotationKey(row.ref), row])); return field.widgets.map((widget) => byKey.get(annotationKey(widget.ref!))!); } ; const namesOf = async (doc: DocumentHandle): Promise => (await doc.forms.list()).fields.map((field) => field.name); const numberOf = (ref: FormFieldRef): number | null => ref.kind === 'objectNumber' ? ref.objectNumber : null; test('a copy is a new field, named after its source, with its settings, value and look, moved', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'email', required: true, maxLength: 40, alternateName: 'Your email address', widgets: [{ page, rect: rect(40), color: '#1d4ed8', strokeWidth: 2, fontSize: 11} ], } ); await doc.forms.setValue(field.ref, { value: 'ada@example.com'} ); const [source] = await rowsOf(doc, field); const result = await doc.forms.copy([field.ref], { offset: OFFSET} ); expect(result.dropped).toEqual([]); expect(result.fields.length).toBe(1); const copy = result.fields[0]!; expect(result.refMap).toEqual([{ from: field.ref, to: copy.ref} ]); expect(copy).toMatchObject({ kind: 'text', name: 'email_2', required: true, maxLength: 40, alternateName: 'Your email address', value: 'ada@example.com', } ); expect(copy.widgets.length).toBe(1); const [row] = await rowsOf(doc, copy); expect(result.widgets).toEqual([row]); expect(row).toMatchObject({ page, rect:{ ...source!.rect, x: source!.rect.x + OFFSET.x, y: source!.rect.y + OFFSET.y} , color: source!.color, strokeWidth: source!.strokeWidth, fontSize: source!.fontSize, borderStyle: source!.borderStyle, } ); expect(await doc.forms.get(copy.ref)).toEqual(copy); expect(await namesOf(doc)).toEqual(['email', 'email_2']); } ); } ); test('names count up from the source’s, and a copy stays in its group', async () =>{ await withDocument(async (doc, page) =>{ const widgets = [{ page, rect: rect(40)} ]; const first = (await doc.forms.create({ kind: 'text', name: 'text_1', widgets} )).field; const grouped = (await doc.forms.create({ kind: 'text', name: 'billing.name', widgets} )) .field; const once = await doc.forms.copy([first.ref]); expect(once.fields.map((field) => field.name)).toEqual(['text_2']); const again = await doc.forms.copy([first.ref, once.fields[0]!.ref]); expect(again.fields.map((field) => field.name)).toEqual(['text_3', 'text_4']); const twice = await doc.forms.copy([grouped.ref, grouped.ref]); expect(twice.fields.map((field) => field.name)).toEqual([ 'billing.name_2', 'billing.name_3', ]); expect(twice.refMap.map((pair) => pair.from)).toEqual([grouped.ref, grouped.ref]); } ); } ); test('values: false gives a copy no value, and it keeps its default', async () =>{ await withDocument(async (doc, page) =>{ const widgets = [{ page, rect: rect(40)} ]; const plain = (await doc.forms.create({ kind: 'text', name: 'plain', widgets} )).field; const preset = ( await doc.forms.create({ kind: 'text', name: 'preset', defaultValue: 'n/a', widgets} ) ).field; await doc.forms.setValue(plain.ref, { value: 'filled'} ); await doc.forms.setValue(preset.ref, { value: 'filled'} ); const result = await doc.forms.copy([plain.ref, preset.ref], { values: false} ); expect( result.fields.map((field) => field.kind === 'text' && [field.value, field.defaultValue]), ).toEqual([ ['', ''], ['', 'n/a'], ]); } ); } ); test('a radio group’s copy keeps its buttons and their values', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'radio', name: 'plan', widgets: [{ page, rect:{ x: 40, y: 100, width: 16, height: 16} , exportValue: 'monthly'} , { page, rect:{ x: 40, y: 130, width: 16, height: 16} , exportValue: 'yearly'} , ], } ); await doc.forms.setValue(field.ref, { value: 'yearly'} ); const result = await doc.forms.copy([field.ref], { offset: OFFSET} ); const copy = result.fields[0]!; expect(copy).toMatchObject({ kind: 'radio', name: 'plan_2', value: 'yearly'} ); expect( copy.kind === 'radio' && copy.widgets.map((widget) => [widget.exportValue, widget.checked]), ).toEqual([ ['monthly', false], ['yearly', true], ]); expect(await doc.forms.get(field.ref)).toMatchObject({ value: 'yearly'} ); } ); } ); test('widgets names the widgets to copy, and a widget keeps its flags', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'reference', widgets: [{ page, rect: rect(40, 100)} , { page, rect: rect(40, 140)} , ], } ); const other = ( await doc.forms.create({ kind: 'text', name: 'other', widgets: [{ page, rect: rect(40, 200)} ], } ) ).field; const [, second] = await rowsOf(doc, field); await doc.forms.updateWidget(second!.ref, { locked: true, print: false} ); const before = await namesOf(doc); const result = await doc.forms.copy([field.ref], { widgets: [second!.ref], offset: OFFSET, } ); const [row, ...rest] = await rowsOf(doc, result.fields[0]!); expect(rest).toEqual([]); expect(row).toMatchObject({ rect:{ ...second!.rect, x: second!.rect.x + OFFSET.x, y: second!.rect.y + OFFSET.y} , locked: true, print: false, } ); const [foreign] = await rowsOf(doc, other); await expect( doc.forms.copy([field.ref], { widgets: [foreign!.ref]} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); expect(await namesOf(doc)).toEqual([...before, 'reference_2']); } ); } ); test('onto another page: the same spot from that page’s top-left', async () =>{ await withDocument(async (doc, page, other) =>{ const{ field} = await doc.forms.create({ kind: 'checkbox', name: 'agree', widgets: [{ page, rect:{ x: 40, y: 100, width: 16, height: 16} } ], } ); const [source] = await rowsOf(doc, field); const result = await doc.forms.copy([field.ref], { page: other} ); const [row] = await rowsOf(doc, result.fields[0]!); expect(row).toMatchObject({ page: other, rect: source!.rect} ); expect(result.fields[0]).toMatchObject({ kind: 'checkbox', name: 'agree_2'} ); } ); } ); test('a copy keeps its script, and joins the calculation order after its source', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'total', actions:{ calculate:{ type: 'javascript', script: 'event.value = 1; '} } , widgets: [{ page, rect: rect(40)} ], } ); const result = await doc.forms.copy([field.ref], { offset: OFFSET} ); const copy = result.fields[0]!; expect(result.dropped).toEqual([]); expect(copy.actions?.calculate).toEqual(field.actions?.calculate); expect(result.calculationOrder).toEqual([field.ref, copy.ref]); } ); } ); test('takes the object numbers it is given', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'numbered', widgets: [{ page, rect: rect(40)} ], } ); await doc.objectNumbers.reserve(2); const numbers = [doc.objectNumbers.take()!, doc.objectNumbers.take()!]; const result = await doc.forms.copy([field.ref], { objectNumbers: numbers} ); const copy = result.fields[0]!; expect([numberOf(copy.ref), copy.widgets[0]!.objectNumber]).toEqual(numbers); await doc.objectNumbers.reserve(1); await expect( doc.forms.copy([field.ref], { objectNumbers: [doc.objectNumbers.take()!]} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } ); } ); test('emits one forms.created per field, as one transaction', async () =>{ await withDocument(async (doc, page) =>{ const widgets = [{ page, rect: rect(40)} ]; const refs = [ (await doc.forms.create({ kind: 'text', name: 'one', widgets} )).field.ref, (await doc.forms.create({ kind: 'text', name: 'two', widgets} )).field.ref, ]; const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const result = await doc.forms.copy(refs, { offset: OFFSET, opId: 'copy-1'} ); expect(result.meta).toMatchObject({ opId: 'copy-1', undoable: true} ); expect(events.map((event) => event.type)).toEqual(['forms.created', 'forms.created']); events.forEach((event, index) =>{ expect('origin' in event && event.origin.transaction).toEqual({ id: 'copy-1', index, count: 2, } ); expect(event.type === 'forms.created' && event.field).toEqual(result.fields[index]); } ); } ); } ); test('is undone and redone, under the same names', async () =>{ await withDocument(async (doc, page) =>{ const widgets = [{ page, rect: rect(40)} ]; const refs = [ (await doc.forms.create({ kind: 'text', name: 'one', widgets} )).field.ref, (await doc.forms.create({ kind: 'checkbox', name: 'two', widgets} )).field.ref, ]; const before = await doc.forms.list(); const copied = await doc.forms.copy(refs, { offset: OFFSET} ); const after = await doc.forms.list(); expect(after.fields.map((field) => field.name)).toEqual(['one', 'two', 'one_2', 'two_2']); const undo = await doc.apply({ undoOf: copied.meta.opId} ); expect(await doc.forms.list()).toEqual(before); await doc.apply({ undoOf: undo.meta.opId} ); expect(await doc.forms.list()).toEqual(after); } ); } ); test('refuses before anything is written', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'kept', widgets: [{ page, rect: rect(40)} ], } ); const before = await doc.forms.list(); await expect( doc.forms.copy([field.ref, { kind: 'fqn', name: 'missing'} ]), ).rejects.toMatchObject({ code: EngineErrorCode.NotFound} ); await expect(doc.forms.copy([field.ref], { page: toPageRef(9999)} )).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); expect(await doc.forms.list()).toEqual(before); } ); } ); test('a copy of more fields than a bundle holds items is refused, and writes nothing', async () =>{ await withDocument(async (doc, page) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'many', widgets: [{ page, rect: rect(40)} ], } ); const before = await doc.forms.list(); const max = DEFAULT_BUNDLE_LIMITS.items; const fields = Array.from({ length: max + 1} , () => field.ref); await expect(doc.forms.copy(fields)).rejects.toMatchObject({ code: EngineErrorCode.PayloadTooLarge, details:{ limit: 'items', max, value: max + 1} , } ); expect(await doc.forms.list()).toEqual(before); } ); } ); test('needs doc.forms.modify', async () =>{ if (!options.openScoped) return; const filler = await options.openScoped(engine, 'authoring', [ 'doc.open', 'doc.render', 'doc.forms.fill', ]); try{ const refused = await filler.forms.copy([{ kind: 'fqn', name: 'any'} ]).then( () => null, (error: unknown) => error, ); expect(isPermissionRefusal(refused)).toBe(true); } finally{ await filler.close(); } } ); } ); } runFormPredictionConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFormPredictionConformance.ts): export function runFormPredictionConformance( runner: ConformanceTestRunner, options: FormPredictionConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`form prediction conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; let page: PageRef; let named = 0; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine); const{ pages} = await doc.pages.list(); page = toPageRef(pages[0]!.ref.objectNumber); } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); const read = async (ref: FormFieldRef): Promise =>{ const snapshot = await doc.forms.list(); const field = snapshot.fields.find((candidate) => sameRef(candidate.ref, ref)); if (!field) throw new Error(`no field ${ JSON.stringify(ref)} `); return{ field, widgets: rowsOf(field, snapshot.widgets)} ; } ; const run = async (ref: FormFieldRef, op: FormOp): Promise =>{ switch (op.type){ case 'setValue': await doc.forms.setValue(ref, op.value); return; case 'reset': await doc.forms.reset([ref]); return; case 'display': await doc.apply({ ops: [{ type: 'forms.setDisplay', field: ref, display: op.display} ]} ); return; case 'update': await doc.forms.update(ref, op.patch); return; case 'updateWidget':{ const widget = (await read(ref)).widgets[0]!; await doc.forms.updateWidget(widget.ref, op.patch); return; } } } ; const predict = (current: FieldWithWidgets, op: FormOp): FieldWithWidgets =>{ switch (op.type){ case 'setValue': return fieldAfterValue(current, op.value); case 'reset': return fieldAfterReset(current); case 'display': return{ ...current, widgets: widgetsAfterDisplay(current.widgets, op.display)} ; case 'update': return formFieldAfter(current, op.patch); case 'updateWidget': return{ ...current, widgets: current.widgets.map((row, at) => at === 0 ? widgetAfterPatch(row, op.patch) : row, ), } ; } } ; for (const scenario of CREATES){ test(`create: ${ scenario.name} `, async () =>{ const draft = scenario.draft(page, `created_${ named++} `); const{ field: created} = await doc.forms.create(draft); const actual = await read(created.ref); const predicted = formFieldOfDraft(draft, { objectNumber: created.ref.kind === 'objectNumber' ? created.ref.objectNumber : 0, widgets: actual.widgets.map((row) => row.ref as AnnotationRef), widgetNames: actual.widgets.map((row) => row.nm ?? ''), groupId: actual.field.groupId, createdBy: actual.field.createdBy, createdAt: actual.field.createdAt, } ); expect(differences(predicted, actual)).toEqual([]); } ); } for (const scenario of REFUSALS){ test(`refused: ${ scenario.name} `, async () =>{ const{ field: created} = await doc.forms.create(scenario.draft(page, `field_${ named++} `)); for (const op of scenario.before ?? []) await run(created.ref, op); const current = await read(created.ref); const predicted = codeOf(() => predict(current, scenario.op)); const actual = await run(created.ref, scenario.op).then( () => 'applied', (error: unknown) => (error as{ code?: string} ).code ?? 'unknown', ); expect(predicted).toBe(actual); expect(actual === 'applied').toBe(false); } ); } for (const scenario of CASES){ test(scenario.name, async () =>{ const{ field: created} = await doc.forms.create(scenario.draft(page, `field_${ named++} `)); for (const op of scenario.before ?? []) await run(created.ref, op); const current = await read(created.ref); const predicted = predict(current, scenario.op); await run(created.ref, scenario.op); const actual = await read(created.ref); expect(differences(predicted, actual)).toEqual([]); } ); } } ); } runFormScriptConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFormScriptConformance.ts): export function runFormScriptConformance( runner: ConformanceTestRunner, options: FormScriptConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`form script conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDoc = async ( body: (doc: DocumentHandle) => Promise, scope: readonly string[] = EVERYTHING, ) =>{ const doc = await options.open(engine, scope); try{ await body(doc); } finally{ await doc.close(); } } ; const fieldOf = async (doc: DocumentHandle, name: string): Promise =>{ const field = (await doc.forms.list()).fields.find((f) => f.name === name); if (!field) throw new Error(`no field '${ name} '`); return field; } ; const scriptOf = ( field: FormField, event: 'keystroke' | 'format' | 'validate' | 'calculate', ) =>{ const root = field.actions?.[event]?.root; return root?.type === 'javascript' ? root.script : null; } ; const orderOf = async (doc: DocumentHandle): Promise =>{ const{ fields, calculationOrder} = await doc.forms.list(); return calculationOrder.map((ref) =>{ const field = ref && fields.find((f) => JSON.stringify(f.ref) === JSON.stringify(ref)); return field ? field.name : '?'; } ); } ; const createCalculated = async (doc: DocumentHandle, name: string) => doc.forms.create({ kind: 'text', name, actions:{ calculate: CALCULATE} } ); const outcome = (attempt: Promise) => attempt.then( () => 'resolved', (error: unknown) => (EngineError.is(error) ? error.code : String(error)), ); test("create writes a field's scripts; a calculate script puts it in the order", async () =>{ await withDoc(async (doc) =>{ const created = await doc.forms.create({ kind: 'text', name: 'total', readOnly: true, actions:{ calculate: CALCULATE, format:{ ...script('AFNumber_Format(2, 0, 0, 0, "", true); '), next: [script('x = 1; ')], } , } , } ); expect(scriptOf(created.field, 'calculate')).toBe('event.value = 1; '); expect(created.calculationOrder?.map((ref) => ref.kind)).toEqual(['objectNumber']); const total = await fieldOf(doc, 'total'); expect(scriptOf(total, 'format')).toBe('AFNumber_Format(2, 0, 0, 0, "", true); '); expect(total.actions?.format?.root?.next.map((n) => n.type)).toEqual(['javascript']); expect(scriptOf(total, 'keystroke')).toBe(null); expect(await orderOf(doc)).toEqual(['total']); } ); } ); test('update sets, replaces and removes scripts; an event left out keeps its own', async () =>{ await withDoc(async (doc) =>{ await doc.forms.update(NAME, { actions:{ format: script('a(); ')} } ); await doc.forms.update(NAME, { actions:{ format: script('b(); '), validate: script('c(); ')} , } ); let name = await fieldOf(doc, 'name'); expect([scriptOf(name, 'format'), scriptOf(name, 'validate')]).toEqual(['b(); ', 'c(); ']); await doc.forms.update(NAME, { actions:{ format: null} } ); name = await fieldOf(doc, 'name'); expect([scriptOf(name, 'format'), scriptOf(name, 'validate')]).toEqual([null, 'c(); ']); expect(await orderOf(doc)).toEqual([]); } ); } ); test('the order follows the calculate scripts: added at the end, gone with the script or the field', async () =>{ await withDoc(async (doc) =>{ await createCalculated(doc, 'a'); await createCalculated(doc, 'b'); const updated = await doc.forms.update(NAME, { actions:{ calculate: CALCULATE} } ); expect(updated.calculationOrder?.length).toBe(3); expect(await orderOf(doc)).toEqual(['a', 'b', 'name']); await doc.forms.update(NAME, { actions:{ calculate: null} } ); expect(await orderOf(doc)).toEqual(['a', 'b']); const deleted = await doc.forms.delete({ kind: 'fqn', name: 'a'} ); expect(deleted.calculationOrder?.length).toBe(1); expect(await orderOf(doc)).toEqual(['b']); } ); } ); test('reorderCalculations moves fields by neighbour and publishes the whole order', async () =>{ await withDoc(async (doc) =>{ const a = (await createCalculated(doc, 'a')).field.ref; await createCalculated(doc, 'b'); const c = (await createCalculated(doc, 'c')).field.ref; const heard: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) => heard.push(event)); try{ const moved = await doc.forms.reorderCalculations([c], { before: a} ); expect(moved.calculationOrder.length).toBe(3); expect(await orderOf(doc)).toEqual(['c', 'a', 'b']); expect(heard.some((event) => event.type === 'forms.calculationsReordered')).toBe(true); await doc.forms.reorderCalculations([a], 'end'); expect(await orderOf(doc)).toEqual(['c', 'b', 'a']); } finally{ unsubscribe(); } expect(await outcome(doc.forms.reorderCalculations([NAME], 'start'))).toBe( EngineErrorCode.NotFound, ); expect(await outcome(doc.forms.reorderCalculations([a], { after: a} ))).toBe( EngineErrorCode.InvalidArg, ); } ); } ); test('undo puts the scripts and the order back; redo does them again', async () =>{ await withDoc(async (doc) =>{ await createCalculated(doc, 'a'); const b = (await createCalculated(doc, 'b')).field.ref; const scripted = await doc.forms.update(NAME, { actions:{ calculate: CALCULATE, format: script('f(); ')} , } ); expect(await orderOf(doc)).toEqual(['a', 'b', 'name']); const undo = await doc.apply({ undoOf: scripted.meta.opId} ); let name = await fieldOf(doc, 'name'); expect([scriptOf(name, 'calculate'), scriptOf(name, 'format')]).toEqual([null, null]); expect(await orderOf(doc)).toEqual(['a', 'b']); await doc.apply({ undoOf: undo.meta.opId} ); name = await fieldOf(doc, 'name'); expect(scriptOf(name, 'format')).toBe('f(); '); expect(await orderOf(doc)).toEqual(['a', 'b', 'name']); const moved = await doc.forms.reorderCalculations([NAME], { before: b} ); expect(await orderOf(doc)).toEqual(['a', 'name', 'b']); await doc.apply({ undoOf: moved.meta.opId} ); expect(await orderOf(doc)).toEqual(['a', 'b', 'name']); const deleted = await doc.forms.delete({ kind: 'fqn', name: 'a'} ); expect(await orderOf(doc)).toEqual(['b', 'name']); await doc.apply({ undoOf: deleted.meta.opId} ); expect(await orderOf(doc)).toEqual(['a', 'b', 'name']); } ); } ); test('a field event takes JavaScript only', async () =>{ await withDoc(async (doc) =>{ const notAScript ={ type: 'uri', uri: 'https://example.com', } as unknown as FieldScriptWrite; expect(await outcome(doc.forms.update(NAME, { actions:{ format: notAScript} } ))).toBe( EngineErrorCode.InvalidArg, ); expect(scriptOf(await fieldOf(doc, 'name'), 'format')).toBe(null); } ); } ); const rowOf = async (doc: DocumentHandle, ref: AnnotationRef) =>{ const row = (await doc.forms.list()).widgets.find( (w) => JSON.stringify(w.ref) === JSON.stringify(ref), ); if (!row) throw new Error('no widget row'); return row; } ; const actionType = (row:{ actions: unknown} , event: string) => ((row.actions as Record | null)?.[event]?.root?.type ?? null) as string | null; test("a widget's actions are written with its placement and read back from its row", async () =>{ await withDoc(async (doc) =>{ const{ field} = await doc.forms.create({ kind: 'text', name: 'clearing', widgets: [{ page: PAGE, rect:{ x: 20, y: 200, width: 120, height: 24} , actions:{ activate: RESET, focus: script('focused(); ')} , } , ], } ); const [first] = field.widgets; const row = await rowOf(doc, first!.ref!); expect(actionType(row, 'activate')).toBe('reset-form'); expect(actionType(row, 'focus')).toBe('javascript'); const added = await doc.forms.addWidget(field.ref, { page: PAGE, rect:{ x: 20, y: 240, width: 120, height: 24} , actions:{ blur: script('blurred(); ')} , } ); const second = added.field.widgets.find((w) => w.objectNumber !== first!.objectNumber)!; expect(actionType(await rowOf(doc, second.ref!), 'blur')).toBe('javascript'); } ); } ); test('updateWidget sets, replaces and removes actions; a read sent back keeps them', async () =>{ await withDoc(async (doc) =>{ await doc.forms.update(NAME, { actions:{ calculate: CALCULATE} } ); await doc.forms.updateWidget(WIDGET, { actions:{ activate:{ type: 'goto', destination:{ kind: 'xyz', page: PAGE, x: 10, y: 20, zoom: null} , } , mouseUp: script('up(); '), } , } ); let row = await rowOf(doc, WIDGET); expect(actionType(row, 'activate')).toBe('goto'); const goto = row.actions?.activate?.root; expect(goto?.type === 'goto' && goto.destination.kind === 'xyz' && goto.destination.x).toBe( 10, ); expect(scriptOf(await fieldOf(doc, 'name'), 'calculate')).toBe('event.value = 1; '); await doc.forms.updateWidget(WIDGET, { actions: row.actions, interiorColor: '#eeeeee'} ); row = await rowOf(doc, WIDGET); expect(actionType(row, 'mouseUp')).toBe('javascript'); await doc.forms.updateWidget(WIDGET, { actions:{ activate: RESET, mouseUp: null} } ); row = await rowOf(doc, WIDGET); expect([actionType(row, 'activate'), actionType(row, 'mouseUp')]).toEqual([ 'reset-form', null, ]); } ); } ); test("undo puts a widget's actions back", async () =>{ await withDoc(async (doc) =>{ await doc.forms.updateWidget(WIDGET, { actions:{ activate: RESET} } ); const changed = await doc.forms.updateWidget(WIDGET, { actions:{ activate: script('a(); '), focus: script('f(); ')} , } ); await doc.apply({ undoOf: changed.meta.opId} ); const row = await rowOf(doc, WIDGET); expect([actionType(row, 'activate'), actionType(row, 'focus')]).toEqual([ 'reset-form', null, ]); } ); } ); test('a widget action that only changes the view needs doc.forms.modify alone', async () =>{ await withDoc(async (doc) =>{ await doc.forms.updateWidget(WIDGET, { actions:{ activate: RESET} } ); const scripted = [ script('x(); '), { type: 'uri', uri: 'https://example.com'} as PdfActionWrite, { type: 'submit-form', url: 'https://example.com/in', fields: null} as PdfActionWrite, { ...RESET, next: [script('then(); ')]} as PdfActionWrite, ]; for (const action of scripted){ expect( await outcome(doc.forms.updateWidget(WIDGET, { actions:{ activate: action} } )), ).toBe(EngineErrorCode.Forbidden); } expect( await outcome( doc.forms.create({ kind: 'text', name: 'y', widgets: [{ page: PAGE, rect:{ x: 20, y: 300, width: 80, height: 20} , actions:{ activate: script('y(); ')} , } , ], } ), ), ).toBe(EngineErrorCode.Forbidden); expect( await outcome( doc.forms.addWidget(NAME, { page: PAGE, rect:{ x: 20, y: 340, width: 80, height: 20} , actions:{ blur: script('b(); ')} , } ), ), ).toBe(EngineErrorCode.Forbidden); expect( await outcome( doc.apply({ ops: [{ type: 'forms.updateWidget', widget: WIDGET, patch:{ actions:{ focus: script('f(); ')} } , } , ], } ), ), ).toBe(EngineErrorCode.Forbidden); } , DESIGN_ONLY); } ); test('writing a script takes doc.forms.script; removing one does not', async () =>{ await withDoc(async (doc) =>{ await doc.forms.update(NAME, { actions:{ format: script('f(); ')} } ); } ); await withDoc(async (doc) =>{ expect(doc.security.allows('doc.forms.script')).toBe(false); const refused = [ await outcome(doc.forms.update(NAME, { actions:{ format: script('f(); ')} } )), await outcome( doc.forms.create({ kind: 'text', name: 'x', actions:{ calculate: CALCULATE} } ), ), await outcome( doc.apply({ ops: [{ type: 'forms.update', field: NAME, patch:{ actions:{ validate: script('v(); ')} } , } , ], } ), ), ]; expect(refused.every((code) => code === EngineErrorCode.Forbidden)).toBe(true); await doc.forms.create({ kind: 'text', name: 'plain'} ); await doc.forms.update(NAME, { actions:{ format: null} } ); } , DESIGN_ONLY); } ); } ); } runFormTransferConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runFormTransferConformance.ts): export function runFormTransferConformance( runner: ConformanceTestRunner, options: FormTransferConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`form transfer conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const open = ( identity: Identity, scope: readonly string[] = EVERYTHING, bytes: Uint8Array = TWO_PAGES_PDF, ) => options.openAs(engine, { scope, identity} , bytes.slice()); const using = async ( body: (opened: (doc: Promise) => Promise) => Promise, ) =>{ const docs: DocumentHandle[] = []; try{ await body(async (doc) =>{ const handle = await doc; docs.push(handle); return handle; } ); } finally{ for (const doc of docs) await doc.close(); } } ; const build = async (doc: DocumentHandle) =>{ const{ forms} = doc; await forms.create({ kind: 'text', name: 'customer.name', maxLength: 40, actions:{ validate: script('validated(); ')} , widgets: [{ page: FIRST, rect: wide(240)} ], } ); await forms.setValue(fqn('customer.name'), { value: 'Ada'} ); await forms.create({ kind: 'checkbox', name: 'agree', widgets: [{ page: FIRST, rect: small(20, 200), exportValue: 'Yes'} ], } ); await forms.setValue(fqn('agree'), { checked: true} ); await forms.create({ kind: 'radio', name: 'plan', widgets: [{ page: FIRST, rect: small(20, 160), exportValue: 'basic'} , { page: SECOND, rect: small(20, 160), exportValue: 'pro'} , ], } ); await forms.setValue(fqn('plan'), { value: 'pro'} ); await forms.create({ kind: 'combobox', name: 'country', options: [{ label: 'Netherlands', value: 'NL'} , { label: 'Belgium', value: 'BE'} , ], widgets: [{ page: SECOND, rect: wide(240)} ], } ); await forms.setValue(fqn('country'), { value: 'BE'} ); await forms.create({ kind: 'listbox', name: 'tags', multiSelect: true, options: [{ label: 'A', value: 'a'} , { label: 'B', value: 'b'} , { label: 'C', value: 'c'} , ], widgets: [{ page: SECOND, rect:{ x: 20, y: 120, width: 80, height: 60} } ], } ); await forms.setValue(fqn('tags'), { selectedValues: ['a', 'c']} ); await forms.create({ kind: 'pushbutton', name: 'go', widgets: [{ page: SECOND, rect:{ x: 200, y: 240, width: 60, height: 24} , caption: 'Go', actions:{ activate:{ type: 'uri', uri: 'https://example.com'} } , } , ], } ); await forms.create({ kind: 'signature', name: 'sign', widgets: [{ page: SECOND, rect:{ x: 200, y: 20, width: 80, height: 40} } ], } ); await forms.create({ kind: 'text', name: 'subtotal', actions:{ calculate: script('event.value = 1; ')} , widgets: [{ page: FIRST, rect: wide(100)} ], } ); await forms.create({ kind: 'text', name: 'total', actions:{ calculate: script('event.value = 2; ')} , widgets: [{ page: FIRST, rect: wide(60)} ], } ); await forms.reorderCalculations([fqn('total')], 'start'); } ; const sourceBundle = async ( opened: (doc: Promise) => Promise, ) =>{ const source = await opened(open(ALICE)); await build(source); return source.forms.export(); } ; const fieldOf = async (doc: DocumentHandle, name: string): Promise =>{ const field = (await doc.forms.list()).fields.find((f) => f.name === name); if (!field) throw new Error(`no field '${ name} '`); return field; } ; const namesOf = async (doc: DocumentHandle) => (await doc.forms.list()).fields.map((field) => field.name); const orderOf = async (doc: DocumentHandle): Promise =>{ const{ fields, calculationOrder} = await doc.forms.list(); return calculationOrder.map((ref) =>{ const field = ref && fields.find((f) => encodeFieldRefKey(f.ref) === encodeFieldRefKey(ref)); return field ? field.name : '?'; } ); } ; const refusalOf = (attempt: Promise) => attempt.then( () => null, (error: unknown) => error, ); test('a design import copies every field: the copy exports as its source', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); expect(bundle.fields.map(({ data} ) => data.name)).toEqual(SOURCE_FIELDS); const target = await opened(open(ALICE)); const result = await target.forms.import(bundle); expect(result.dropped).toEqual([]); expect(result.meta.undoable).toBe(true); expect(result.fields.map((field) => field.name)).toEqual(SOURCE_FIELDS); expect(result.refMap.map(({ from} ) => from)).toEqual( bundle.fields.map(({ data} ) => data.ref), ); expect(result.refMap.map(({ to} ) => to)).toEqual(result.fields.map((field) => field.ref)); expect(comparable(await target.forms.export())).toEqual(comparable(bundle)); expect(await orderOf(target)).toEqual(['total', 'subtotal']); } ); } ); test('an export takes whole fields: by name, or every field with a widget on a page', async () =>{ await using(async (opened) =>{ const source = await opened(open(ALICE)); await build(source); const named = await source.forms.export({ fields: [fqn('plan'), fqn('agree')]} ); expect(named.fields.map(({ data} ) => data.name)).toEqual(['agree', 'plan']); expect(named.widgets).toHaveLength(3); expect(named.pages.map(({ page} ) => page)).toEqual([FIRST, SECOND]); const onSecond = await source.forms.export({ pages: [SECOND]} ); expect(onSecond.fields.map(({ data} ) => data.name)).toEqual([ 'plan', 'country', 'tags', 'go', 'sign', ]); await expect(source.forms.export({ fields: [fqn('nothing')]} )).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); } ); } ); test("restore writes the source's attribution and the importer; stamp makes the fields the session's", async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const restored = await opened(open(BOB)); await restored.forms.import(bundle); const copied = await fieldOf(restored, 'customer.name'); expect(copied).toMatchObject({ createdBy: 'alice', filledBy: 'alice', filledByName: 'Alice Author', importedBy: 'bob', } ); const source = bundle.fields.find(({ data} ) => data.name === 'customer.name')!.data; expect(copied.createdAt).toBe(source.createdAt); expect(copied.filledAt).toBe(source.filledAt); expect(await fieldOf(restored, 'go')).toMatchObject({ createdBy: 'alice', filledBy: null} ); const stamped = await opened(open(BOB)); await stamped.forms.import(bundle, { attribution: 'stamp'} ); expect(await fieldOf(stamped, 'customer.name')).toMatchObject({ createdBy: 'bob', filledBy: 'bob', filledByName: 'Bob Builder', importedBy: null, } ); } ); } ); test('restoring needs doc.forms.import; stamping needs only what a create needs', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(BOB, [...DESIGN, 'doc.forms.script'])); expect(isPermissionRefusal(await refusalOf(target.forms.import(bundle)))).toBe(true); expect(isPermissionRefusal(await refusalOf(target.forms.importValues(bundle)))).toBe(true); expect(await namesOf(target)).toEqual([]); const stamped = await target.forms.import(bundle, { attribution: 'stamp'} ); expect(stamped.fields).toHaveLength(SOURCE_FIELDS.length); const filler = await opened(open(BOB, FILL)); expect( isPermissionRefusal( await refusalOf(filler.forms.import(bundle, { attribution: 'stamp'} )), ), ).toBe(true); } ); } ); test('without doc.forms.script, scripts, submits and links are left out; the rest is copied', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(BOB, DESIGN)); const result = await target.forms.import(bundle, { attribution: 'stamp'} ); expect(result.fields.map((field) => field.name)).toEqual(SOURCE_FIELDS); const left = result.dropped.map(({ ref, widget, field, reason} ) => ({ name: bundle.fields.find( ({ data} ) => encodeFieldRefKey(data.ref) === encodeFieldRefKey(ref!), )?.data.name, widget: widget !== undefined, field, reason, } )); expect(left).toEqual([{ name: 'customer.name', widget: false, field: 'actions.validate', reason: 'script-not-allowed', } , { name: 'go', widget: true, field: 'actions.activate', reason: 'script-not-allowed'} , { name: 'subtotal', widget: false, field: 'actions.calculate', reason: 'script-not-allowed', } , { name: 'total', widget: false, field: 'actions.calculate', reason: 'script-not-allowed', } , ]); expect((await fieldOf(target, 'customer.name')).actions?.validate ?? null).toBeNull(); expect(await orderOf(target)).toEqual([]); } ); } ); test('pages map: as they are by default, or as a list says; a page that maps nowhere refuses', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const swapped = await opened(open(ALICE)); const result = await swapped.forms.import(bundle, { pages: [{ from: FIRST, to: SECOND} , { from: SECOND, to: FIRST} , ], } ); const plan = result.fields.find((field) => field.name === 'plan')!; expect(plan.widgets.map((widget) => widget.page)).toEqual([SECOND, FIRST]); const short = await opened(open(ALICE, EVERYTHING, ONE_PAGE_PDF)); const events: DocumentEvent[] = []; short.events.subscribe((event) => events.push(event)); await expect(short.forms.import(bundle)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); expect(await namesOf(short)).toEqual([]); expect(events).toEqual([]); } ); } ); test('a field whose name is taken is left out, and so is one that would be its parent or child', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); await target.forms.create({ kind: 'text', name: 'agree'} ); await target.forms.create({ kind: 'text', name: 'customer'} ); await target.forms.create({ kind: 'text', name: 'go.now'} ); const result = await target.forms.import(bundle); const conflicts = result.dropped .filter(({ reason} ) => reason === 'name-conflict') .map(({ ref} ) => encodeFieldRefKey(ref!)); const names = new Map( bundle.fields.map(({ data} ) => [encodeFieldRefKey(data.ref), data.name]), ); expect(conflicts.map((key) => names.get(key))).toEqual(['customer.name', 'agree', 'go']); expect(result.fields.map((field) => field.name)).toEqual( SOURCE_FIELDS.filter((name) => !['customer.name', 'agree', 'go'].includes(name)), ); } ); } ); test("the calculation order of the copies follows the form's own, as the bundle has it", async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); await target.forms.create({ kind: 'text', name: 'own', actions:{ calculate: script('event.value = 0; ')} , } ); const result = await target.forms.import(bundle); expect(await orderOf(target)).toEqual(['own', 'total', 'subtotal']); expect(result.calculationOrder).toHaveLength(3); } ); } ); test('a signature never travels: a signature field is copied unsigned', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const sign = bundle.fields.find(({ data} ) => data.name === 'sign')!.data; expect(sign.valueEntry).toEqual({ kind: 'none'} ); const source = await opened(open(ALICE)); await build(source); await source.forms.update(fqn('customer.name'), { noExport: true} ); const [name] = (await source.forms.export({ fields: [fqn('customer.name')]} )).fields; expect(name!.data).toMatchObject({ value: '', valueEntry:{ kind: 'none'} , filledBy: null, filledAt: null, } ); } ); } ); test('a values import fills the fields of the same name, and reports what it leaves out', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(BOB)); await target.forms.import(bundle, { attribution: 'stamp', values: false} ); expect((await fieldOf(target, 'customer.name')).valueEntry).toEqual({ kind: 'none'} ); const rows = bundle.fields.map(({ data} ) => data); const row = (name: string) => rows.find((data) => data.name === name)!; const values: FormBundle ={ ...bundle, fields: [{ data: row('customer.name')} , { data:{ ...row('agree'), name: 'missing'} } , { data:{ ...row('customer.name'), name: 'agree'} } , { data:{ ...row('country'), value: 'FR', valueEntry:{ kind: 'scalar', value: 'FR'} } , } , { data: row('tags')} , ] as FormBundle['fields'], } ; const result = await target.forms.importValues(values, { attribution: 'restore'} ); expect(result.fields.map((field) => field.name)).toEqual(['customer.name', 'tags']); expect(result.dropped.map(({ reason} ) => reason)).toEqual([ 'no-field', 'wrong-kind', 'value-not-allowed', ]); expect(await fieldOf(target, 'customer.name')).toMatchObject({ value: 'Ada', filledBy: 'alice', importedBy: 'bob', } ); expect(await fieldOf(target, 'tags')).toMatchObject({ selectedValues: ['a', 'c']} ); expect(await fieldOf(target, 'country')).toMatchObject({ value: ''} ); } ); } ); test('a design import is undone and redone: fields, widgets and calculation order back exactly', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); await target.forms.create({ kind: 'text', name: 'own', actions:{ calculate: script('event.value = 0; ')} , } ); const before = await target.forms.list(); const imported = await target.forms.import(bundle); const after = await target.forms.list(); const undo = await target.apply({ undoOf: imported.meta.opId} ); expect(undo.items.map((item) => item.type)).toEqual( SOURCE_FIELDS.map(() => 'forms.delete'), ); expect(await target.forms.list()).toEqual(before); await target.apply({ undoOf: undo.meta.opId} ); const redone = await target.forms.list(); expect(redone.fields).toEqual(after.fields); expect(redone.calculationOrder).toEqual(after.calculationOrder); expect(await orderOf(target)).toEqual(['own', 'total', 'subtotal']); } ); } ); test('a values import is undone and redone: values and who filled them back', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(BOB)); await target.forms.import(bundle, { attribution: 'stamp', values: false} ); await target.forms.setValue(fqn('customer.name'), { value: 'Bob'} ); const filled = await target.forms.importValues(bundle); expect(filled.meta.undoable).toBe(true); expect(await fieldOf(target, 'customer.name')).toMatchObject({ value: 'Ada', filledBy: 'alice', } ); const undo = await target.apply({ undoOf: filled.meta.opId} ); expect(await fieldOf(target, 'customer.name')).toMatchObject({ value: 'Bob', filledBy: 'bob', } ); expect((await fieldOf(target, 'agree')).valueEntry).toEqual({ kind: 'none'} ); await target.apply({ undoOf: undo.meta.opId} ); expect(await fieldOf(target, 'customer.name')).toMatchObject({ value: 'Ada', filledBy: 'alice', importedBy: 'bob', } ); expect(await fieldOf(target, 'agree')).toMatchObject({ checked: true} ); } ); } ); test('an imported field changed since is left alone by the undo; the rest goes', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); const imported = await target.forms.import(bundle); await target.forms.update(fqn('country'), { required: true} ); const undo = await target.apply({ undoOf: imported.meta.opId} ); expect(undo.items.filter((item) => item.type === 'skipped')).toHaveLength(1); expect(await namesOf(target)).toEqual(['country']); } ); } ); test('a retry under the same opId answers again and writes nothing more', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); const first = await target.forms.import(bundle, { opId: 'form-import-retry'} ); const again = await target.forms.import(bundle, { opId: 'form-import-retry'} ); expect(again.refMap).toEqual(first.refMap); expect(await namesOf(target)).toEqual(SOURCE_FIELDS); const values = await target.forms.importValues(bundle, { opId: 'form-values-retry'} ); const valuesAgain = await target.forms.importValues(bundle, { opId: 'form-values-retry'} ); expect(valuesAgain.fields).toEqual(values.fields); } ); } ); test('each import is one transaction: one event per field, sharing its opId', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); const events: DocumentEvent[] = []; target.events.subscribe((event) => events.push(event)); const imported = await target.forms.import(bundle, { opId: 'form-import-1'} ); const created = events.filter((event) => event.type === 'forms.created'); expect(created).toHaveLength(SOURCE_FIELDS.length); created.forEach((event, index) =>{ if (event.type !== 'forms.created') return; expect(event.field).toEqual(imported.fields[index]); expect(event.origin.transaction).toEqual({ id: 'form-import-1', index, count: SOURCE_FIELDS.length, } ); } ); events.length = 0; await target.forms.setValue(fqn('customer.name'), { value: 'Changed'} ); await target.forms.setValue(fqn('agree'), { checked: false} ); events.length = 0; const filled = await target.forms.importValues(bundle, { opId: 'form-values-1'} ); const set = events.filter((event) => event.type === 'forms.valueSet'); expect(set.map((event) => event.type === 'forms.valueSet' && event.field.name)).toEqual( filled.fields.map((field) => field.name), ); expect(filled.fields.map((field) => field.name)).toEqual(['customer.name', 'agree']); } ); } ); test('refuses before writing: a malformed bundle, and doc.apply takes no import', async () =>{ await using(async (opened) =>{ const bundle = await sourceBundle(opened); const target = await opened(open(ALICE)); const broken ={ ...bundle, format: 'embedpdf/annotations'} as unknown as FormBundle; await expect(target.forms.import(broken)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); const strayWidget ={ ...bundle, fields: bundle.fields.slice(1)} ; const result = await target.forms.import(strayWidget, { attribution: 'stamp'} ); expect(result.dropped.filter(({ reason} ) => reason === 'no-field')).toHaveLength(1); const change ={ ops: [{ type: 'forms.import', bundle, attribution: 'restore'} ]} ; const refused = await refusalOf(target.apply(change as unknown as Change)); expect(EngineError.is(refused, EngineErrorCode.InvalidArg)).toBe(true); } ); } ); } ); } runMeasurementConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runMeasurementConformance.ts): export function runMeasurementConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`measurement conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ await engine?.destroy(); } ); const open = async () => options.openKind === 'bytes' ? engine.open({ kind: 'bytes', id: options.fixture.id, bytes: await options.fixture.bytes()} , EVERY_PERMISSION, ) : engine.open({ kind: 'id', id: options.fixture.cloudId ?? options.fixture.id} ); const scale = measureFromKnownLength(100, { value: 3, unit: 'm'} ); const vertices = [{ x: 0, y: 0} , { x: 100, y: 0} , { x: 100, y: 100} , ]; test('geometry derives contents while caption patches retain placement', async () =>{ const doc = await open(); try{ const page = doc.page((await doc.pages.list()).pages[0].ref); const created = ( await page.annotations.create({ subtype: 'line', intent: 'line-dimension', measure: scale, linePoints:{ start: vertices[0], end: vertices[1]} , captionEnabled: true, captionOffset:{ along: 10, perpendicular: 20} , } ) ).annotation; const inert = await page.annotations.update(created.ref, { subtype: 'line', contents: '999 m', } ); expect(inert.annotation.contents).toBe('3.00 m'); expect(inert.appearance).toEqual({ action: 'preserved', changed: false} ); const changed = await page.annotations.update(created.ref, { subtype: 'line', linePoints:{ start: vertices[0], end:{ x: 200, y: 0} } , } ); expect(changed.annotation.contents).toBe('6.00 m'); expect(changed.appearance.changed).toBe(true); const hidden = await page.annotations.update(created.ref, { subtype: 'line', captionEnabled: false, } ); expect(hidden.annotation).toMatchObject({ contents: '6.00 m', captionEnabled: false, captionOffset:{ along: 10, perpendicular: 20} , } ); expect(hidden.appearance.changed).toBe(true); const reset = await page.annotations.update(created.ref, { subtype: 'line', captionEnabled: true, captionOffset: null, measure: null, } ); expect(reset.annotation.contents).toBe('6.00 m'); expect(reset.annotation.subtype === 'line' && reset.annotation.captionOffset === null).toBe( true, ); expect(measurementReadout(reset.annotation)).toEqual({ unavailable: 'no-measure'} ); } finally{ await doc.close(); } } ); test('all three kinds derive labels, save, reopen and retain captions', async () =>{ let doc = await open(); try{ const pageObjectNumber = (await doc.pages.list()).pages[0].ref.objectNumber; const drafts: AnnotationDraft[] = [{ subtype: 'line', intent: 'line-dimension', measure: measureFromKnownLength(1, { value: 1.00000001, unit: 'm'} ), contents: 'wrong', linePoints:{ start: vertices[0], end:{ x: 3.4450000001, y: 0} } , captionEnabled: true, captionOffset:{ along: 10, perpendicular: 20} , } , { subtype: 'polyline', intent: 'polyline-dimension', measure: scale, contents: 'wrong', vertices, captionEnabled: true, captionCenter:{ x: 0, y: 0} , } , { subtype: 'polygon', intent: 'polygon-dimension', measure: scale, contents: 'wrong', vertices, captionEnabled: true, captionCenter:{ x: 50, y: 30} , } , ]; const saved = []; for (const draft of drafts){ const preview = measurementReadout(draft); const a = (await doc.page(toPageRef(pageObjectNumber)).annotations.create(draft)) .annotation; expect(a.contents).toBe('label' in preview ? preview.label : undefined); saved.push(a); } const bytes = options.openKind === 'bytes' ? await doc.download() : undefined; await doc.close(); doc = bytes ? await engine.open({ kind: 'bytes', id: `${ options.fixture.id} -saved`, bytes} , EVERY_PERMISSION, ) : await open(); const page = doc.page((await doc.pages.list()).pages[0].ref); const list = (await page.annotations.list()).annotations; for (const before of saved){ const a = list.find((a) => annotationKey(a.ref) === annotationKey(before.ref))!; expect(a.contents).toBe(before.contents); if (a.subtype !== 'line' && a.subtype !== 'polygon' && a.subtype !== 'polyline') throw new Error('Missing dimension'); expect(captionOf(a)).toEqual(captionOf(before)); const result = await page.annotations.update(a.ref, { subtype: a.subtype, color: '#0000ff', } ); expect(result.annotation.contents).toBe(before.contents); } } finally{ await doc.close(); } } ); test('calibration updates only viewports and emits one event per write', async () =>{ const doc = await open(); try{ const pageObjectNumber = (await doc.pages.list()).pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); if (!page.measure) throw new Error('Measurement service is required'); const listed = (await page.measure.listViewports()).viewports; for (const viewport of listed){ expect('name' in viewport && 'measure' in viewport).toBe(true); } const foreign = listed.filter((v) => !v.owned); const annotations = (await page.annotations.list()).annotations; const events: DocumentEvent[] = []; const off = doc.events.subscribe((event) => events.push(event)); try{ const set = await page.measure.setScale(scale); expect(set.page).toEqual(page.ref); expect( (await page.measure.listViewports()).viewports.filter((v) => v.owned), ).toHaveLength(1); expect((await page.annotations.list()).annotations).toEqual(annotations); await page.measure.setScale(null); expect((await page.measure.listViewports()).viewports).toEqual(foreign); const changes = events.filter((e) => e.type === 'pages.scaleSet'); expect(changes).toHaveLength(2); for (const event of changes) expect(event).toMatchObject({ page: toPageRef(pageObjectNumber), meta:{ affectedPages: []} , } ); } finally{ off(); } } finally{ await doc.close(); } } ); test('invalid and immediately aborted calibration leaves the previous scale intact', async () =>{ const doc = await open(); try{ const page = doc.page((await doc.pages.list()).pages[0].ref); await page.measure!.setScale(scale); const before = await page.measure!.listViewports(); await expect( page.measure!.setScale({ ...scale, x: [{ unit: 'm', conversion: 0} ]} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const pending = page.measure!.setScale(null); pending.abort('conformance'); await expect(pending).rejects.toBeInstanceOf(AbortError); expect(await page.measure!.listViewports()).toEqual(before); } finally{ await doc.close(); } } ); } ); } runMetadataConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runMetadataConformance.ts): export function runMetadataConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`metadata conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('reads metadata from sample fixture', async () =>{ const doc = await openFixture(engine, options); try{ const meta = await doc.metadata.get(); expect(meta).toMatchObject(options.fixture.expected); expect(meta.trapped).toMatch(/^(true|false|unknown)$/); } finally{ await doc.close(); } } ); test('abort() before completion rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const p = doc.metadata.get(); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); test('aborting one read does not affect a concurrent one', async () =>{ const doc = await openFixture(engine, options); try{ const a = doc.metadata.get(); const b = doc.metadata.get(); a.abort('test'); await expect(a).rejects.toBeInstanceOf(AbortError); await expect(b).resolves.toMatchObject(options.fixture.expected); } finally{ await doc.close(); } } ); test('metadata after close throws DocNotOpen', async () =>{ const doc = await openFixture(engine, options); await doc.close(); let caught: unknown; try{ await doc.metadata.get(); } catch (err){ caught = err; } expect(caught).toBeTruthy(); expect(EngineError.is(caught, EngineErrorCode.DocNotOpen)).toBe(true); } ); test('update() sets standard fields, custom.update() sets custom keys, each read sees its own', async () =>{ const doc = await openFixture(engine, options); try{ const result = await doc.metadata.update({ title: 'Conformance Title', subject: 'Conformance Subject', } ); expect(result.metadata.title).toBe('Conformance Title'); expect(result.metadata.subject).toBe('Conformance Subject'); expect('custom' in result.metadata).toBe(false); const customResult = await doc.metadata.custom.update({ ConformanceKey: 'conformance-value', } ); expect(customResult.custom['ConformanceKey']).toBe('conformance-value'); const after = await doc.metadata.get(); expect(after.title).toBe('Conformance Title'); expect(after.subject).toBe('Conformance Subject'); const afterCustom = await doc.metadata.custom.get(); expect(afterCustom['ConformanceKey']).toBe('conformance-value'); } finally{ await doc.close(); } } ); test('custom.update(): a key left out stays, null removes, standard fields are untouched', async () =>{ const doc = await openFixture(engine, options); try{ await doc.metadata.update({ title: 'Kept Title'} ); await doc.metadata.custom.update({ KeepMe: 'a', DropMe: 'b'} ); const{ custom} = await doc.metadata.custom.update({ DropMe: null, AddMe: 'c'} ); expect(custom['KeepMe']).toBe('a'); expect('DropMe' in custom).toBe(false); expect(custom['AddMe']).toBe('c'); expect((await doc.metadata.custom.get())['KeepMe']).toBe('a'); expect((await doc.metadata.get()).title).toBe('Kept Title'); } finally{ await doc.close(); } } ); test("'' is a value, and custom.update() refuses a key it can't write", async () =>{ const doc = await openFixture(engine, options); try{ await doc.metadata.update({ title: ''} ); await doc.metadata.custom.update({ EmptyKey: ''} ); expect((await doc.metadata.get()).title).toBe(''); expect((await doc.metadata.custom.get())['EmptyKey']).toBe(''); for (const key of ['Title', 'Bad\u0001Key', '']){ let caught: unknown; try{ await doc.metadata.custom.update({ NotWritten: 'x', [key]: 'x'} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); expect((caught as EngineError).details?.['field']).toBe(key); } expect('NotWritten' in (await doc.metadata.custom.get())).toBe(false); } finally{ await doc.close(); } } ); test('update() clears a field with null', async () =>{ const doc = await openFixture(engine, options); try{ await doc.metadata.update({ title: 'To Be Cleared'} ); const set = await doc.metadata.get(); expect(set.title).toBe('To Be Cleared'); await doc.metadata.update({ title: null} ); const cleared = await doc.metadata.get(); expect(cleared.title).toBe(null); } finally{ await doc.close(); } } ); test('update() after close throws DocNotOpen', async () =>{ const doc = await openFixture(engine, options); await doc.close(); let caught: unknown; try{ await doc.metadata.update({ title: 'nope'} ); } catch (err){ caught = err; } expect(caught).toBeTruthy(); expect(EngineError.is(caught, EngineErrorCode.DocNotOpen)).toBe(true); } ); test('custom reads and writes after close throw DocNotOpen', async () =>{ const doc = await openFixture(engine, options); await doc.close(); for (const call of [() => doc.metadata.custom.get(), () => doc.metadata.custom.update({ } )]){ let caught: unknown; try{ await call(); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.DocNotOpen)).toBe(true); } } ); } ); } runMixedScriptConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runMixedScriptConformance.ts): export function runMixedScriptConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`mixed-script conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); for (const writer of WRITERS){ for (const scriptCase of CASES){ test(`${ writer.name} : ${ scriptCase.name} `, async () =>{ const doc = await openFixture(engine, options); try{ const [page] = (await doc.pages.insertBlank({ size: PAGE_SIZE} )).insertedPages; const{ ref, missing} = await writer.write( doc, page!, scriptCase.value, scriptCase.fontFamily ?? 'helvetica', ); const pdf = await doc.page(ref.page).annotations.exportAppearance([ref]); const drawn = await drawnTextOf(pdf); expect(drawn).toHaveLength(1); const expected = (writer.field && scriptCase.fieldRuns) || scriptCase.runs; expect(byFont(drawn[0]!)).toEqual(expected); expect(problemsOf(drawn[0]!)).toEqual([]); expect(missing).toEqual(scriptCase.missing); await doc.page(ref.page).annotations.flatten([ref]); const layout = await doc.page(ref.page).text.layout(); expect(layout.charCount > 0).toBe(true); expect(charactersOutside(layout, writer.box)).toEqual([]); const{ text} = await doc.page(ref.page).text.get(); const misread = drawn[0]!.runs .filter((run) => RIGHT_TO_LEFT.test(run.text) && !text.includes(run.text)) .map((run) => run.text); expect(misread).toEqual([]); } finally{ await doc.close(); } } ); } } test('a change says what each op drew with no font, and what all of them did', async () =>{ const doc = await openFixture(engine, options); try{ const page = (await doc.pages.list()).pages[0]!; const freeText = (y: number, contents: string) => ({ type: 'annotations.create', page: page.ref, data:{ subtype: 'free-text', box:{ x: 20, y, width: 260, height: 40} , fontFamily: 'helvetica', contents, } , } ) as const; const result = await doc.apply({ ops: [freeText(20, 'A中'), freeText(80, 'Hello'), freeText(140, '한中')], } ); expect(result.items.map((item) => item.meta.missingCharacters)).toEqual([ ['中'], undefined, ['한', '中'], ]); expect(result.meta.missingCharacters).toEqual(['中', '한']); } finally{ await doc.close(); } } ); } ); } runNamedPagesConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runNamedPagesConformance.ts): export function runNamedPagesConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`named pages conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('pages.list() carries namedPages and every entry resolves', async () =>{ const doc = await openFixture(engine, options); try{ const layout = await doc.pages.list(); PageListSnapshotSchema.parse(layout); expect(Array.isArray(layout.namedPages)).toBe(true); const pageObjectNumbers = new Set(layout.pages.map((page) => page.ref.objectNumber)); for (const entry of layout.namedPages){ expect(entry.name.length > 0).toBe(true); if (entry.target.kind === 'page'){ expect(pageObjectNumbers.has(entry.target.page.objectNumber)).toBe(true); } } } finally{ await doc.close(); } } ); test('pages.setName() registers, replaces by key, and renames via `replace`', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.setName) return; const before = await doc.pages.list(); const [first, second] = before.pages; const baseline = before.namedPages.length; const created = await doc.pages.setName({ name: 'Approved=Goedgekeurd', page: first.ref, } ); PageNameResultSchema.parse(created); expect(created.layout.pages.length).toBe(before.pages.length); expect(find(created, 'Approved=Goedgekeurd')).toEqual({ kind: 'page', page: toPageRef(first.ref.objectNumber), } ); expect(created.layout.namedPages.length).toBe(baseline + 1); const delta = created.meta.cacheDelta; if (delta){ expect(delta.docVersion > delta.previousDocVersion).toBe(true); expect((delta.layoutVersion ?? 0) > 0).toBe(true); } const listed = await doc.pages.list(); expect(listed.namedPages).toEqual(created.layout.namedPages); const replaced = await doc.pages.setName({ name: 'Approved=Goedgekeurd', page: second.ref, } ); expect(find(replaced, 'Approved=Goedgekeurd')).toEqual({ kind: 'page', page: toPageRef(second.ref.objectNumber), } ); expect(replaced.layout.namedPages.length).toBe(baseline + 1); const renamed = await doc.pages.setName({ name: 'Approved=Approved', page: second.ref, replace: 'Approved=Goedgekeurd', } ); expect(find(renamed, 'Approved=Goedgekeurd')).toBe(undefined); expect(find(renamed, 'Approved=Approved')).toEqual({ kind: 'page', page: toPageRef(second.ref.objectNumber), } ); expect(renamed.layout.namedPages.length).toBe(baseline + 1); } finally{ await doc.close(); } } ); test('non-ASCII keys round-trip through set → list', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.setName) return; const before = await doc.pages.list(); const key = 'Stämpel=Stämpel 日本'; const result = await doc.pages.setName({ name: key, page: before.pages[0].ref, } ); expect(find(result, key)).toEqual({ kind: 'page', page: toPageRef(before.pages[0].ref.objectNumber), } ); const listed = await doc.pages.list(); expect(listed.namedPages.some((entry) => entry.name === key)).toBe(true); } finally{ await doc.close(); } } ); test('pages.removeName() drops the registration and keeps the page', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.setName || !doc.pages.removeName) return; const before = await doc.pages.list(); await doc.pages.setName({ name: 'Draft=Concept', page: before.pages[0].ref, } ); const removed = await doc.pages.removeName({ name: 'Draft=Concept'} ); PageNameResultSchema.parse(removed); expect(find(removed, 'Draft=Concept')).toBe(undefined); expect(removed.layout.pages.length).toBe(before.pages.length); await expect(doc.pages.removeName({ name: 'Draft=Concept'} )).rejects.toMatchObject({ code: EngineErrorCode.NotFound, } ); } finally{ await doc.close(); } } ); test('pages.setName() rejects an empty name and an unknown page', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.setName) return; const before = await doc.pages.list(); await expect( doc.pages.setName({ name: '', page: before.pages[0].ref} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); let unknownPage: unknown = null; try{ await doc.pages.setName({ name: 'Ghost=Ghost', page: toPageRef(987654321)} ); } catch (error){ unknownPage = error; } expect( EngineError.is(unknownPage, EngineErrorCode.NotFound) || EngineError.is(unknownPage, EngineErrorCode.InvalidArg), ).toBe(true); } finally{ await doc.close(); } } ); test('deleting a page removes every registration pointing at it', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.setName) return; const before = await doc.pages.list(); if (before.pages.length < 2) return; const victim = before.pages[1].ref; const survivor = before.pages[0].ref; await doc.pages.setName({ name: 'Victim=One', page: victim} ); await doc.pages.setName({ name: 'Victim=Two', page: victim} ); await doc.pages.setName({ name: 'Survivor', page: survivor} ); const deleted = await doc.pages.delete([victim]); const names = deleted.layout.namedPages.map((entry) => entry.name); expect(names.includes('Victim=One')).toBe(false); expect(names.includes('Victim=Two')).toBe(false); expect(names).toContain('Survivor'); expect(deleted.layout.namedPages.some((entry) => entry.target.kind === 'dangling')).toBe( false, ); } finally{ await doc.close(); } } ); test('abort on pages.setName() rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.setName) return; const before = await doc.pages.list(); const promise = doc.pages.setName({ name: 'Aborted=Aborted', page: before.pages[0].ref, } ); promise.abort(); await expect(promise).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); } ); } runNoStrokeConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runNoStrokeConformance.ts): export function runNoStrokeConformance( runner: ConformanceTestRunner, options: NoStrokeConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`no-stroke conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const onPage = async (run: (page: PageHandle, doc: DocumentHandle) => Promise) =>{ const doc = await options.open(engine); try{ const{ pages} = await doc.pages.list(); await run(doc.page(toPageRef(pages[0]!.ref.objectNumber)), doc); } finally{ await doc.close(); } } ; const strokedOf = async (page: PageHandle): Promise> =>{ const{ annotations} = await page.annotations.list(); return new Map( annotations.filter(isStroked).map((annotation) => [annotation.nm ?? '', annotation]), ); } ; test('a /C left out or empty reads as no stroke and keeps its width', async () =>{ await onPage(async (page) =>{ const read = await strokedOf(page); for (const stroke of STROKE_CASES){ for (const kind of STROKED_KINDS){ const annotation = read.get(`${ stroke.name} -${ kind} `); expect(annotation?.color).toBe(stroke.color); expect(annotation?.strokeWidth).toBe(stroke.strokeWidth); } } } ); } ); test('a shape with no stroke draws its fill alone, where the stroke would be', async () =>{ await onPage(async (page) =>{ const [red, empty, leftOut] = await Promise.all( [0, 1, 2].map((row) => rasterOf(page, { x: MARGIN, y: MARGIN + row * CELL, width: SIZE, height: SIZE} ), ), ); const middle = (SIZE * SCALE) / 2; expect(colorAt(red!, 2, middle)).toBe('red'); expect(colorAt(red!, 6, middle)).toBe('red'); expect(colorAt(red!, middle, middle)).toBe('blue'); for (const unstroked of [empty!, leftOut!]){ expect(colorAt(unstroked, 2, middle)).toBe('white'); expect(colorAt(unstroked, 6, middle)).toBe('blue'); expect(colorAt(unstroked, middle, middle)).toBe('blue'); } } ); } ); test('color null writes /C [] and keeps the width; a color brings the stroke back', async () =>{ await onPage(async (page, doc) =>{ const square = (await strokedOf(page)).get('red-square')!; const{ annotation: cleared} = await page.annotations.update(square.ref, { color: null, } ); expect(isStroked(cleared) && cleared.color).toBe(null); expect(isStroked(cleared) && cleared.strokeWidth).toBe(2); const text = new TextDecoder('latin1').decode(await doc.download()); expect(lastObjectNamed(text, 'red-square')).toMatch(/\/C\s*\[\s*\]/); const{ annotation: restroked} = await page.annotations.update(square.ref, { color: '#00ff00', } ); expect(isStroked(restroked) && restroked.color).toBe('#00ff00'); expect(isStroked(restroked) && restroked.strokeWidth).toBe(2); } ); } ); test('every stroked kind is created without a stroke from color null', async () =>{ await onPage(async (page) =>{ const box ={ x: 40, y: 40, width: 60, height: 60} ; const points = [{ x: 40, y: 100} , { x: 70, y: 40} , { x: 100, y: 100} , ]; const drafts: AnnotationDraft[] = [{ subtype: 'square', box, color: null, interiorColor: '#0000ff'} , { subtype: 'circle', box, color: null, interiorColor: '#0000ff'} , { subtype: 'polygon', vertices: points, color: null, interiorColor: '#0000ff'} , { subtype: 'polyline', vertices: points, color: null} , { subtype: 'line', linePoints:{ start: points[0]!, end: points[2]!} , lineEndings:{ start: 'none', end: 'closed-arrow'} , color: null, interiorColor: '#0000ff', } , { subtype: 'ink', inkList: [points], color: null} , ]; for (const draft of drafts){ const{ annotation} = await page.annotations.create(draft); expect(isStroked(annotation) && annotation.color).toBe(null); expect(isStroked(annotation) && annotation.strokeWidth).toBe(1); } const{ annotation: defaulted} = await page.annotations.create({ subtype: 'square', box, } ); expect(isStroked(defaulted) && defaulted.color).toBe('#ff0000' satisfies Color); } ); } ); } ); } runObjectNumberConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runObjectNumberConformance.ts): export function runObjectNumberConformance( runner: ConformanceTestRunner, options: ObjectNumberConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`object number conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDocument = async ( body: (doc: DocumentHandle, pages: readonly PageRef[]) => Promise, ) =>{ const doc = await options.open(engine); try{ const{ pages} = await doc.pages.list(); await body( doc, pages.map((page) => toPageRef(page.ref.objectNumber)), ); } finally{ await doc.close(); } } ; const take = async (doc: DocumentHandle, count: number): Promise =>{ await doc.objectNumbers.reserve(count); return Array.from({ length: count} , () => doc.objectNumbers.take()!); } ; const refAt = (page: PageRef, objectNumber: number): AnnotationRef => ({ kind: 'objectNumber', page, objectNumber, } ); test('the pool hands out numbers, each once', async () =>{ await withDocument(async (doc) =>{ await doc.objectNumbers.reserve(100); expect(doc.objectNumbers.held >= 100).toBe(true); const numbers = Array.from({ length: 100} , () => doc.objectNumbers.take()); expect(numbers.every((number) => Number.isInteger(number) && number! > 0)).toBe(true); expect(new Set(numbers).size).toBe(100); } ); } ); test('a create at a number lands at it; one without a number lands elsewhere', async () =>{ await withDocument(async (doc, [page]) =>{ const [first, second] = await take(doc, 2); const square = await doc .page(page!) .annotations.create({ subtype: 'square', box: box(20)} , { objectNumber: first} ); expect(square.annotation.ref).toEqual(refAt(page!, first!)); const free = await doc.page(page!).annotations.create({ subtype: 'circle', box: box(80)} ); const freeNumber = free.annotation.ref.kind === 'objectNumber' ? free.annotation.ref.objectNumber : null; expect([first, second].includes(freeNumber!)).toBe(false); const circle = await doc .page(page!) .annotations.create({ subtype: 'circle', box: box(140)} , { objectNumber: second} ); expect(circle.annotation.ref).toEqual(refAt(page!, second!)); const{ annotations} = await doc.page(page!).annotations.list(); const listed = annotations.map((annotation) => annotationKey(annotation.ref)); for (const number of [first, second]){ expect(listed).toContain(annotationKey(refAt(page!, number!))); } } ); } ); test('a number the session does not hold is not-held; one a call uses twice is taken', async () =>{ await withDocument(async (doc, [page]) =>{ const [used, twice] = await take(doc, 2); await doc .page(page!) .annotations.create({ subtype: 'square', box: box(20)} , { objectNumber: used} ); const before = await doc.pages.list(); await expect( doc .page(page!) .annotations.create({ subtype: 'square', box: box(80)} , { objectNumber: used} ), ).rejects.toMatchObject({ code: EngineErrorCode.ObjectNumberUnavailable, details:{ objectNumber: used, reason: 'not-held'} , } ); await expect( doc .page(page!) .annotations.create({ subtype: 'square', box: box(80)} , { objectNumber: 7_999_999} ), ).rejects.toMatchObject({ code: EngineErrorCode.ObjectNumberUnavailable, details:{ objectNumber: 7_999_999, reason: 'not-held'} , } ); await expect( doc.pages.insertBlank({ size:{ width: 200, height: 200} , count: 2} , undefined, { objectNumbers: [twice!, twice!], } ), ).rejects.toMatchObject({ code: EngineErrorCode.ObjectNumberUnavailable, details:{ objectNumber: twice, reason: 'taken'} , } ); expect(await doc.pages.list()).toEqual(before); const inserted = await doc.pages.insertBlank({ size:{ width: 200, height: 200} } , undefined, { objectNumbers: [twice!]} , ); expect(inserted.insertedPages).toEqual([toPageRef(twice!)]); } ); } ); test('a page named at birth takes an annotation at once, in call order', async () =>{ await withDocument(async (doc) =>{ const [pageNumber, annotationNumber] = await take(doc, 2); const page = toPageRef(pageNumber!); const inserting = doc.pages.insertBlank({ size:{ width: 200, height: 200} } , undefined, { objectNumbers: [pageNumber!], } ); const creating = doc .page(page) .annotations.create({ subtype: 'square', box: box(20)} , { objectNumber: annotationNumber} , ); const [inserted, created] = await Promise.all([inserting, creating]); expect(inserted.insertedPages).toEqual([page]); expect(created.annotation.ref).toEqual(refAt(page, annotationNumber!)); expect(created.annotation.nm).toMatch(UUID_V7); } ); } ); test('writes made without waiting apply in the order they were made', async () =>{ await withDocument(async (doc, [page]) =>{ const [number] = await take(doc, 1); const ref = refAt(page!, number!); const events: string[] = []; doc.events.subscribe((event) => events.push(event.type)); const annotations = doc.page(page!).annotations; const writes = [ annotations.create({ subtype: 'square', box: box(20)} , { objectNumber: number} ), annotations.update(ref, { contents: 'first'} ), annotations.update(ref, { contents: 'second'} ), ]; await Promise.all(writes); expect(events).toEqual([ 'annotations.created', 'annotations.updated', 'annotations.updated', ]); const{ annotations: now} = await annotations.list(); expect( now.find( (annotation) => annotation.ref.kind === 'objectNumber' && annotation.ref.objectNumber === number, )?.contents, ).toBe('second'); } ); } ); test('a field and its widgets at numbers; a merged field splits to a number', async () =>{ await withDocument(async (doc, [first, second]) =>{ const [field, left, right, widget, split] = await take(doc, 5); const created = await doc.forms.create({ kind: 'text', name: 'billing.name', widgets: [{ page: second!, rect: box(20)} , { page: second!, rect: box(80)} , ], } , { objectNumber: field, widgetObjectNumbers: [left!, right!]} , ); expect(created.field.ref).toEqual({ kind: 'objectNumber', objectNumber: field} ); expect(created.field.widgets.map((w) => w.objectNumber)).toEqual([left, right]); for (const number of [left, right]){ const read = created.widgets.find( (w) => w.ref.kind === 'objectNumber' && w.ref.objectNumber === number, ); expect(read?.nm).toMatch(UUID_V7); expect(read?.page).toEqual(second); } const added = await doc.forms.addWidget({ kind: 'objectNumber', objectNumber: MERGED_FIELD} , { page: first!, rect: box(140)} , { objectNumber: widget, splitObjectNumber: split} , ); expect(added.field.ref).toEqual({ kind: 'objectNumber', objectNumber: MERGED_FIELD} ); expect(added.field.widgets.map((w) => w.objectNumber).sort((a, b) => a - b)).toEqual( [split!, widget!].sort((a, b) => a - b), ); } ); } ); test("every event of a write carries the write's opId", async () =>{ await withDocument(async (doc, [page]) =>{ const events: DocumentEvent[] = []; doc.events.subscribe((event) => events.push(event)); const created = await doc .page(page!) .annotations.create({ subtype: 'square', box: box(20)} , { opId: 'op-create'} ); await doc.page(page!).annotations.update(created.annotation.ref, { contents: 'x'} ); await doc.pages.insertBlank({ size:{ width: 200, height: 200} } , undefined, { opId: 'op-insert', } ); const [create, update, insert] = events.map((event) => event.type === 'stream.desynced' ? null : event.origin.transaction, ); expect(events).toHaveLength(3); expect(create).toEqual({ id: 'op-create', index: 0, count: 1} ); expect(update).toMatchObject({ index: 0, count: 1} ); expect(typeof update!.id === 'string' && update!.id.length > 0).toBe(true); expect(insert).toEqual({ id: 'op-insert', index: 0, count: 1} ); } ); } ); test('an opId no header could carry is refused, and nothing is written', async () =>{ await withDocument(async (doc, [page]) =>{ const before = await doc.page(page!).annotations.list(); for (const opId of ['', 'has space', 'é', 'x'.repeat(256)]){ await expect( doc.page(page!).annotations.create({ subtype: 'square', box: box(20)} , { opId} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, details:{ field: 'opId'} , } ); } expect(await doc.page(page!).annotations.list()).toEqual(before); } ); } ); } ); } runOutlineConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runOutlineConformance.ts): export function runOutlineConformance( runner: ConformanceTestRunner, options: OutlineConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`outline conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withOutline = async ( body: (doc: DocumentHandle) => Promise, bytes = OUTLINE_FIXTURE_PDF, ) =>{ const doc = await options.open(engine, bytes.slice()); try{ await body(doc); } finally{ await doc.close(); } } ; test('reads every item depth first, with its target, its look and whether it opens', async () =>{ await withOutline(async (doc) =>{ const outline = await doc.outline.get(); expect(outline.incomplete).toBe(false); expect(titles(outline)).toEqual(['A', 'A1', 'B', 'C', 'C1', 'D']); expect(itemOf(outline, A)).toMatchObject({ parent: null, open: true, color: null, bold: false, italic: false, action: null, target:{ kind: 'goto', destination:{ kind: 'xyz', page: FIRST_PAGE, x: 20, y: 20, zoom: null} , } , } ); expect(itemOf(outline, A1)).toMatchObject({ parent: A, open: false, target:{ kind: 'goto', destination:{ kind: 'fit', page: SECOND_PAGE} } , } ); expect(itemOf(outline, B)).toMatchObject({ color: '#ff0000', bold: true, target:{ kind: 'uri', uri: 'https://example.com/'} , action:{ incomplete: false, root:{ type: 'uri', uri: 'https://example.com/'} } , } ); expect(itemOf(outline, C)).toMatchObject({ open: false, target:{ kind: 'goto', destination:{ kind: 'fitH', page: SECOND_PAGE, y: 50} } , } ); expect(itemOf(outline, C1)).toMatchObject({ parent: C, target: null, action: null} ); expect(itemOf(outline, D)).toMatchObject({ target:{ kind: 'javascript'} , action:{ root:{ type: 'javascript', script: 'app.alert(1)'} } , } ); } ); } ); test('a target reads the same however the file stores it', async () =>{ await withOutline(async (doc) =>{ const outline = await doc.outline.get(); expect(outline.incomplete).toBe(false); const shared ={ kind: 'goto', destination:{ kind: 'xyz', page: FIRST_PAGE, x: 10, y: 10, zoom: null} , } ; expect(itemOf(outline, SHARED_ONE)).toMatchObject({ target: shared, action:{ root:{ type: 'goto'} } , } ); expect(itemOf(outline, SHARED_TWO)).toMatchObject({ target: shared} ); expect(await linkTargetOf(doc)).toMatchObject(shared); expect(itemOf(outline, HYPERREF)).toMatchObject({ target:{ kind: 'goto', destination:{ kind: 'xyz', page: SECOND_PAGE, x: 0, y: 100, zoom: null} , } , action:{ root:{ type: 'goto'} } , } ); expect(itemOf(outline, OLD_DESTS)).toMatchObject({ target:{ kind: 'goto', destination:{ kind: 'fitH', page: SECOND_PAGE, y: 50} } , action: null, } ); expect(itemOf(outline, BY_NUMBER)).toMatchObject({ target:{ kind: 'goto', destination:{ kind: 'fit', page: SECOND_PAGE} } , } ); } , OUTLINE_TARGETS_FIXTURE_PDF); } ); test('a new target leaves an action the item shared alone, and an undo brings it back', async () =>{ await withOutline(async (doc) =>{ const before = await doc.outline.get(); const link = await linkTargetOf(doc); const changed = await doc.outline.update(SHARED_ONE, { target:{ kind: 'uri', uri: 'https://example.com/'} , } ); expect(changed.item.target).toEqual({ kind: 'uri', uri: 'https://example.com/'} ); const after = await doc.outline.get(); expect(itemOf(after, SHARED_TWO)).toEqual(itemOf(before, SHARED_TWO)); expect(await linkTargetOf(doc)).toEqual(link); await doc.apply({ undoOf: changed.meta.opId} ); expect(await doc.outline.get()).toEqual(before); } , OUTLINE_TARGETS_FIXTURE_PDF); } ); test('a delete and its undo keep a target however the file stored it', async () =>{ await withOutline(async (doc) =>{ const before = await doc.outline.get(); const link = await linkTargetOf(doc); for (const ref of [SHARED_TWO, HYPERREF, OLD_DESTS, BY_NUMBER]){ const deleted = await doc.outline.delete(ref); expect(itemOf(await doc.outline.get(), ref)).toBe(undefined); await doc.apply({ undoOf: deleted.meta.opId} ); expect(await doc.outline.get()).toEqual(before); } expect(await linkTargetOf(doc)).toEqual(link); } , OUTLINE_TARGETS_FIXTURE_PDF); } ); test('a document without an outline reads an empty one', async () =>{ const bytes = pdfOf([ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] >>', ]); await withOutline(async (doc) =>{ expect(await doc.outline.get()).toEqual({ items: [], incomplete: false} ); await doc.outline.create({ title: 'First'} ); expect(titles(await doc.outline.get())).toEqual(['First']); } , bytes); } ); test('a create goes to its place, under its parent, at the number it names', async () =>{ await withOutline(async (doc) =>{ await doc.objectNumbers.reserve(1); const number = doc.objectNumbers.take()!; const first = await doc.outline.create({ title: 'A0', target:{ kind: 'goto', destination:{ kind: 'fit', page: FIRST_PAGE} } } , { parent: A, position: 'start', objectNumber: number} , ); expect(first.item).toMatchObject({ ref: toOutlineItemRef(number), parent: A, title: 'A0'} ); expect(first.order).toEqual({ parent: A, children: [toOutlineItemRef(number), A1]} ); const after = await doc.outline.create({ title: 'B2', color: '#00ff00'} , { position:{ after: B} } , ); expect(after.order.parent).toBeNull(); expect(after.order.children.map((ref) => ref.objectNumber)).toEqual([ 6, 7, after.item.ref.objectNumber, 8, 9, ]); const outline = await doc.outline.get(); expect(titles(outline)).toEqual(['A', 'A0', 'A1', 'B', 'B2', 'C', 'C1', 'D']); expect(itemOf(outline, after.item.ref)).toMatchObject({ color: '#00ff00', target: null} ); } ); } ); test('an update writes the fields it names and leaves the others', async () =>{ await withOutline(async (doc) =>{ const renamed = await doc.outline.update(B, { title: 'Bee', italic: true} ); expect(renamed.item).toMatchObject({ title: 'Bee', italic: true, bold: true, color: '#ff0000', target:{ kind: 'uri'} , } ); const cleared = await doc.outline.update(B, { color: null, target: null, bold: false} ); expect(cleared.item).toMatchObject({ color: null, target: null, bold: false, italic: true, } ); const retargeted = await doc.outline.update(C1, { target:{ kind: 'goto', destination:{ kind: 'xyz', page: SECOND_PAGE, x: 10, y: 40, zoom: null} , } , } ); expect(retargeted.item.target).toMatchObject({ kind: 'goto', destination:{ kind: 'xyz', page: SECOND_PAGE, x: 10, y: 40, zoom: null} , } ); expect(retargeted.item.action).toMatchObject({ root:{ type: 'goto'} } ); } ); } ); test('open takes effect on an item with children; a leaf has no open state', async () =>{ await withOutline(async (doc) =>{ expect((await doc.outline.update(C, { open: true} )).item.open).toBe(true); expect((await doc.outline.update(A, { open: false} )).item.open).toBe(false); expect((await doc.outline.update(D, { open: true} )).item.open).toBe(false); } ); } ); test('a write answers what the prediction rules say it leaves', async () =>{ await withOutline(async (doc) =>{ const drafts: OutlineItemDraft[] = [{ title: 'Plain'} , { title: 'To a spot', target:{ kind: 'goto', destination:{ kind: 'xyz', page: SECOND_PAGE, x: 10, y: 40, zoom: null} , } , color: '#00AAFF', bold: true, } , { title: 'To a site', target:{ kind: 'uri', uri: 'https://example.com/'} , italic: true, } , { title: 'Next', target:{ kind: 'named', name: 'NextPage'} } , { title: 'Fit', target:{ kind: 'goto', destination:{ kind: 'fit', page: FIRST_PAGE} } , } , ]; for (const draft of drafts){ const{ item} = await doc.outline.create(draft, { parent: C} ); expect(item).toEqual(outlineItemOfDraft(item.ref, C, draft)); } const before = itemOf(await doc.outline.get(), B)!; const patches: OutlineItemPatch[] = [{ title: 'Bee', italic: true} , { color: '#ABCDEF'} , { color: null, target: null, bold: false} , { target:{ kind: 'named', name: 'LastPage'} } , { open: true} , ]; let current = before; for (const patch of patches){ const{ item} = await doc.outline.update(B, patch); expect(item).toEqual(outlineItemAfter(current, patch, false)); current = item; } const parent = itemOf(await doc.outline.get(), C)!; const{ item: opened} = await doc.outline.update(C, { open: true} ); expect(opened).toEqual(outlineItemAfter(parent, { open: true} , true)); } ); } ); test('a move takes items together with the items under them, and names both parents', async () =>{ await withOutline(async (doc) =>{ const moved = await doc.outline.move([C, D], A, { after: A1} ); expect(moved.meta.changedRefs).toEqual([C, D]); expect(orderOf(moved.orders, null)).toEqual([6, 7]); expect(orderOf(moved.orders, A)).toEqual([10, 8, 9]); const outline = await doc.outline.get(); expect(titles(outline)).toEqual(['A', 'A1', 'C', 'C1', 'D', 'B']); expect(itemOf(outline, C)).toMatchObject({ parent: A, open: false} ); expect(itemOf(outline, C1)).toMatchObject({ parent: C} ); await doc.outline.move([C], null, 'start'); expect(childrenOf(await doc.outline.get(), null)).toEqual(['C', 'A', 'B']); } ); } ); test('a move or a create that can not be made is refused', async () =>{ await withOutline(async (doc) =>{ const invalid ={ code: EngineErrorCode.InvalidArg} ; const notFound ={ code: EngineErrorCode.NotFound} ; await expect(doc.outline.move([A], A1, 'end')).rejects.toMatchObject(invalid); await expect(doc.outline.move([A], A, 'end')).rejects.toMatchObject(invalid); await expect(doc.outline.move([A, B], null, { after: B} )).rejects.toMatchObject(invalid); await expect(doc.outline.move([A, A], null, 'end')).rejects.toMatchObject(invalid); await expect(doc.outline.move([A, A1], null, 'end')).rejects.toMatchObject(invalid); await expect(doc.outline.move([A], null, { after: C1} )).rejects.toMatchObject(notFound); await expect(doc.outline.move([toOutlineItemRef(99)], null, 'end')).rejects.toMatchObject( notFound, ); await expect( doc.outline.create({ title: 'x'} , { parent: toOutlineItemRef(3)} ), ).rejects.toMatchObject(notFound); expect(titles(await doc.outline.get())).toEqual(['A', 'A1', 'B', 'C', 'C1', 'D']); } ); } ); test('a delete takes the items under the item, and an undo brings the same ones back', async () =>{ await withOutline(async (doc) =>{ const before = await doc.outline.get(); const deleted = await doc.outline.delete(C); expect(deleted.meta.changedRefs).toEqual([C, C1]); expect(titles(await doc.outline.get())).toEqual(['A', 'A1', 'B', 'D']); const undo = await doc.apply({ undoOf: deleted.meta.opId} ); expect(undo.items.map((item) => item.type)).toEqual(['outline.restore']); expect(await doc.outline.get()).toEqual(before); } ); } ); test('expect refuses a change whose assumption does not hold', async () =>{ await withOutline(async (doc) =>{ await expect( doc.apply({ ops: [{ type: 'outline.update', ref: B, patch:{ title: 'Bee'} , expect:{ title: 'Not B'} , } , ], } ), ).rejects.toMatchObject({ code: EngineErrorCode.ChangeConflict} ); expect(itemOf(await doc.outline.get(), B)?.title).toBe('B'); } ); } ); test('each write publishes its outline event, with its result', async () =>{ await withOutline(async (doc) =>{ const events: DocumentEvent[] = []; const stop = doc.events.subscribe((event) => events.push(event)); let created: OutlineItemRef; try{ created = (await doc.outline.create({ title: 'New'} , { parent: C} )).item.ref; await doc.outline.update(created, { title: 'Newer'} ); await doc.outline.move([created], null, 'end'); await doc.outline.delete(created); } finally{ stop(); } const outline = events.filter((event) => event.type.startsWith('outline.')); expect(outline.map((event) => event.type)).toEqual([ 'outline.created', 'outline.updated', 'outline.moved', 'outline.deleted', ]); expect(outline[0]).toMatchObject({ item:{ title: 'New', parent: C} } ); expect(outline[1]).toMatchObject({ item:{ title: 'Newer'} } ); expect(outline[2]).toMatchObject({ meta:{ changedRefs: [created]} } ); expect(outline[3]).toMatchObject({ deleted: [created]} ); } ); } ); test('without doc.outline.modify every write is refused; reading still works', async () =>{ const doc = await options.openReadOnly(engine, OUTLINE_FIXTURE_PDF.slice()); try{ expect(titles(await doc.outline.get())).toEqual(['A', 'A1', 'B', 'C', 'C1', 'D']); const denied ={ code: EngineErrorCode.Forbidden} ; await expect(doc.outline.create({ title: 'x'} )).rejects.toMatchObject(denied); await expect(doc.outline.update(A, { title: 'x'} )).rejects.toMatchObject(denied); await expect(doc.outline.move([A], null, 'end')).rejects.toMatchObject(denied); await expect(doc.outline.delete(A)).rejects.toMatchObject(denied); } finally{ await doc.close(); } } ); test('an item whose page is gone keeps its place and goes nowhere it can be followed', async () =>{ await withOutline(async (doc) =>{ await doc.pages.delete([FIRST_PAGE]); const outline = await doc.outline.get(); expect(titles(outline)).toEqual(['A', 'A1', 'B', 'C', 'C1', 'D']); expect(itemOf(outline, A)?.target).toEqual({ kind: 'unsupported'} ); } ); } ); test('a broken outline reads what it can and says incomplete', async () =>{ await withOutline(async (doc) =>{ const outline = await doc.outline.get(); expect(outline.incomplete).toBe(true); expect(titles(outline)).toEqual(['One', 'Two']); await doc.outline.update(toOutlineItemRef(5), { title: 'Second'} ); expect(titles(await doc.outline.get())).toEqual(['One', 'Second']); } , BROKEN_OUTLINE_FIXTURE_PDF); } ); } ); } runPageCopyConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageCopyConformance.ts): export function runPageCopyConformance( runner: ConformanceTestRunner, options: PageCopyConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page copy conformance: ${ options.label} `, () =>{ let engine: Engine; let opened = 0; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDocument = async (run: (doc: DocumentHandle) => Promise): Promise =>{ const doc = await options.open(engine, `page-copy-${ ++opened} `); try{ await run(doc); } finally{ await doc.close(); } } ; const take = async (doc: DocumentHandle, count: number): Promise =>{ await doc.objectNumbers.reserve(count); return Array.from({ length: count} , () => doc.objectNumbers.take()!); } ; const orderOf = async (doc: DocumentHandle) => (await doc.pages.list()).pages.map((page) => page.ref.objectNumber); const fieldsOf = async (doc: DocumentHandle) =>{ const{ fields} = await doc.forms.list(); return Object.fromEntries( fields.map((field) => [ field.name, { value: 'value' in field ? field.value : null, pages: field.widgets.map((widget) => widget.page?.objectNumber ?? null), } , ]), ); } ; const annotationCountOf = async (doc: DocumentHandle, page: PageRef) => (await doc.page(page).annotations.list()).annotations.length; test('a copy reads as its page does and brings its annotations and its field, renamed', async () =>{ await withDocument(async (doc) =>{ const [copy] = await take(doc, 1); const before = await doc.pages.list(); const result = await doc.pages.copy([FIRST], 'end', { objectNumbers: [copy!]} ); expect(result.insertedPages).toEqual([toPageRef(copy!)]); expect(await orderOf(doc)).toEqual([3, 4, copy]); const source = before.pages[0]!; const copied = result.layout.pages[2]!; expect({ ...copied, index: source.index, ref: source.ref} ).toEqual(source); expect(await annotationCountOf(doc, toPageRef(copy!))).toBe( await annotationCountOf(doc, FIRST), ); expect(await fieldsOf(doc)).toEqual({ name:{ value: 'Ann', pages: [3]} , name_2:{ value: 'Ann', pages: [copy]} , } ); } ); } ); test('undo takes the copy and its field away, redo brings them back, undo again', async () =>{ await withDocument(async (doc) =>{ const [copy] = await take(doc, 1); const original = await fieldsOf(doc); const applied = await doc.apply({ ops: [{ type: 'pages.copy', pages: [FIRST], objectNumbers: [copy!]} ], } ); const copied = await fieldsOf(doc); const undo = await doc.apply({ undoOf: applied.meta.opId} ); expect(await orderOf(doc)).toEqual([3, 4]); expect(await fieldsOf(doc)).toEqual(original); const redo = await doc.apply({ undoOf: undo.meta.opId} ); expect(await orderOf(doc)).toEqual([3, 4, copy]); expect(await fieldsOf(doc)).toEqual(copied); expect(await annotationCountOf(doc, toPageRef(copy!))).toBe( await annotationCountOf(doc, FIRST), ); await doc.apply({ undoOf: redo.meta.opId} ); expect(await orderOf(doc)).toEqual([3, 4]); expect(await fieldsOf(doc)).toEqual(original); } ); } ); test('a page named twice is copied twice, in the order given', async () =>{ await withDocument(async (doc) =>{ const numbers = await take(doc, 3); await doc.pages.copy([SECOND, FIRST, SECOND], { after: FIRST} , { objectNumbers: numbers} ); expect(await orderOf(doc)).toEqual([3, ...numbers, 4]); } ); } ); test('refused: a page the document does not have, or a number the session does not hold', async () =>{ await withDocument(async (doc) =>{ const [copy] = await take(doc, 1); await expect( doc.pages.copy([toPageRef(9_999)], 'end', { objectNumbers: [copy!]} ), ).rejects.toMatchObject({ code: EngineErrorCode.NotFound} ); await expect( doc.pages.copy([FIRST], 'end', { objectNumbers: [copy! + 1_000]} ), ).rejects.toMatchObject({ code: EngineErrorCode.ObjectNumberUnavailable} ); expect(await orderOf(doc)).toEqual([3, 4]); expect(Object.keys(await fieldsOf(doc))).toEqual(['name']); } ); } ); } ); } runPageDeleteConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageDeleteConformance.ts): export function runPageDeleteConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page delete conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('pages.delete() removes the page and returns the surviving layout', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); if (before.pages.length < 2) return; const victim = before.pages[1].ref.objectNumber; const result = await doc.pages.delete([toPageRef(victim)]); expect(PageDeleteResultSchema.safeParse(result).success).toBe(true); const after = result.layout; expect(after.pages.length).toBe(before.pages.length - 1); expect(after.pageCount).toBe(before.pageCount - 1); expect(after.pages.some((p) => p.ref.objectNumber === victim)).toBe(false); const expectedOrder = before.pages .map((p) => p.ref.objectNumber) .filter((pageObjectNumber) => pageObjectNumber !== victim); expect(after.pages.map((p) => p.ref.objectNumber)).toEqual(expectedOrder); for (let i = 0; i < after.pages.length; i++){ expect(after.pages[i].index).toBe(i); } const relisted = await doc.pages.list(); expect(relisted.pages.map((p) => p.ref.objectNumber)).toEqual(expectedOrder); } finally{ await doc.close(); } } ); test('addressing a deleted page afterwards is a clean NotFound', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); if (before.pages.length < 2) return; const victim = before.pages[1].ref.objectNumber; await doc.pages.delete([toPageRef(victim)]); let caught: unknown; try{ await doc.page(toPageRef(victim)).annotations.list(); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); test('an annotation born inline keeps its baseIndex name when another page is deleted', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const inline = (await doc.annotations.list()).annotations.find( (a) => a.ref.kind === 'baseIndex', ); const victim = list.pages.find((p) => p.ref.objectNumber !== inline?.page.objectNumber); if (!inline || !victim) return; await doc.pages.delete([victim.ref]); const update = await doc.page(inline.page).annotations.update(inline.ref, { contents: 'still alive', } ); expect(update.annotation.contents).toBe('still alive'); expect(annotationKey(update.annotation.ref)).toBe(annotationKey(inline.ref)); } finally{ await doc.close(); } } ); test('deleting EVERY page is rejected with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); let caught: unknown; try{ await doc.pages.delete(list.pages.map((p) => p.ref)); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.delete() rejects duplicate PONs with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; let caught: unknown; try{ await doc.pages.delete([toPageRef(pageObjectNumber), toPageRef(pageObjectNumber)]); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.delete() rejects unknown PON with NotFound or InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); let bogus = 0; for (const p of list.pages) bogus = Math.max(bogus, p.ref.objectNumber); bogus += 9999; let caught: unknown; try{ await doc.pages.delete([toPageRef(bogus)]); } catch (err){ caught = err; } expect( EngineError.is(caught, EngineErrorCode.NotFound) || EngineError.is(caught, EngineErrorCode.InvalidArg), ).toBe(true); } finally{ await doc.close(); } } ); test('abort on pages.delete() rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); if (list.pages.length < 2) return; const pageObjectNumber = list.pages[1].ref.objectNumber; const p = doc.pages.delete([toPageRef(pageObjectNumber)]); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); } ); } runPageExtractConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageExtractConformance.ts): export function runPageExtractConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page extract conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('pages.extract() returns standalone PDF bytes and leaves the source untouched', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); const target = before.pages[before.pages.length - 1]; const bytes = await doc.pages.extract([target.ref]); expect(bytes.length > PDF_MAGIC.length).toBe(true); expect(Array.from(bytes.slice(0, PDF_MAGIC.length))).toEqual(PDF_MAGIC); const after = await doc.pages.list(); expect(after.pages.map((p) => p.ref.objectNumber)).toEqual( before.pages.map((p) => p.ref.objectNumber), ); expect(after.pageCount).toBe(before.pageCount); } finally{ await doc.close(); } } ); test('extracted bytes re-open as a document with the requested pages, in caller order', async () =>{ if (options.openKind !== 'bytes') return; const doc = await openFixture(engine, options); let extracted: DocumentHandle | null = null; try{ const list = await doc.pages.list(); if (list.pages.length < 2) return; const p0 = list.pages[0]; const p1 = list.pages[1]; const bytes = await doc.pages.extract([p1.ref, p0.ref]); extracted = await engine.open({ kind: 'bytes', id: `${ options.fixture.id} -extracted`, bytes} , EVERY_PERMISSION, ); const out = await extracted.pages.list(); expect(out.pageCount).toBe(2); expect(out.pages[0].size).toEqual(p1.size); expect(out.pages[1].size).toEqual(p0.size); } finally{ if (extracted) await extracted.close(); await doc.close(); } } ); test('pages.extract() rejects empty input with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ let caught: unknown; try{ await doc.pages.extract([]); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.extract() rejects duplicate PONs with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; let caught: unknown; try{ await doc.pages.extract([toPageRef(pageObjectNumber), toPageRef(pageObjectNumber)]); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.extract() rejects unknown PON with NotFound or InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); let bogus = 0; for (const p of list.pages) bogus = Math.max(bogus, p.ref.objectNumber); bogus += 9999; let caught: unknown; try{ await doc.pages.extract([toPageRef(bogus)]); } catch (err){ caught = err; } expect( EngineError.is(caught, EngineErrorCode.NotFound) || EngineError.is(caught, EngineErrorCode.InvalidArg), ).toBe(true); } finally{ await doc.close(); } } ); test('abort on pages.extract() rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const p = doc.pages.extract([list.pages[0].ref]); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); } ); } runPageFlattenConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageFlattenConformance.ts): export function runPageFlattenConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page flatten conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('flattens eligible appearances once without changing layout', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.pages.flatten) return; const layoutBefore = await doc.pages.list(); const pageObjectNumber = layoutBefore.pages[0].ref.objectNumber; const annotationsBefore = await doc.page(toPageRef(pageObjectNumber)).annotations.list(); const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type === 'pages.flattened') events.push(event); } ); const result = await doc.pages.flatten([toPageRef(pageObjectNumber)], { usage: 'display'} ); expect(PageFlattenResultSchema.safeParse(result).success).toBe(true); expect(result.pages).toEqual([toPageRef(pageObjectNumber)]); expect(result.usage).toBe('display'); expect(result.results.map((item) => item.status)).toEqual(['applied']); expect(result.meta.affectedPages).toEqual([toPageRef(pageObjectNumber)]); expect(events).toHaveLength(1); const layoutAfter = await doc.pages.list(); expect(layoutAfter).toEqual(layoutBefore); const annotationsAfter = await doc.page(toPageRef(pageObjectNumber)).annotations.list(); expect(annotationsAfter.annotations.length < annotationsBefore.annotations.length).toBe( true, ); const noOp = await doc.pages.flatten([toPageRef(pageObjectNumber)], { usage: 'display'} ); expect(noOp.results.map((item) => item.status)).toEqual(['unchanged']); expect(noOp.meta).toMatchObject({ affectedPages: [], cacheDelta: null, undoable: false} ); expect(events).toHaveLength(1); unsubscribe(); await expect( doc.pages.flatten([toPageRef(pageObjectNumber), toPageRef(pageObjectNumber)]), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } finally{ await doc.close(); } } ); } ); } runPageFormFieldsConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageFormFieldsConformance.ts): export function runPageFormFieldsConformance( runner: ConformanceTestRunner, options: PageFormFieldsConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page form fields conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('an insert brings the form fields of the inserted pages', async () =>{ const doc = await open(engine, options, options.target); try{ const before = await doc.pages.list(); await doc.pages.insert(await options.form.bytes()); expect(await fieldsOf(doc)).toEqual(FORM_FIELDS); const pages = new Set( (await doc.pages.list()).pages.slice(before.pageCount).map((p) => p.ref.objectNumber), ); const widgets = (await doc.forms.list()).fields.flatMap((field) => field.widgets); expect(widgets.every((widget) => widget.page && pages.has(widget.page.objectNumber))).toBe( true, ); } finally{ await doc.close(); } } ); test('the inserted fields read the same after a save in either mode', async () =>{ if (options.openKind !== 'bytes') return; for (const mode of ['rewrite', 'incremental'] as const){ const doc = await open(engine, options, options.target); let reopened: DocumentHandle | null = null; try{ await doc.pages.insert(await options.form.bytes()); const bytes = await doc.download({ mode} ); reopened = await engine.open({ kind: 'bytes', id: `${ options.target.id} -form-insert-${ mode} `, bytes} , EVERY_PERMISSION, ); expect(await fieldsOf(reopened)).toEqual(FORM_FIELDS); } finally{ if (reopened) await reopened.close(); await doc.close(); } } } ); test('fields named as the document names its own come in as name_2, kept apart', async () =>{ const doc = await open(engine, options, options.target); let reopened: DocumentHandle | null = null; try{ await doc.pages.insert(await options.form.bytes()); await doc.pages.insert(await options.form.bytes()); const fields = await fieldsOf(doc); expect(fields).toEqual({ ...FORM_FIELDS, 'person_2.name': FORM_FIELDS['person.name'], 'person_2.email': FORM_FIELDS['person.email'], plan_2: FORM_FIELDS.plan, agree_2: FORM_FIELDS.agree, } ); const name = (await doc.forms.list()).fields.find((field) => field.name === 'person.name'); await doc.forms.setValue(name!.ref, { value: 'Bea'} ); const after = await fieldsOf(doc); expect(after['person.name']!.value).toBe('Bea'); expect(after['person_2.name']!.value).toBe('Ann'); if (options.openKind !== 'bytes') return; reopened = await engine.open({ kind: 'bytes', id: `${ options.target.id} -form-insert-twice`, bytes: await doc.download(), } , EVERY_PERMISSION, ); expect(await fieldsOf(reopened)).toEqual(after); } finally{ if (reopened) await reopened.close(); await doc.close(); } } ); test('an extract brings only the fields of the extracted pages', async () =>{ const form = await open(engine, options, options.form); const doc = await open(engine, options, options.target); try{ const{ pages} = await form.pages.list(); await doc.pages.insert(await form.pages.extract([pages[1]!.ref])); expect(await fieldsOf(doc)).toEqual(SECOND_PAGE_FIELDS); } finally{ await doc.close(); await form.close(); } } ); } ); } runPageGeometryOrientationConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageGeometryOrientationConformance.ts): export function runPageGeometryOrientationConformance( runner: ConformanceTestRunner, options: PageGeometryOrientationOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page geometry orientation conformance: ${ options.label} [${ options.fixture.id} ]`, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const readSnapshot = async (): Promise<{ snapshot: PageGeometrySnapshot; close: () => Promise; } > =>{ const doc = await openFixture(engine, options); const layout = await doc.page(toPageRef(options.fixture.pageObjectNumber)).text.layout(); return{ snapshot:{ runs: [...layout.runs]} , close: () => doc.close()} ; } ; test('snapshot round-trips the wire schema', async () =>{ const{ snapshot, close} = await readSnapshot(); try{ const parsed = PageGeometrySnapshotSchema.safeParse(snapshot); expect(parsed.success).toBe(true); if (parsed.success){ expect(parsed.data).toEqual(snapshot); } } finally{ await close(); } } ); test('run starts tile the page character sequence', async () =>{ const{ snapshot, close} = await readSnapshot(); try{ let next = 0; for (const run of snapshot.runs){ expect(run.start).toBe(next); next += run.glyphs.length; } } finally{ await close(); } } ); test('runs match the fixture orientation expectation', async () =>{ const{ snapshot, close} = await readSnapshot(); try{ const expectation = options.fixture.expectation; if (expectation.kind === 'upright'){ for (const run of snapshot.runs){ expect(isRotatedGeometryRun(run)).toBe(false); if (isRotatedGeometryRun(run)) continue; for (const glyph of run.glyphs){ expect('width' in glyph.loose).toBe(true); if (glyph.empty){ expect(glyph.loose).toEqual({ x: 0, y: 0, width: 0, height: 0} ); } } } return; } if (expectation.kind === 'empty-only'){ for (const run of snapshot.runs){ expect(isRotatedGeometryRun(run)).toBe(false); if (isRotatedGeometryRun(run)) continue; for (const glyph of run.glyphs){ expect(glyph.empty).toBe(true); expect(glyph.loose).toEqual({ x: 0, y: 0, width: 0, height: 0} ); } } return; } const rotatedRuns = snapshot.runs.filter(isRotatedGeometryRun); expect(rotatedRuns.length >= (expectation.minRotatedRuns ?? 1)).toBe(true); for (const run of rotatedRuns){ expect( expectation.rotations.some((rotation) => rotationClose(run.rotation, rotation, ROTATION_TOLERANCE), ), ).toBe(true); expect(run.ascentFlip).toBe(expectation.ascentFlip); assertRotatedRunGeometry(run); } if (expectation.sheared){ const shearedGlyphs = rotatedRuns .flatMap((run) => run.glyphs) .filter( (glyph) => !glyph.empty && Math.abs(glyph.loose.lowerLeft.x - glyph.loose.upperLeft.x) > 1, ); expect(shearedGlyphs.length > 0).toBe(true); } } finally{ await close(); } } ); function assertRotatedRunGeometry(run: RotatedGeometryRun): void{ for (const glyph of run.glyphs){ if (glyph.empty){ expect(glyph.loose).toEqual({ upperLeft:{ x: 0, y: 0} , upperRight:{ x: 0, y: 0} , lowerLeft:{ x: 0, y: 0} , lowerRight:{ x: 0, y: 0} , } ); continue; } const q = glyph.loose; expect( Math.abs(q.upperRight.x - q.upperLeft.x - (q.lowerRight.x - q.lowerLeft.x)) <= COORD_TOLERANCE, ).toBe(true); expect( Math.abs(q.upperRight.y - q.upperLeft.y - (q.lowerRight.y - q.lowerLeft.y)) <= COORD_TOLERANCE, ).toBe(true); const bounds = pageQuadBounds(q); const{ rect} = run; expect(bounds.x >= rect.x - COORD_TOLERANCE).toBe(true); expect(bounds.x + bounds.width <= rect.x + rect.width + COORD_TOLERANCE).toBe(true); expect(bounds.y >= rect.y - COORD_TOLERANCE).toBe(true); expect(bounds.y + bounds.height <= rect.y + rect.height + COORD_TOLERANCE).toBe(true); } } } ); } runPageInsertBlankConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageInsertBlankConformance.ts): export function runPageInsertBlankConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page insert-blank conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('appends one blank page of the requested size with a fresh PON', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); const beforePageObjectNumbers = before.pages.map((p) => p.ref.objectNumber); const result = await doc.pages.insertBlank({ size: SIZE} ); expect(result.insertedPages.length).toBe(1); expect(result.layout.pageCount).toBe(before.pageCount + 1); expect( result.layout.pages.slice(0, before.pageCount).map((p) => p.ref.objectNumber), ).toEqual(beforePageObjectNumbers); const newPageObjectNumber = result.insertedPages[0].objectNumber; expect(beforePageObjectNumbers.includes(newPageObjectNumber)).toBe(false); const appended = result.layout.pages[before.pageCount]; expect(appended.ref.objectNumber).toBe(newPageObjectNumber); expect(appended.size).toEqual(SIZE); expect(appended.rotation).toBe(0); } finally{ await doc.close(); } } ); test('a position + count places the blank block after its neighbour', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); if (before.pages.length < 2) return; const beforePageObjectNumbers = before.pages.map((p) => p.ref.objectNumber); const result = await doc.pages.insertBlank({ size: SIZE, count: 2} , { after: before.pages[0].ref} , ); expect(result.insertedPages.length).toBe(2); expect(result.insertedPages[0].objectNumber === result.insertedPages[1].objectNumber).toBe( false, ); const pageObjectNumbers = result.layout.pages.map((p) => p.ref.objectNumber); expect(pageObjectNumbers[0]).toBe(beforePageObjectNumbers[0]); expect(pageObjectNumbers.slice(1, 3)).toEqual( result.insertedPages.map((p) => p.objectNumber), ); expect(pageObjectNumbers.slice(3)).toEqual(beforePageObjectNumbers.slice(1)); expect(result.layout.pages[1].size).toEqual(SIZE); expect(result.layout.pages[2].size).toEqual(SIZE); } finally{ await doc.close(); } } ); test('the blank pages persist through save → re-open', async () =>{ if (options.openKind !== 'bytes') return; const doc = await openFixture(engine, options); let reopened: DocumentHandle | null = null; try{ const before = await doc.pages.list(); await doc.pages.insertBlank({ size: SIZE} ); const bytes = await doc.download(); reopened = await engine.open({ kind: 'bytes', id: `${ options.fixture.id} -insert-blank-reopen`, bytes, } , EVERY_PERMISSION, ); const after = await reopened.pages.list(); expect(after.pageCount).toBe(before.pageCount + 1); const tail = after.pages[after.pageCount - 1]; expect(Math.round(tail.size.width)).toBe(SIZE.width); expect(Math.round(tail.size.height)).toBe(SIZE.height); } finally{ if (reopened) await reopened.close(); await doc.close(); } } ); test('non-positive size and bad count reject with InvalidArg; an unknown neighbour with NotFound', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); const rejects: Array<() => Promise> = [ () => doc.pages.insertBlank({ size:{ width: 0, height: 612} } ), () => doc.pages.insertBlank({ size:{ width: 396, height: -10} } ), () => doc.pages.insertBlank({ size: SIZE, count: 0} ), () => doc.pages.insertBlank({ size: SIZE, count: PAGE_INSERT_BLANK_MAX_COUNT + 1} ), ]; for (const attempt of rejects){ let caught: unknown; try{ await attempt(); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } let caught: unknown; try{ await doc.pages.insertBlank({ size: SIZE} , { after: toPageRef(UNKNOWN_PAGE)} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); const list = await doc.pages.list(); expect(list.pageCount).toBe(before.pageCount); expect(list.pages.map((p) => p.ref.objectNumber)).toEqual( before.pages.map((p) => p.ref.objectNumber), ); } finally{ await doc.close(); } } ); } ); } runPageInsertConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageInsertConformance.ts): export function runPageInsertConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page insert conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('appends every source page with fresh PONs; existing pages keep identity', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); const beforePageObjectNumbers = before.pages.map((p) => p.ref.objectNumber); const single = await doc.pages.extract([toPageRef(beforePageObjectNumbers[0])]); const result = await doc.pages.insert(single); expect(result.insertedPages.length).toBe(1); expect(result.layout.pageCount).toBe(before.pageCount + 1); expect( result.layout.pages.slice(0, before.pageCount).map((p) => p.ref.objectNumber), ).toEqual(beforePageObjectNumbers); const newPageObjectNumber = result.insertedPages[0].objectNumber; expect(beforePageObjectNumbers.includes(newPageObjectNumber)).toBe(false); expect(result.layout.pages[before.pageCount].ref.objectNumber).toBe(newPageObjectNumber); expect(result.layout.pages[before.pageCount].size).toEqual(before.pages[0].size); } finally{ await doc.close(); } } ); test('a position places the block after its neighbour, in source order', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); if (before.pages.length < 2) return; const beforePageObjectNumbers = before.pages.map((p) => p.ref.objectNumber); const two = await doc.pages.extract([ toPageRef(beforePageObjectNumbers[0]), toPageRef(beforePageObjectNumbers[1]), ]); const result = await doc.pages.insert(two, { after: before.pages[0].ref} ); expect(result.insertedPages.length).toBe(2); const pageObjectNumbers = result.layout.pages.map((p) => p.ref.objectNumber); expect(pageObjectNumbers[0]).toBe(beforePageObjectNumbers[0]); expect(pageObjectNumbers.slice(1, 3)).toEqual( result.insertedPages.map((p) => p.objectNumber), ); expect(pageObjectNumbers.slice(3)).toEqual(beforePageObjectNumbers.slice(1)); } finally{ await doc.close(); } } ); test('the inserted pages persist through save → re-open', async () =>{ if (options.openKind !== 'bytes') return; const doc = await openFixture(engine, options); let reopened: DocumentHandle | null = null; try{ const before = await doc.pages.list(); const single = await doc.pages.extract([before.pages[0].ref]); await doc.pages.insert(single); const bytes = await doc.download(); reopened = await engine.open({ kind: 'bytes', id: `${ options.fixture.id} -insert-reopen`, bytes, } , EVERY_PERMISSION, ); const after = await reopened.pages.list(); expect(after.pageCount).toBe(before.pageCount + 1); } finally{ if (reopened) await reopened.close(); await doc.close(); } } ); test('empty bytes reject with InvalidArg; garbage rejects with MalformedPdf', async () =>{ const doc = await openFixture(engine, options); try{ let caught: unknown; try{ await doc.pages.insert(new Uint8Array(0)); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); caught = undefined; try{ await doc.pages.insert(new TextEncoder().encode('not a pdf at all')); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.MalformedPdf)).toBe(true); const list = await doc.pages.list(); expect(list.pageCount > 0).toBe(true); } finally{ await doc.close(); } } ); test('a neighbour that is not a page of the document rejects with NotFound', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); const single = await doc.pages.extract([before.pages[0].ref]); let caught: unknown; try{ await doc.pages.insert(single, { before: toPageRef(UNKNOWN_PAGE)} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); expect((await doc.pages.list()).pageCount).toBe(before.pageCount); } finally{ await doc.close(); } } ); } ); } runPagePredictionConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPagePredictionConformance.ts): export function runPagePredictionConformance( runner: ConformanceTestRunner, options: PagePredictionConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page prediction conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine); } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); const read = async (): Promise =>{ const{ pages, labels} = await doc.pages.list(); return{ pages, labels} ; } ; const take = async (count: number): Promise =>{ if (count === 0) return []; await doc.objectNumbers.reserve(count); return Array.from({ length: count} , () => doc.objectNumbers.take()!); } ; for (const scenario of CASES){ test(scenario.name, async () =>{ const before = await read(); const op = scenario.op(before.pages, await take(scenario.numbers ?? 0)); const predicted = pagesAfter(before, op); const applied = await doc.apply({ ops: [op]} ); const after = await read(); expect(differences(predicted, after)).toEqual([]); const undone = undoneOf(before, after, op); const undo = await doc.apply({ undoOf: applied.meta.opId} ); const afterUndo = await read(); expect(differences(undone, afterUndo)).toEqual([]); const redone = pagesAfter(afterUndo, op); const redo = await doc.apply({ undoOf: undo.meta.opId} ); expect(differences(redone, await read())).toEqual([]); await doc.apply({ undoOf: redo.meta.opId} ); } ); } for (const scenario of REFUSALS){ test(`refused: ${ scenario.name} `, async () =>{ const before = await read(); const op = scenario.op(before.pages, await take(scenario.numbers ?? 0)); expect(pagesAfter(before, op)).toBe(before); const outcome = await doc.apply({ ops: [op]} ).then( () => 'applied', () => 'refused', ); expect(outcome).toBe('refused'); expect(differences(before, await read())).toEqual([]); } ); } } ); } runPageRenderConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageRenderConformance.ts): export function runPageRenderConformance( runner: ConformanceTestRunner, options: PageRenderConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page render conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; let page: PageHandle; let layout: PageLayout; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine); const{ pages} = await doc.pages.list(); layout = pages[0]!; page = doc.page(layout.ref); } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); test('the layout reports where the page sits in PDF space', async () =>{ const{ pages} = await doc.pages.list(); expect(pages[0]!.size).toEqual({ width: 400, height: 400} ); expect(pages[0]!.pdfCropBox).toEqual({ left: 100, bottom: 200, right: 500, top: 600} ); expect(pages[0]!.boxes.crop).toEqual({ x: 0, y: 0, width: 400, height: 400} ); } ); test('an image reports the size of its pixels', async () =>{ const cases: Array<{ options: PageImageOptions; size: [number, number]} > = [{ options:{ } , size: [400, 400]} , { options:{ viewport:{ kind: 'scale', scale: 0.25} } , size: [100, 100]} , { options:{ viewport:{ kind: 'width', width: 123} } , size: [123, 123]} , { options:{ target:{ kind: 'rect', rect:{ x: 100, y: 250, width: 100, height: 50} } , rotation: 90, } , size: [50, 100], } , { options:{ target:{ kind: 'rect', rect:{ x: 100, y: 250, width: 100, height: 50} } , viewport:{ kind: 'width', width: 30} , } , size: [30, 15], } , ]; for (const{ options, size} of cases){ const image = await page.render.image({ format: 'png', ...options} ); const raster = await decode(image); expect([image.width, image.height]).toEqual(size); expect([raster.width, raster.height]).toEqual(size); } } ); test('a page image starts at the crop box', async () =>{ const raster = await decode( await page.render.image({ format: 'png', viewport:{ kind: 'scale', scale: 0.5} } ), ); expect(isDark(pixel(raster, 75, 125))).toBe(true); expect(isDark(pixel(raster, 25, 25))).toBe(false); } ); test("a target rect is in page space, from the crop box's top-left", async () =>{ const square = await decode( await page.render.image({ format: 'png', target:{ kind: 'rect', rect: SQUARE_ON_PAGE} , viewport:{ kind: 'scale', scale: 0.1} , } ), ); expect([square.width, square.height]).toEqual([10, 10]); expect(everyPixel(square, isDark)).toBe(true); const beside = await decode( await page.render.image({ format: 'png', target:{ kind: 'rect', rect:{ x: 200, y: 200, width: 100, height: 100} } , viewport:{ kind: 'scale', scale: 0.1} , } ), ); expect(everyPixel(beside, (rgba) => !isDark(rgba))).toBe(true); } ); test('an appearance on a cropped page renders its own area', async () =>{ const{ annotation} = await page.annotations.create({ subtype: 'square', box: SQUARE_ON_PAGE, color: '#ff0000', interiorColor: '#ff0000', } ); try{ const{ appearances} = await page.annotations.renderAppearances({ format: 'png'} ); const found = appearances.find( (a) => a.mode === 'normal' && annotationKey(a.ref) === annotationKey(annotation.ref), ); expect(found !== undefined).toBe(true); const{ x, y, width, height} = found!.rect; expect(Math.abs(x - SQUARE_ON_PAGE.x) <= 2 && Math.abs(y - SQUARE_ON_PAGE.y) <= 2).toBe( true, ); expect(Math.abs(width - 100) <= 4 && Math.abs(height - 100) <= 4).toBe(true); const raster = await decode(found!.image); const [r, g, b, a] = pixel(raster, raster.width >> 1, raster.height >> 1); expect(r > 200 && g < 60 && b < 60 && a > 200).toBe(true); } finally{ await page.annotations.delete(annotation.ref); } } ); test("an image's transform is pageTransform's, and puts the page where its pixels are", async () =>{ const cases: PageImageOptions[] = [{ viewport:{ kind: 'scale', scale: 0.5} } , { viewport:{ kind: 'scale', scale: 0.5} , rotation: 90} , { viewport:{ kind: 'width', width: 150} , rotation: 180} , { viewport:{ kind: 'width', width: 150} , rotation: 270} , { target:{ kind: 'rect', rect:{ x: 50, y: 150, width: 200, height: 160} } , viewport:{ kind: 'width', width: 100} , rotation: 90, } , ]; for (const options of cases){ const image = await page.render.image({ format: 'png', ...options} ); const{ transform} = image; expect([transform.width, transform.height]).toEqual([image.width, image.height]); const expected = pageTransform(layout, options); expect([expected.width, expected.height]).toEqual([image.width, image.height]); expect(transform.matrix.every((n, i) => Math.abs(n - expected.matrix[i]!) < 1e-9)).toBe( true, ); const raster = await decode(image); const inside = transform.pageToPixels({ x: 150, y: 250} ); expect(isDark(pixel(raster, Math.floor(inside.x), Math.floor(inside.y)))).toBe(true); const outside = transform.pageToPixels({ x: 70, y: 250} ); expect(isDark(pixel(raster, Math.floor(outside.x), Math.floor(outside.y)))).toBe(false); const back = transform.pixelsToPage(inside); expect(Math.abs(back.x - 150) < 1e-9 && Math.abs(back.y - 250) < 1e-9).toBe(true); } } ); test('blob() is the image, the same bytes its object URL serves', async () =>{ const image = await page.render.image({ format: 'png', viewport:{ kind: 'scale', scale: 0.25} , } ); const blob = await image.blob(); expect(blob.type).toBe(image.mimeType); const bytes = new Uint8Array(await blob.arrayBuffer()); const decoded = await decodePng(bytes); expect([decoded.width, decoded.height]).toEqual([image.width, image.height]); const{ url, revoke} = await image.objectUrl(); try{ const served = new Uint8Array(await (await fetch(url)).arrayBuffer()); expect(served.length === bytes.length && served.every((b, i) => b === bytes[i])).toBe(true); } finally{ revoke(); } } ); test('quality goes from 0 to 1', async () =>{ for (const quality of [0, 0.5, 1]){ const image = await page.render.image({ format: 'png', quality, viewport:{ kind: 'scale', scale: 0.1} , } ); expect([image.width, image.height]).toEqual([40, 40]); } for (const quality of [-0.1, 1.5, 80]){ await expect( page.render.image({ format: 'png', quality, viewport:{ kind: 'scale', scale: 0.1} } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } } ); } ); } runPageReorderConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageReorderConformance.ts): export function runPageReorderConformance( runner: ConformanceTestRunner, options: PageReorderConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const fix = options.fixture; describe(`page reorder conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('pages.list() returns every page in display order, durable PONs only', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); expect(PageListSnapshotSchema.safeParse(list).success).toBe(true); expect(list.pages.length >= 1).toBe(true); for (let i = 0; i < list.pages.length; i++){ expect(list.pages[i].index).toBe(i); expect(list.pages[i].ref.objectNumber > 0).toBe(true); } const seen = new Set(); for (const p of list.pages){ expect(seen.has(p.ref.objectNumber)).toBe(false); seen.add(p.ref.objectNumber); } } finally{ await doc.close(); } } ); test('pages.reorder() moves pages to a position and returns the full new order', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); if (before.pages.length < 3) return; const pageObjectNumbers = pickReorderPageObjectNumbers( before.pages.map((p) => p.ref.objectNumber), fix, ); if (!pageObjectNumbers) return; const target = pageObjectNumbers[pageObjectNumbers.length - 1]; const result = await doc.pages.reorder([toPageRef(target)], 'start'); expect(PageReorderResultSchema.safeParse(result).success).toBe(true); expect(result.pages.map((p) => p.objectNumber)).toEqual([target]); const after = result.layout; expect(after.pages.length).toBe(before.pages.length); expect(after.pages[0].ref.objectNumber).toBe(target); for (let i = 0; i < after.pages.length; i++){ expect(after.pages[i].index).toBe(i); } const beforePageObjectNumbers = new Set(before.pages.map((p) => p.ref.objectNumber)); const afterPageObjectNumbers = new Set(after.pages.map((p) => p.ref.objectNumber)); expect(beforePageObjectNumbers.size).toBe(afterPageObjectNumbers.size); for (const pageObjectNumber of beforePageObjectNumbers) expect(afterPageObjectNumbers.has(pageObjectNumber)).toBe(true); const relisted = await doc.pages.list(); expect(relisted.pages.map((p) => p.ref.objectNumber)).toEqual( after.pages.map((p) => p.ref.objectNumber), ); } finally{ await doc.close(); } } ); test('an annotation born inline keeps its baseIndex name across a page reorder', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const inline = (await doc.annotations.list()).annotations.find( (a) => a.ref.kind === 'baseIndex', ); const other = list.pages.find((p) => p.ref.objectNumber !== inline?.page.objectNumber); if (!inline || !other) return; await doc.pages.reorder([other.ref], 'start'); const update = await doc.page(inline.page).annotations.update(inline.ref, { contents: 'still alive', } ); expect(update.annotation.contents).toBe('still alive'); expect(annotationKey(update.annotation.ref)).toBe(annotationKey(inline.ref)); } finally{ await doc.close(); } } ); test('pages.reorder() puts the pages right before or after their neighbour, in the order given', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); if (before.pages.length < 3) return; const [first, second, third] = before.pages.map((p) => p.ref); const order = async () => (await doc.pages.list()).pages.map((p) => p.ref.objectNumber); const rest = before.pages.slice(3).map((p) => p.ref.objectNumber); await doc.pages.reorder([third!, first!], { after: second!} ); expect(await order()).toEqual([ second!.objectNumber, third!.objectNumber, first!.objectNumber, ...rest, ]); await doc.pages.reorder([first!], { before: second!} ); expect(await order()).toEqual([ first!.objectNumber, second!.objectNumber, third!.objectNumber, ...rest, ]); const last = before.pages[before.pages.length - 1]!.ref; await doc.pages.reorder([first!], 'end'); expect((await order()).at(-1)).toBe(first!.objectNumber); await doc.pages.reorder([first!], { before: second!} ); expect((await order()).at(-1)).toBe(last.objectNumber); } finally{ await doc.close(); } } ); test('pages.reorder() rejects duplicate PONs with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); if (list.pages.length < 1) return; const target = list.pages[0].ref; let caught: unknown; try{ await doc.pages.reorder([target, target], 'start'); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.reorder() rejects a neighbour that is one of the moved pages with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); if (list.pages.length < 2) return; const [first, second] = list.pages.map((p) => p.ref); let caught: unknown; try{ await doc.pages.reorder([first!, second!], { after: second!} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.reorder() rejects an unknown page or neighbour with NotFound', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); let bogus = 0; for (const p of list.pages) bogus = Math.max(bogus, p.ref.objectNumber); bogus += 9999; const refused = async (attempt: () => Promise) =>{ try{ await attempt(); } catch (err){ return err; } return undefined; } ; const unknownPage = await refused(() => doc.pages.reorder([toPageRef(bogus)], 'start')); expect(EngineError.is(unknownPage, EngineErrorCode.NotFound)).toBe(true); const unknownNeighbour = await refused(() => doc.pages.reorder([list.pages[0]!.ref], { after: toPageRef(bogus)} ), ); expect(EngineError.is(unknownNeighbour, EngineErrorCode.NotFound)).toBe(true); expect((await doc.pages.list()).pages.map((p) => p.ref.objectNumber)).toEqual( list.pages.map((p) => p.ref.objectNumber), ); } finally{ await doc.close(); } } ); test('abort on pages.reorder() rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); if (list.pages.length < 1) return; const target = list.pages[0].ref; const p = doc.pages.reorder([target], 'start'); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); } ); } runPageRotateConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageRotateConformance.ts): export function runPageRotateConformance( runner: ConformanceTestRunner, options: ConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page rotate conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('pages.rotate() sets the absolute rotation and returns the full layout', async () =>{ const doc = await openFixture(engine, options); try{ const before = await doc.pages.list(); const target = before.pages[0]; const result = await doc.pages.rotate([target.ref], 90); expect(PageRotateResultSchema.safeParse(result).success).toBe(true); const after = result.layout; const rotated = after.pages.find((p) => p.ref.objectNumber === target.ref.objectNumber); expect(rotated?.rotation).toBe(90); expect(rotated?.size.width).toBe(target.size.width); expect(rotated?.size.height).toBe(target.size.height); expect(after.pages.map((p) => p.ref.objectNumber)).toEqual( before.pages.map((p) => p.ref.objectNumber), ); const relisted = await doc.pages.list(); expect( relisted.pages.find((p) => p.ref.objectNumber === target.ref.objectNumber)?.rotation, ).toBe(90); } finally{ await doc.close(); } } ); test('absolute rotation is idempotent: setting the same value twice is a no-op', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; const first = await doc.pages.rotate([toPageRef(pageObjectNumber)], 180); const second = await doc.pages.rotate([toPageRef(pageObjectNumber)], 180); expect(second.layout.pages.map((p) => [p.ref.objectNumber, p.rotation])).toEqual( first.layout.pages.map((p) => [p.ref.objectNumber, p.rotation]), ); } finally{ await doc.close(); } } ); test('one rotation applies to EVERY listed page (the multi-select gesture)', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); if (list.pages.length < 2) return; const pageObjectNumbers = list.pages.slice(0, 2).map((p) => p.ref.objectNumber); const result = await doc.pages.rotate(pageObjectNumbers.map(toPageRef), 270); for (const pageObjectNumber of pageObjectNumbers){ expect( result.layout.pages.find((p) => p.ref.objectNumber === pageObjectNumber)?.rotation, ).toBe(270); } } finally{ await doc.close(); } } ); test('an annotation born inline keeps its baseIndex name when its page is rotated', async () =>{ const doc = await openFixture(engine, options); try{ const inline = (await doc.annotations.list()).annotations.find( (a) => a.ref.kind === 'baseIndex', ); if (!inline) return; await doc.pages.rotate([inline.page], 90); const update = await doc.page(inline.page).annotations.update(inline.ref, { contents: 'still alive', } ); expect(update.annotation.contents).toBe('still alive'); expect(annotationKey(update.annotation.ref)).toBe(annotationKey(inline.ref)); } finally{ await doc.close(); } } ); test('pages.rotate() rejects an invalid rotation value with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; let caught: unknown; try{ await doc.pages.rotate([toPageRef(pageObjectNumber)], 45 as never); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.rotate() rejects duplicate PONs with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; let caught: unknown; try{ await doc.pages.rotate([toPageRef(pageObjectNumber), toPageRef(pageObjectNumber)], 90); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('pages.rotate() rejects unknown PON with NotFound or InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); let bogus = 0; for (const p of list.pages) bogus = Math.max(bogus, p.ref.objectNumber); bogus += 9999; let caught: unknown; try{ await doc.pages.rotate([toPageRef(bogus)], 90); } catch (err){ caught = err; } expect( EngineError.is(caught, EngineErrorCode.NotFound) || EngineError.is(caught, EngineErrorCode.InvalidArg), ).toBe(true); } finally{ await doc.close(); } } ); test('abort on pages.rotate() rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; const p = doc.pages.rotate([toPageRef(pageObjectNumber)], 90); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); } ); } runPageSpaceConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageSpaceConformance.ts): export function runPageSpaceConformance( runner: ConformanceTestRunner, options: PageSpaceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const fixtures = PAGE_SPACE_FIXTURES.filter( (fixture) => !options.only || options.only.includes(fixture.name), ); describe(`page space conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); for (const fixture of fixtures){ describe(`${ fixture.name} : ${ fixture.about} `, () =>{ let doc: DocumentHandle; let layouts: PageLayout[]; beforeAll(async () =>{ doc = await options.open(engine, fixture); layouts = (await doc.pages.list()).pages; } ); afterAll(async () =>{ if (doc) await doc.close(); } ); const eachPage = async ( check: (page: PageSpaceFixturePage, layout: PageLayout) => Promise, ) =>{ expect(layouts.length).toBe(fixture.pages.length); for (const [index, page] of fixture.pages.entries()){ await check(page, layouts[index]!); } } ; const eachShownPage = ( check: (page: PageSpaceFixturePage, layout: PageLayout) => Promise, ) => eachPage((page, layout) => hasArea(page.expected.visible) ? check(page, layout) : Promise.resolve(), ); test('the page size is the visible page box', async () =>{ await eachPage(async (page, layout) =>{ const visible = page.expected.visible; expect(layout.size).toEqual({ width: visible.right - visible.left, height: visible.top - visible.bottom, } ); } ); } ); test('the boxes are as ISO defines them, measured from the visible page', async () =>{ await eachPage(async (page, layout) =>{ const{ boxes, visible} = page.expected; expect(layout.pdfCropBox).toEqual(visible); expect(layout.boxes).toEqual({ media: toPage(boxes.media, visible), crop: toPage(boxes.crop, visible), bleed: toPage(boxes.bleed, visible), trim: toPage(boxes.trim, visible), art: toPage(boxes.art, visible), } ); expect(layout.boxes.crop).toEqual({ x: 0, y: 0, width: width(visible), height: height(visible), } ); } ); } ); test('the turn and the unit size', async () =>{ await eachPage(async (page, layout) =>{ expect(layout.rotation).toBe(page.expected.rotation); expect(layout.userUnit).toBe(page.expected.userUnit); } ); } ); test('the tab order', async () =>{ await eachPage(async (page, layout) =>{ expect(layout.tabOrder).toBe(page.expected.tabOrder ?? null); } ); } ); test("a render starts at the visible page box's top-left", async () =>{ await eachShownPage(async (page, layout) =>{ const visible = page.expected.visible; const scale = scaleFor(visible); const raster = await render(doc, layout.ref, { viewport:{ kind: 'scale', scale} } ); expect(Math.abs(raster.width - width(visible) * scale) <= 1).toBe(true); expect(Math.abs(raster.height - height(visible) * scale) <= 1).toBe(true); for (const mark of page.marks){ expect(darkAt(raster, middleOf(toPage(mark, visible)), scale)).toBe(true); } expect(darkAt(raster, { x: 20, y: 20} , scale)).toBe(false); } ); } ); test('text is found where it is drawn', async () =>{ const slice = await doc.search.query({ text: 'Corner'} ); await eachShownPage(async (page, layout) =>{ const visible = page.expected.visible; const word = page.words[0]!; const match = slice.matches.find((m) => samePage(m.page, layout.ref)); expect(match !== undefined).toBe(true); const box = match!.segments[0]!.rect; expect(Math.abs(box.x - (word.x - visible.left)) <= 3).toBe(true); expect(box.y < visible.top - word.y && box.y + box.height > visible.top - word.y).toBe( true, ); const scale = scaleFor(visible); const raster = await render(doc, layout.ref, { viewport:{ kind: 'scale', scale} } ); expect(darkInside(raster, box, scale) > 0).toBe(true); } ); } ); test('a created annotation is drawn where it was put', async () =>{ await eachShownPage(async (page, layout) =>{ const visible = page.expected.visible; const spot: PageBox ={ x: width(visible) / 2 - 20, y: height(visible) / 2 - 20, width: 40, height: 40, } ; const handle = doc.page(layout.ref); const{ annotation} = await handle.annotations.create({ subtype: 'square', box: spot, color: '#000000', interiorColor: '#000000', } ); try{ const read = annotation.rect; expect(read.x <= spot.x && read.x + read.width >= spot.x + spot.width).toBe(true); expect(read.y <= spot.y && read.y + read.height >= spot.y + spot.height).toBe(true); const scale = scaleFor(visible); const raster = await render(doc, layout.ref, { viewport:{ kind: 'scale', scale} , includeAnnotations: true, } ); expect(darkAt(raster, middleOf(spot), scale)).toBe(true); } finally{ await handle.annotations.delete(annotation.ref); } } ); } ); test("a form field's widget is placed where it was put", async () =>{ await eachShownPage(async (page, layout) =>{ const visible = page.expected.visible; const spot: PageBox ={ x: width(visible) / 2 - 30, y: height(visible) / 2 - 10, width: 60, height: 20, } ; const{ field, widgets} = await doc.forms.create({ kind: 'text', name: `placed_${ layout.ref.objectNumber} `, widgets: [{ page: layout.ref, rect: spot} ], } ); try{ const widget = field.widgets[0]!; expect(widgets.map((w) => w.rect)).toEqual([spot]); const read = (await doc.forms.list()).widgets.find( (w) => w.ref.kind === 'objectNumber' && w.ref.objectNumber === widget.objectNumber, ); expect(read?.rect).toEqual(spot); } finally{ await doc.forms.delete(field.ref); } } ); } ); test('a region render shows its own area', async () =>{ await eachShownPage(async (page, layout) =>{ const raster = await render(doc, layout.ref, { target:{ kind: 'rect', rect: toPage(page.marks[0]!, page.expected.visible)} , viewport:{ kind: 'scale', scale: 0.1} , } ); expect(raster.width > 0 && raster.height > 0).toBe(true); expect(everyPixelDark(raster)).toBe(true); } ); } ); if (fixture.pages.some((page) => page.links?.length)){ test("a destination is measured from its target page's visible box", async () =>{ await eachPage(async (page, layout) =>{ if (!page.links?.length) return; const{ annotations} = await doc.page(layout.ref).annotations.list(); const links = annotations.filter( (a): a is Extract => a.subtype === 'link', ); for (const link of page.links){ const read = links.find((a) => sameBox(a.rect, toPage(link.rect, page.expected.visible)), ); expect(read !== undefined).toBe(true); const target = read!.target; expect(target?.kind).toBe('goto'); if (target?.kind !== 'goto') continue; const destination = target.destination; expect(samePage(destination.page, layouts[link.toPage]!.ref)).toBe(true); expect(placeOf(destination)).toEqual(link.expected); } } ); } ); } if (fixture.pages.some((page) => page.openAction)){ test("a page's open action is measured from its target page's visible box", async () =>{ await eachPage(async (page, layout) =>{ if (!page.openAction) return; const root = layout.actions?.open?.root; expect(root?.type).toBe('goto'); if (root?.type !== 'goto') return; const target = layouts[page.openAction.toPage]!.ref; expect(samePage(root.destination.page, target)).toBe(true); expect(placeOf(root.destination)).toEqual(page.openAction.expected); } ); } ); } if (fixture.fieldAction){ const{ toPage, expected} = fixture.fieldAction; test("a field's actions are measured from their target page's visible box", async () =>{ const{ fields} = await doc.forms.list(); const script = fields.find((field) => field.name === 'total')?.actions?.calculate?.root; expect(script?.type).toBe('javascript'); const goTo = script?.next[0]; expect(goTo?.type).toBe('goto'); if (goTo?.type !== 'goto') return; expect(samePage(goTo.destination.page, layouts[toPage]!.ref)).toBe(true); expect(placeOf(goTo.destination)).toEqual(expected); } ); } if (fixture.openDestination){ const{ toPage, expected} = fixture.openDestination; test("the document's open destination is measured from its page's visible box", async () =>{ const{ openDestination} = await doc.actions.get(); expect(openDestination != null).toBe(true); expect(samePage(openDestination!.page, layouts[toPage]!.ref)).toBe(true); expect(placeOf(openDestination!)).toEqual(expected); } ); } test('a redaction removes what is inside it, and only that', async () =>{ const page = fixture.pages[0]!; const layout = layouts[0]!; const visible = page.expected.visible; if (!hasArea(visible)) return; const slice = await doc.search.query({ text: 'Corner'} ); const match = slice.matches.find((m) => samePage(m.page, layout.ref)); expect(match !== undefined).toBe(true); const found = match!.segments[0]!.rect; const handle = doc.page(layout.ref); const{ annotation} = await handle.annotations.create({ subtype: 'redact', rect:{ x: found.x - 2, y: found.y - 2, width: found.width + 4, height: found.height + 4, } , } ); await doc.redaction.apply({ annotations: [annotation.ref]} ); const after = await doc.search.query({ text: 'Corner'} ); expect(after.matches.some((m) => samePage(m.page, layout.ref))).toBe(false); const scale = scaleFor(visible); const raster = await render(doc, layout.ref, { viewport:{ kind: 'scale', scale} } ); expect(darkInside(raster, found, scale)).toBe(0); for (const mark of page.marks){ expect(darkAt(raster, middleOf(toPage(mark, visible)), scale)).toBe(true); } } ); } ); } } ); } runPageTextConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPageTextConformance.ts): export function runPageTextConformance( runner: ConformanceTestRunner, options: PageTextConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`page text conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('read() returns a PageTextSnapshot with non-empty text', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const snap = await page.text.get(); expect(PageTextSnapshotSchema.safeParse(snap).success).toBe(true); expect(snap.charCount >= options.fixture.minCharCount).toBe(true); expect(snap.text.length > 0).toBe(true); } finally{ await doc.close(); } } ); test('extracted text contains the expected substring', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const snap = await page.text.get(); expect(snap.text.includes(options.fixture.expectedSubstring)).toBe(true); } finally{ await doc.close(); } } ); test('read() on an unknown pageObjectNumber throws NotFound', async () =>{ const doc = await openFixture(engine, options); try{ let caught: unknown; try{ const ghost = doc.page(toPageRef(999_999_999)); await ghost.text.get(); } catch (err){ caught = err; } expect(caught).toBeTruthy(); expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); test('abort() on read rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); const p = page.text.get(); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); test('read after close throws DocNotOpen', async () =>{ const doc = await openFixture(engine, options); const page = doc.page(toPageRef(options.fixture.pageObjectNumber)); await doc.close(); let caught: unknown; try{ await page.text.get(); } catch (err){ caught = err; } expect(caught).toBeTruthy(); expect(EngineError.is(caught, EngineErrorCode.DocNotOpen)).toBe(true); } ); } ); } runPermissionConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPermissionConformance.ts): export function runPermissionConformance( runner: ConformanceTestRunner, options: PermissionConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`permission conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const as = async (token: PermissionToken, body: (doc: DocumentHandle) => Promise) =>{ const doc = await options.open(engine, PERMISSION_TOKENS[token]); try{ await body(doc); } finally{ await doc.close(); } } ; const refusal = (attempt: Promise): Promise => attempt.then( () => null, (error: unknown) => error, ); const outcome = (error: unknown) => EngineError.is(error) ? error.code : error === null ? 'resolved' : String(error); const expectRefused = (error: unknown, code: EngineErrorCode) =>{ expect(outcome(error)).toBe(code); } ; const keys = (refs: readonly AnnotationRef[]) => refs.map(annotationKey); test('lists: each token reads its own family and is refused the other', async () =>{ await as('everything', async (doc) =>{ const{ annotations} = await doc.page(PAGE).annotations.list(); expect(keys(annotations.map((a) => a.ref))).toEqual( keys([SQUARE, ...[6, 7, 8].map((n) => ({ ...SQUARE, objectNumber: n} ))]), ); const form = await doc.forms.list(); expect(form.fields.map((field) => field.name)).toEqual(['name']); expect(keys(form.widgets.map((row) => row.ref))).toEqual(keys([WIDGET])); } ); await as('fill', async (doc) =>{ const form = await doc.forms.list(); expect(keys(form.widgets.map((row) => row.ref))).toEqual(keys([WIDGET])); expectRefused(await refusal(doc.page(PAGE).annotations.list()), EngineErrorCode.Forbidden); expectRefused(await refusal(doc.annotations.list()), EngineErrorCode.Forbidden); } ); await as('comment', async (doc) =>{ const{ annotations} = await doc.page(PAGE).annotations.list(); expect(annotations).toHaveLength(4); expect(annotations.some((a) => a.subtype === 'widget')).toBe(false); expectRefused(await refusal(doc.forms.list()), EngineErrorCode.Forbidden); } ); } ); test('appearance images: each family takes its own read', async () =>{ await as('everything', async (doc) =>{ const page = doc.page(PAGE); const forms = await page.forms.renderAppearances(); expect(new Set(keys(forms.appearances.map((a) => a.ref)))).toEqual(new Set(keys([WIDGET]))); const annotations = await page.annotations.renderAppearances(); expect( keys(annotations.appearances.map((a) => a.ref)).includes(annotationKey(WIDGET)), ).toBe(false); } ); await as('fill', async (doc) =>{ const page = doc.page(PAGE); const forms = await page.forms.renderAppearances(); expect(new Set(keys(forms.appearances.map((a) => a.ref)))).toEqual(new Set(keys([WIDGET]))); expectRefused( await refusal(page.annotations.renderAppearances()), EngineErrorCode.Forbidden, ); } ); await as('comment', async (doc) =>{ const page = doc.page(PAGE); const annotations = await page.annotations.renderAppearances(); expect( keys(annotations.appearances.map((a) => a.ref)).includes(annotationKey(WIDGET)), ).toBe(false); expectRefused(await refusal(page.forms.renderAppearances()), EngineErrorCode.Forbidden); } ); } ); test('pictures: a left-out layer never asks for more than the token may read', async () =>{ await as('fill', async (doc) =>{ const page = doc.page(PAGE); await page.render.image(); expectRefused( await refusal(page.render.image({ includeAnnotations: true} )), EngineErrorCode.Forbidden, ); } ); await as('comment', async (doc) =>{ const page = doc.page(PAGE); await page.render.image(); await page.render.image({ includeAnnotations: true} ); expectRefused( await refusal(page.render.image({ includeFormFields: true} )), EngineErrorCode.Forbidden, ); } ); } ); test('writes: each token writes its own family; the annotation verbs refuse a widget', async () =>{ await as('fill', async (doc) =>{ const filled = await doc.forms.setValue(NAME, { value: 'Bea'} ); expect(keys(filled.widgets.map((row) => row.ref))).toEqual(keys([WIDGET])); expect('annotations' in filled).toBe(false); expectRefused( await refusal(doc.page(PAGE).annotations.create({ subtype: 'square', box: box(20)} )), EngineErrorCode.Forbidden, ); expectRefused( await refusal(doc.forms.updateWidget(WIDGET, { interiorColor: '#ffd500'} )), EngineErrorCode.Forbidden, ); expectRefused( await refusal(doc.forms.create({ kind: 'text', name: 'extra'} )), EngineErrorCode.Forbidden, ); } ); await as('comment', async (doc) =>{ await doc.page(PAGE).annotations.create({ subtype: 'square', box: box(20)} ); expectRefused( await refusal(doc.forms.setValue(NAME, { value: 'Bea'} )), EngineErrorCode.Forbidden, ); expectRefused( await refusal(doc.forms.updateWidget(WIDGET, { interiorColor: '#ffd500'} )), EngineErrorCode.Forbidden, ); } ); for (const token of ['everything', 'comment', 'fill'] as const){ await as(token, async (doc) =>{ const page = doc.page(PAGE); expectRefused( await refusal( page.annotations.update(WIDGET, { subtype: 'widget', interiorColor: '#fff'} ), ), EngineErrorCode.InvalidArg, ); expectRefused(await refusal(page.annotations.delete(WIDGET)), EngineErrorCode.InvalidArg); expectRefused( await refusal(page.annotations.reorder([WIDGET], 'start')), EngineErrorCode.InvalidArg, ); } ); } } ); if (options.openSameDocument){ const openSameDocument = options.openSameDocument; test("events: a token hears its own family of another session's writes, never the other", async () =>{ const writer = await options.open(engine, PERMISSION_TOKENS.everything); const filler = await openSameDocument(engine, writer, PERMISSION_TOKENS.fill); const commenter = await openSameDocument(engine, writer, PERMISSION_TOKENS.comment); try{ const heardByFiller: DocumentEvent[] = []; const heardByCommenter: DocumentEvent[] = []; filler.events.subscribe((event) => heardByFiller.push(event)); commenter.events.subscribe((event) => heardByCommenter.push(event)); await new Promise((resolve) => setTimeout(resolve, 300)); await writer.page(PAGE).annotations.create({ subtype: 'square', box: box(80)} ); await writer.forms.setValue(NAME, { value: 'Bea'} ); const deadline = Date.now() + 10_000; const heard = (events: DocumentEvent[], type: DocumentEvent['type']) => events.some((event) => event.type === type); while ( !( heard(heardByFiller, 'forms.valueSet') && heard(heardByCommenter, 'annotations.created') ) ){ if (Date.now() > deadline) throw new Error('timed out waiting for the remote events'); await new Promise((resolve) => setTimeout(resolve, 25)); } await new Promise((resolve) => setTimeout(resolve, 300)); const types = (events: DocumentEvent[]) => events.map((event) => event.type); expect(types(heardByFiller).some((type) => type.startsWith('annotations.'))).toBe(false); expect(types(heardByCommenter).some((type) => type.startsWith('forms.'))).toBe(false); } finally{ await commenter.close(); await filler.close(); await writer.close(); } } ); } } ); } runPieceInfoConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPieceInfoConformance.ts): export function runPieceInfoConformance( runner: ConformanceTestRunner, options: PieceInfoConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`pieceInfo conformance: ${ options.label} `, () =>{ let engine: LocalEngine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('doc-level: the full value vocabulary round-trips with tags intact', async () =>{ const doc = await openFixture(engine, options); try{ await doc.pieceInfo.update(APP, { name: 'Standard Stamps', schema: 1, shared: true, kind:{ name: 'StampLibrary'} , tags: ['legal', 'finance'], } ); const snap = await doc.pieceInfo.get(APP); expect(snap).toBeTruthy(); expect(snap!.entries).toEqual({ name:{ type: 'string', value: 'Standard Stamps'} , schema:{ type: 'number', value: 1} , shared:{ type: 'boolean', value: true} , kind:{ type: 'name', value: 'StampLibrary'} , tags:{ type: 'string-array', value: ['legal', 'finance']} , } ); expect(typeof snap!.modifiedAt).toBe('string'); } finally{ await doc.close(); } } ); test('page-level: the stamp schema round-trips on a page', async () =>{ const doc = await openFixture(engine, options); try{ const list = await doc.pages.list(); const page = doc.page(list.pages[0].ref); await page.pieceInfo.update(APP, { name: 'Witness', subject: 'Getuige'} ); const snap = await page.pieceInfo.get(APP); expect(snap!.entries).toEqual({ name:{ type: 'string', value: 'Witness'} , subject:{ type: 'string', value: 'Getuige'} , } ); expect(await doc.pieceInfo.get(APP)).toBe(null); } finally{ await doc.close(); } } ); test('writes persist through save → re-open', async () =>{ const doc = await openFixture(engine, options); let reopened: LocalDocumentHandle | null = null; try{ const list = await doc.pages.list(); const pageObjectNumber = list.pages[0].ref.objectNumber; await doc.pieceInfo.update(APP, { name: 'Standard Stamps'} ); await doc .page(toPageRef(pageObjectNumber)) .pieceInfo.update(APP, { name: 'Witness', subject: 'Getuige'} ); const bytes = await doc.download(); reopened = await engine.open({ kind: 'bytes', id: `${ options.fixture.id} -pi-reopen`, bytes} , EVERY_PERMISSION, ); const relist = await reopened.pages.list(); const docSnap = await reopened.pieceInfo.get(APP); expect(docSnap!.entries.name).toEqual({ type: 'string', value: 'Standard Stamps'} ); const pageSnap = await reopened.page(relist.pages[0].ref).pieceInfo.get(APP); expect(pageSnap!.entries.subject).toEqual({ type: 'string', value: 'Getuige'} ); } finally{ if (reopened) await reopened.close(); await doc.close(); } } ); test('null deletes a key; clear removes an entry; siblings survive', async () =>{ const doc = await openFixture(engine, options); try{ await doc.pieceInfo.update(APP, { name: 'A', keep: 'B'} ); await doc.pieceInfo.update(SIBLING_APP, { other: 'C'} ); await doc.pieceInfo.update(APP, { name: null} ); const afterDelete = await doc.pieceInfo.get(APP); expect(Object.keys(afterDelete!.entries)).toEqual(['keep']); const apps = await doc.pieceInfo.list(); expect(apps.includes(APP)).toBe(true); expect(apps.includes(SIBLING_APP)).toBe(true); await doc.pieceInfo.delete(APP); expect(await doc.pieceInfo.get(APP)).toBe(null); const sibling = await doc.pieceInfo.get(SIBLING_APP); expect(sibling!.entries.other).toEqual({ type: 'string', value: 'C'} ); } finally{ await doc.close(); } } ); test('an application that was never written reads as null', async () =>{ const doc = await openFixture(engine, options); try{ expect(await doc.pieceInfo.get('EMBD_NeverWritten')).toBe(null); const list = await doc.pages.list(); expect(await doc.page(list.pages[0].ref).pieceInfo.get('EMBD_NeverWritten')).toBe(null); } finally{ await doc.close(); } } ); } ); } runPrintCopyConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPrintRenderConformance.ts): export function runPrintCopyConformance( runner: ConformanceTestRunner, options: PrintCopyConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`print copy conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; let small: PageLayout; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine, PRINT_SCOPES.everything); small = (await doc.pages.list()).pages[0]!; } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); const as = async ( scope: readonly string[], body: (doc: DocumentHandle) => Promise, ): Promise =>{ const restricted = await options.open(engine, scope); try{ await body(restricted); } finally{ await restricted.close(); } } ; const copySpots = async ( source: DocumentHandle, extractOptions: PageExtractOptions, picture: PageImageOptions, ): Promise<{ dark: Record; annotations: number} > =>{ const bytes = await source.pages.extract([small.ref], extractOptions); const copy = await options.openCopy(engine, bytes); try{ const{ pages} = await copy.pages.list(); expect(pages).toHaveLength(1); const page = pages[0]!; const{ annotations} = await copy.page(page.ref).annotations.list(); return{ dark: await darkSpotsOf(copy, page.ref, picture), annotations: annotations.length, } ; } finally{ await copy.close(); } } ; test('a print copy, printed, shows what a print picture shows, with nothing interactive left', async () =>{ const before = (await doc.page(small.ref).annotations.list()).annotations.length; const all = [...ANNOTATION_SPOTS, ...FIELD_SPOTS]; const printed = await copySpots(doc, { flatten:{ usage: 'print'} } , print(150)); expect(printed.dark).toEqual(shown('print', all)); expect(printed.annotations).toBe(0); expect((await doc.page(small.ref).annotations.list()).annotations.length).toBe(before); } ); test('a display copy shows what a screen picture shows', async () =>{ const all = [...ANNOTATION_SPOTS, ...FIELD_SPOTS]; const shownCopy = await copySpots(doc, { flatten:{ } } , { } ); expect(shownCopy.dark).toEqual(shown('display', all)); expect(shownCopy.annotations).toBe(0); } ); test('includeAnnotations and includeFormFields choose what a copy paints', async () =>{ const cases: Array<{ options: PageExtractOptions; spots: readonly Spot[]} > = [{ options:{ includeAnnotations: false, includeFormFields: false} , spots: []} , { options:{ includeAnnotations: true, includeFormFields: false} , spots: ANNOTATION_SPOTS, } , { options:{ includeAnnotations: false, includeFormFields: true} , spots: FIELD_SPOTS} , ]; for (const{ options, spots} of cases){ const{ dark} = await copySpots( doc, { ...options, flatten:{ usage: 'print'} } , print(150), ); expect(dark).toEqual(shown('print', spots)); } } ); test('the include options take flatten', async () =>{ for (const options of [{ includeAnnotations: false} , { includeFormFields: true} ]){ await expect(doc.pages.extract([small.ref], options)).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } } ); test('a flattened copy needs doc.download or doc.download.flattened, and paints what the caller may read', async () =>{ const reads = ['doc.open', 'doc.render', 'doc.annotate.read', 'doc.forms.read']; await as([...reads, 'doc.download.flattened'], async (flattenedOnly) =>{ await expect(flattenedOnly.pages.extract([small.ref])).rejects.toMatchObject({ code: EngineErrorCode.Forbidden, } ); const bytes = await flattenedOnly.pages.extract([small.ref], { flatten:{ usage: 'print'} , } ); expect(Array.from(bytes.slice(0, 4))).toEqual([0x25, 0x50, 0x44, 0x46]); } ); await as(reads, async (noDownload) =>{ await expect( noDownload.pages.extract([small.ref], { flatten:{ usage: 'print'} } ), ).rejects.toMatchObject({ code: EngineErrorCode.Forbidden} ); } ); await as( ['doc.open', 'doc.render', 'doc.forms.read', 'doc.download'], async (noAnnotations) =>{ await expect( noAnnotations.pages.extract([small.ref], { flatten:{ usage: 'print'} , includeAnnotations: true, } ), ).rejects.toMatchObject({ code: EngineErrorCode.Forbidden} ); const{ dark} = await copySpots( noAnnotations, { flatten:{ usage: 'print'} } , print(150), ); expect(dark).toEqual(shown('print', FIELD_SPOTS)); } , ); } ); } ); } runPrintRenderConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runPrintRenderConformance.ts): export function runPrintRenderConformance( runner: ConformanceTestRunner, options: PrintRenderConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`print render conformance: ${ options.label} `, () =>{ let engine: Engine; let doc: DocumentHandle; let small: PageLayout; let large: PageLayout; beforeAll(async () =>{ engine = await options.makeEngine(); doc = await options.open(engine, PRINT_SCOPES.everything); const{ pages} = await doc.pages.list(); small = pages[0]!; large = pages[1]!; } ); afterAll(async () =>{ if (doc) await doc.close(); if (engine) await engine.destroy(); } ); const as = async ( scope: readonly string[], body: (doc: DocumentHandle) => Promise, ): Promise =>{ const restricted = await options.open(engine, scope); try{ await body(restricted); } finally{ await restricted.close(); } } ; const darkSpots = (options: PageImageOptions) => darkSpotsOf(doc, small.ref, options); test('a print picture is the whole page at its DPI, with pageTransform as its transform', async () =>{ for (const dpi of [150, 300] as const){ const options: PageImageOptions = print(dpi); const image = await doc.page(small.ref).render.image({ format: 'png', ...options} ); const size = Math.round((200 * dpi) / 72); expect([image.width, image.height]).toEqual([size, size]); const raster = await decode(image); expect([raster.width, raster.height]).toEqual([size, size]); const expected = pageTransform(small, options); expect([expected.width, expected.height]).toEqual([size, size]); expect( image.transform.matrix.every((n, i) => Math.abs(n - expected.matrix[i]!) < 1e-9), ).toBe(true); } } ); test('a page bigger than the paper is printed at the size it has fitted to A4 or Letter', async () =>{ const options: PageImageOptions ={ ...print(150), includeAnnotations: false, includeFormFields: false, } ; const image = await doc.page(large.ref).render.image({ format: 'png', ...options} ); expect([image.width, image.height]).toEqual([1241, 1754]); const expected = pageTransform(large, options); expect([expected.width, expected.height]).toEqual([1241, 1754]); } ); test('a screen picture follows the screen rules, a print picture the print rules', async () =>{ const layers ={ includeAnnotations: true, includeFormFields: true} ; const all = [...ANNOTATION_SPOTS, ...FIELD_SPOTS]; expect(await darkSpots(layers)).toEqual(shown('display', all)); expect(await darkSpots({ ...layers, ...print(150)} )).toEqual(shown('print', all)); } ); test('each print picture draws what its family draws', async () =>{ const cases: Array<{ layers: PageImageOptions; spots: readonly Spot[]} > = [{ layers:{ includeAnnotations: false, includeFormFields: false} , spots: []} , { layers:{ includeAnnotations: true, includeFormFields: false} , spots: ANNOTATION_SPOTS} , { layers:{ includeAnnotations: false, includeFormFields: true} , spots: FIELD_SPOTS} , ]; for (const{ layers, spots} of cases){ expect(await darkSpots({ ...layers, ...print(300)} )).toEqual(shown('print', spots)); } } ); test('options that do not fit a print picture are refused', async () =>{ const page = doc.page(small.ref); const refused: PageImageOptions[] = [{ usage: 'print'} , { usage: 'print', viewport:{ kind: 'scale', scale: 2} } , { usage: 'print', viewport:{ kind: 'width', width: 400} } , { usage: 'print', viewport:{ kind: 'dpi', dpi: 200 as 150} } , { viewport:{ kind: 'dpi', dpi: 150} } , { usage: 'display', viewport:{ kind: 'dpi', dpi: 300} } , { ...print(150), target:{ kind: 'rect', rect:{ x: 0, y: 0, width: 50, height: 50} } } , { ...print(150), rotation: 90} , { ...print(150), background: 'transparent'} , ]; for (const options of refused){ await expect(page.render.image({ format: 'png', ...options} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } } ); test('printing needs doc.print, and 300 DPI doc.print.high', async () =>{ await as(PRINT_SCOPES.screen, async (screenOnly) =>{ const page = screenOnly.page(small.ref); const image = await page.render.image({ format: 'png'} ); expect([image.width, image.height]).toEqual([200, 200]); await expect(page.render.image({ format: 'png', ...print(150)} )).rejects.toMatchObject({ code: EngineErrorCode.Forbidden, } ); } ); await as(PRINT_SCOPES.print, async (printOnly) =>{ const page = printOnly.page(small.ref); const image = await page.render.image({ format: 'png', ...print(150)} ); expect((await decode(image)).width).toBe(417); await expect(page.render.image({ format: 'png', ...print(300)} )).rejects.toMatchObject({ code: EngineErrorCode.Forbidden, } ); } ); } ); test('printing needs no doc.render, and doc.print gives no screen picture', async () =>{ await as(PRINT_SCOPES.printOnly, async (printOnly) =>{ const page = printOnly.page(small.ref); const image = await page.render.image({ format: 'png', ...print(150)} ); expect((await decode(image)).width).toBe(417); for (const options of [{ } , { viewport:{ kind: 'thumbnail'} } ] as PageImageOptions[]){ await expect(page.render.image({ format: 'png', ...options} )).rejects.toMatchObject({ code: EngineErrorCode.Forbidden, } ); } } ); } ); test('a thumbnail is the whole page, PAGE_THUMBNAIL_SIZE on its long side', async () =>{ const page = doc.page(small.ref); const image = await page.render.image({ format: 'png', viewport:{ kind: 'thumbnail'} } ); expect([image.width, image.height]).toEqual([PAGE_THUMBNAIL_SIZE, PAGE_THUMBNAIL_SIZE]); const pixels = await decode(image); expect([pixels.width, pixels.height]).toEqual([PAGE_THUMBNAIL_SIZE, PAGE_THUMBNAIL_SIZE]); const tall = await doc .page(large.ref) .render.image({ format: 'png', viewport:{ kind: 'thumbnail'} } ); expect(Math.max(tall.width, tall.height)).toBe(PAGE_THUMBNAIL_SIZE); const rect ={ kind: 'rect', rect:{ x: 0, y: 0, width: 50, height: 50} } as const; for (const options of [{ viewport:{ kind: 'thumbnail'} , target: rect} , { usage: 'print', viewport:{ kind: 'thumbnail'} } , ] as PageImageOptions[]){ await expect(page.render.image({ format: 'png', ...options} )).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg, } ); } } ); test('a thumbnail needs doc.render.thumbnail, which doc.render includes', async () =>{ await as(PRINT_SCOPES.thumbnails, async (thumbnailsOnly) =>{ const page = thumbnailsOnly.page(small.ref); const image = await page.render.image({ format: 'png', viewport:{ kind: 'thumbnail'} } ); expect(image.width).toBe(PAGE_THUMBNAIL_SIZE); for (const options of [{ } , print(150)] as PageImageOptions[]){ await expect(page.render.image({ format: 'png', ...options} )).rejects.toMatchObject({ code: EngineErrorCode.Forbidden, } ); } } ); await as(PRINT_SCOPES.screen, async (screenOnly) =>{ const image = await screenOnly .page(small.ref) .render.image({ format: 'png', viewport:{ kind: 'thumbnail'} } ); expect(image.width).toBe(PAGE_THUMBNAIL_SIZE); } ); } ); } ); } runRedactionApplyConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runRedactionApplyConformance.ts): export function runRedactionApplyConformance( runner: ConformanceTestRunner, options: RedactionApplyConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const REDACT_RECT ={ x: 50, y: 50, width: 120, height: 100} ; const COLLATERAL_QUAD: HighlightDraft['quadPoints'] = [{ upperLeft:{ x: 70, y: 80} , upperRight:{ x: 150, y: 80} , lowerLeft:{ x: 70, y: 120} , lowerRight:{ x: 150, y: 120} , } , ]; describe(`redaction apply conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('annotations scope applies the marked redaction and counts collateral', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.redaction) return; const layoutBefore = await doc.pages.list(); const pageObjectNumber = layoutBefore.pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); const collateral = await page.annotations.create({ subtype: 'highlight', quadPoints: COLLATERAL_QUAD, } satisfies HighlightDraft); expect(collateral.annotation.subtype).toBe('highlight'); const marked = await page.annotations.create({ subtype: 'redact', rect: REDACT_RECT, interiorColor: '#000000', overlayText: 'REDACTED', fontColor: '#ffffff', } satisfies RedactDraft); expect(marked.annotation.subtype).toBe('redact'); await page.annotations.create({ subtype: 'popup', rect:{ x: 300, y: 300, width: 100, height: 60} , parent: marked.annotation.ref, } ); const before = await page.annotations.list(); const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type === 'redaction.applied') events.push(event); } ); const result = await doc.redaction.apply({ annotations: [marked.annotation.ref]} ); expect(RedactionApplyResultSchema.safeParse(result).success).toBe(true); expect(result.results).toHaveLength(1); expect(result.results[0].page.objectNumber).toBe(pageObjectNumber); expect(result.results[0].status).toBe('applied'); expect(result.results[0].removedAnnotationCount).toBe(2); expect(result.removedAnnotationCount).toBe(2); expect(result.meta.affectedPages).toEqual([page.ref]); expect(events).toHaveLength(1); unsubscribe(); const after = await page.annotations.list(); expect(after.annotations.length).toBe(before.annotations.length - 3); expect(await doc.pages.list()).toEqual(layoutBefore); expect((await page.text.get()).text).toContain('REDACTED'); } finally{ await doc.close(); } } ); test('annotations scope applies several marks of a page together and leaves its others', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.redaction) return; const pageObjectNumber = (await doc.pages.list()).pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); const mark = (x: number) => page.annotations.create({ subtype: 'redact', rect:{ x, y: 20, width: 40, height: 30} , interiorColor: '#000000', } satisfies RedactDraft); const first = await mark(10); const kept = await mark(70); const last = await mark(130); await page.annotations.create({ subtype: 'highlight', quadPoints: [{ upperLeft:{ x: 15, y: 25} , upperRight:{ x: 45, y: 25} , lowerLeft:{ x: 15, y: 45} , lowerRight:{ x: 45, y: 45} , } , ], } satisfies HighlightDraft); const result = await doc.redaction.apply({ annotations: [last.annotation.ref, first.annotation.ref], } ); expect(result.results).toHaveLength(1); expect(result.results[0].status).toBe('applied'); expect(result.results[0].removedAnnotationCount).toBe(1); const left = (await page.annotations.list()).annotations; expect(left.map((annotation) => annotation.subtype)).toEqual(['redact']); expect(left[0].ref).toEqual(kept.annotation.ref); } finally{ await doc.close(); } } ); test('a label fitted to its region (fontSize 0) is burned in', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.redaction) return; const layout = await doc.pages.list(); const page = doc.page(toPageRef(layout.pages[0].ref.objectNumber)); const marked = await page.annotations.create({ subtype: 'redact', rect: REDACT_RECT, interiorColor: '#000000', } satisfies RedactDraft); await page.annotations.update(marked.annotation.ref, { subtype: 'redact', overlayText: 'CLASSIFIED', fontSize: 0, fontColor: '#ffffff', } ); await doc.redaction.apply({ annotations: [marked.annotation.ref]} ); expect((await page.text.get()).text).toContain('CLASSIFIED'); } finally{ await doc.close(); } } ); test('pages scope applies everything once and validates its input', async () =>{ const doc = await openFixture(engine, options); try{ if (!doc.redaction) return; const layout = await doc.pages.list(); const pageObjectNumber = layout.pages[0].ref.objectNumber; const page = doc.page(toPageRef(pageObjectNumber)); await page.annotations.create({ subtype: 'redact', rect: REDACT_RECT, interiorColor: '#000000', } satisfies RedactDraft); const events: DocumentEvent[] = []; const unsubscribe = doc.events.subscribe((event) =>{ if (event.type === 'redaction.applied') events.push(event); } ); const applied = await doc.redaction.apply({ pages: [toPageRef(pageObjectNumber)]} ); expect(applied.results.map((item) => item.status)).toEqual(['applied']); expect(applied.removedAnnotationCount).toBe(0); expect(events).toHaveLength(1); const noOp = await doc.redaction.apply({ pages: [toPageRef(pageObjectNumber)]} ); expect(noOp.results.map((item) => item.status)).toEqual(['unchanged']); expect(noOp.meta).toMatchObject({ affectedPages: [], cacheDelta: null, undoable: false} ); expect(events).toHaveLength(1); unsubscribe(); await expect( doc.redaction.apply({ pages: [toPageRef(pageObjectNumber), toPageRef(pageObjectNumber)], } ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); const notRedact = await page.annotations.create({ subtype: 'highlight', quadPoints: COLLATERAL_QUAD, } satisfies HighlightDraft); await expect( doc.redaction.apply({ annotations: [notRedact.annotation.ref]} ), ).rejects.toMatchObject({ code: EngineErrorCode.InvalidArg} ); } finally{ await doc.close(); } } ); test('applies on a page without /Contents or /Resources', async () =>{ const doc = await options.openBarePage(engine); try{ if (!doc.redaction) return; const layout = await doc.pages.list(); const page = doc.page(toPageRef(layout.pages[0].ref.objectNumber)); await page.annotations.create({ subtype: 'redact', rect: REDACT_RECT, interiorColor: '#000000', overlayText: 'REDACTED', fontColor: '#ffffff', } satisfies RedactDraft); const applied = await doc.redaction.apply({ pages: [page.ref]} ); expect(applied.results.map((item) => item.status)).toEqual(['applied']); expect(applied.meta.affectedPages).toEqual([page.ref]); expect((await page.annotations.list()).annotations).toHaveLength(0); expect((await page.text.get()).text).toContain('REDACTED'); } finally{ await doc.close(); } } ); } ); } runSearchConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runSearchConformance.ts): export function runSearchConformance( runner: ConformanceTestRunner, options: SearchConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const fixture = options.fixture; async function collectAll( doc: Awaited>, request: Parameters[0], ): Promise<{ matches: SearchMatch[]; slices: SearchSlice[]} >{ const matches: SearchMatch[] = []; const slices: SearchSlice[] = []; let cursor: string | undefined; for (; ; ){ const slice = await doc.search.query({ ...request, cursor} ); expect(SearchSliceSchema.safeParse(slice).success).toBe(true); matches.push(...slice.matches); slices.push(slice); if (slice.nextCursor === null) return{ matches, slices} ; cursor = slice.nextCursor; } } describe(`search conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('finds the present literal with sane matches', async () =>{ const doc = await openFixture(engine, options); try{ const{ matches} = await collectAll(doc, { text: fixture.presentLiteral, } ); expect(matches.length > 0).toBe(true); expect(matches.some((m) => m.page.objectNumber === fixture.presentPageObjectNumber)).toBe( true, ); for (const m of matches){ expect(m.count > 0).toBe(true); expect(m.segments.length > 0).toBe(true); for (const s of m.segments){ expect(s.rect.width > 0).toBe(true); expect(s.rect.height > 0).toBe(true); const xs = [ s.quad.upperLeft.x, s.quad.upperRight.x, s.quad.lowerLeft.x, s.quad.lowerRight.x, ]; const ys = [ s.quad.upperLeft.y, s.quad.upperRight.y, s.quad.lowerLeft.y, s.quad.lowerRight.y, ]; expect(Math.abs(s.rect.x - Math.min(...xs)) < 1e-3).toBe(true); expect(Math.abs(s.rect.x + s.rect.width - Math.max(...xs)) < 1e-3).toBe(true); expect(Math.abs(s.rect.y - Math.min(...ys)) < 1e-3).toBe(true); expect(Math.abs(s.rect.y + s.rect.height - Math.max(...ys)) < 1e-3).toBe(true); expect(s.advance === 1 || s.advance === -1).toBe(true); } } } finally{ await doc.close(); } } ); test('matching is case-insensitive by default', async () =>{ const doc = await openFixture(engine, options); try{ const lower = await collectAll(doc, { text: fixture.presentLiteral.toLowerCase(), } ); const upper = await collectAll(doc, { text: fixture.presentLiteral.toUpperCase(), } ); expect(lower.matches.length).toBe(upper.matches.length); expect(lower.matches.length > 0).toBe(true); } finally{ await doc.close(); } } ); test('snippets carry the matched text; without them a match has none', async () =>{ const doc = await openFixture(engine, options); try{ const withSnippets = await collectAll(doc, { text: fixture.presentLiteral, snippets: true, } ); for (const m of withSnippets.matches){ expect(!!m.snippet).toBe(true); const s = m.snippet!; const hit = s.match; expect(foldText(hit).folded).toBe(foldText(fixture.presentLiteral).folded); } const plain = await collectAll(doc, { text: fixture.presentLiteral, } ); expect(plain.matches.length).toBe(withSnippets.matches.length); for (const m of plain.matches) expect(m.snippet === undefined).toBe(true); } finally{ await doc.close(); } } ); test('the absent literal exhausts with zero matches', async () =>{ const doc = await openFixture(engine, options); try{ const{ matches, slices} = await collectAll(doc, { text: fixture.absentLiteral, } ); expect(matches.length).toBe(0); const last = slices[slices.length - 1]; expect(last.nextCursor).toBe(null); expect(last.pageCount > 0).toBe(true); } finally{ await doc.close(); } } ); test('a one-page limit walks the whole document via the cursor', async () =>{ const doc = await openFixture(engine, options); try{ const whole = await collectAll(doc, { text: fixture.presentLiteral, } ); const sliced = await collectAll(doc, { text: fixture.presentLiteral, limit:{ pages: 1} , } ); expect(sliced.matches.length).toBe(whole.matches.length); const last = sliced.slices[sliced.slices.length - 1]; expect(last.pagesSearched).toBe(last.pageCount); expect(sliced.slices.length).toBe(last.pageCount); } finally{ await doc.close(); } } ); test('from rotates the scan order (viewport-first)', async () =>{ const doc = await openFixture(engine, options); try{ const slice = await doc.search.query({ text: fixture.presentLiteral, from: toPageRef(fixture.presentPageObjectNumber), limit:{ pages: 1} , } ); expect(slice.matches.length > 0).toBe(true); expect(slice.matches[0].page.objectNumber).toBe(fixture.presentPageObjectNumber); } finally{ await doc.close(); } } ); test('a cursor replayed against a different query is rejected', async () =>{ const doc = await openFixture(engine, options); try{ const first = await doc.search.query({ text: fixture.presentLiteral, limit:{ pages: 1} , } ); expect(first.nextCursor !== null).toBe(true); let caught: unknown; try{ await doc.search.query({ text: fixture.absentLiteral, cursor: first.nextCursor!, } ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('a malformed cursor is rejected', async () =>{ const doc = await openFixture(engine, options); try{ let caught: unknown; try{ await doc.search.query({ text: fixture.presentLiteral, cursor: 'not a cursor', } ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally{ await doc.close(); } } ); test('regex queries match with offsets and rects', async () =>{ const doc = await openFixture(engine, options); try{ const{ matches} = await collectAll(doc, { text: fixture.presentRegex, regex: true, } ); expect(matches.length > 0).toBe(true); for (const m of matches){ expect(m.count > 0).toBe(true); expect(m.segments.length > 0).toBe(true); } } finally{ await doc.close(); } } ); test('regex flags are restrictions: matchCase and wholeWord return subsets', async () =>{ const doc = await openFixture(engine, options); try{ const all = await collectAll(doc, { text: fixture.presentRegex, regex: true, } ); const key = (m: SearchMatch) => `${ m.page.objectNumber} :${ m.start} :${ m.count} `; const allKeys = new Set(all.matches.map(key)); for (const flags of [{ matchCase: true} , { wholeWord: true} ]){ const restricted = await collectAll(doc, { text: fixture.presentRegex, regex: true, ...flags, } ); expect(restricted.matches.length <= all.matches.length).toBe(true); for (const m of restricted.matches) expect(allKeys.has(key(m))).toBe(true); } } finally{ await doc.close(); } } ); test('ignoreWhitespace keeps every default hit and finds the space-free needle', async () =>{ const doc = await openFixture(engine, options); try{ const key = (m: SearchMatch) => `${ m.page.objectNumber} :${ m.start} :${ m.count} `; const plain = await collectAll(doc, { text: fixture.presentLiteral} ); const relaxed = await collectAll(doc, { text: fixture.presentLiteral, ignoreWhitespace: true, } ); const relaxedKeys = new Set(relaxed.matches.map(key)); for (const m of plain.matches) expect(relaxedKeys.has(key(m))).toBe(true); const squashed = await collectAll(doc, { text: fixture.presentLiteral.replace(/\s+/g, ''), ignoreWhitespace: true, } ); expect(squashed.matches.map(key)).toEqual(relaxed.matches.map(key)); } finally{ await doc.close(); } } ); test('regex + matchDiacritics / ignoreWhitespace are rejected with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ for (const flags of [{ matchDiacritics: true} , { ignoreWhitespace: true} ]){ let caught: unknown; try{ await doc.search.query({ text: fixture.presentRegex, regex: true, ...flags, } ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } } finally{ await doc.close(); } } ); test('dialect violations are rejected with InvalidArg', async () =>{ const doc = await openFixture(engine, options); try{ for (const pattern of ['(a)\\1', '(?=x)y', '(']){ let caught: unknown; try{ await doc.search.query({ text: pattern, regex: true} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } } finally{ await doc.close(); } } ); test('an empty needle returns an exhausted, empty slice', async () =>{ const doc = await openFixture(engine, options); try{ const slice = await doc.search.query({ text: ' '} ); expect(slice.matches.length).toBe(0); expect(slice.nextCursor).toBe(null); } finally{ await doc.close(); } } ); test('abort() on query rejects with AbortError', async () =>{ const doc = await openFixture(engine, options); try{ const p = doc.search.query({ text: fixture.presentLiteral} ); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally{ await doc.close(); } } ); test('query after close throws DocNotOpen', async () =>{ const doc = await openFixture(engine, options); await doc.close(); let caught: unknown; try{ await doc.search.query({ text: fixture.presentLiteral} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.DocNotOpen)).toBe(true); } ); } ); } runSignatureConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runSignatureConformance.ts): export function runSignatureConformance( runner: ConformanceTestRunner, options: SignatureConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`signatures conformance: ${ options.label} `, () =>{ let engine: Engine; let permitEngine: Engine | null = null; let supported = false; beforeAll(async () =>{ engine = await options.makeEngine(); const probe = await open(engine, options, options.fixtures.unsignedForm); supported = probe.signatures !== undefined; await probe.close(); if (supported && options.makePermitEngine) permitEngine = await options.makePermitEngine(); } ); afterAll(async () =>{ if (permitEngine) await permitEngine.destroy(); if (engine) await engine.destroy(); } ); test('an unsigned form has no signatures and no protection; version() hashes the loaded bytes', async () =>{ if (!supported) return; const bytes = await options.fixtures.unsignedForm.bytes(); const doc = await open(engine, options, options.fixtures.unsignedForm); try{ const snapshot = await doc.signatures.list(); expect(snapshot.chainValid).toBe(true); expect(snapshot.signatures).toEqual([]); expect(snapshot.revisions.length >= 1).toBe(true); expect(snapshot.protection.judged).toBeNull(); expect(snapshot.protection.enforced).toBeNull(); expect(snapshot.protection.certification).toBeNull(); expect(snapshot.protection.fieldLocks).toEqual([]); expect(doc.security.allows('doc.pages.assemble')).toBe(true); if (isLocalDocument(doc)){ const version = await doc.version(); expect(version.sizeBytes).toBe(bytes.byteLength); expect(version.sha256).toBe(await sha256Hex(bytes)); } let caught: unknown; try{ await doc.signatures.getContents({ kind: 'fqn', name: 'no-such-field'} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); test('two approval signatures: revisions, coverage, digests, contents, revision bytes', async () =>{ if (!supported) return; const fixture = options.fixtures.twoApprovals; const bytes = await fixture.bytes(); const doc = await open(engine, options, fixture); try{ const snapshot = await doc.signatures.list(); expect(snapshot.chainValid).toBe(true); expect(snapshot.revisions).toHaveLength(3); expect(snapshot.signatures).toHaveLength(2); expect(snapshot.revisions[2].end).toBe(bytes.byteLength); for (const [i, sig] of snapshot.signatures.entries()){ expect(sig.index).toBe(i); expect(sig.signed).toBe(true); expect(sig.kind).toBe('signature'); expect(sig.field.kind).toBe('objectNumber'); expect(sig.fieldName).toBe(fixture.fieldNames[i]); expect(sig.coverage).toBe('whole-revision'); expect(sig.revisionIndex).toBe(i + 1); expect(snapshot.revisions[i + 1].signatureIndex).toBe(i); expect(sig.subFilter).toBe('ETSI.CAdES.detached'); expect(typeof sig.signer.signedAt).toBe('string'); expect(sig.docMdp).toBeNull(); expect(sig.catalogCertification).toBe(false); expect(sig.contentsSizeBytes > 0).toBe(true); expect(sig.byteRange![0]).toBe(0); expect(sig.byteRange![2] + sig.byteRange![3]).toBe(snapshot.revisions[i + 1].end); } expect(snapshot.protection.judged).toBe('annotate'); expect(snapshot.protection.enforced).toBeNull(); expect(snapshot.protection.certification).toBeNull(); expect(snapshot.protection.fieldLocks).toEqual([]); const first = snapshot.signatures[0]; const contents = await doc.signatures.getContents(first.field); expect(contents.byteLength).toBe(first.contentsSizeBytes); expect(contents[0]).toBe(0x30); const [a, b, c, d] = first.byteRange!; const sealed = await doc.signatures.downloadRevision(1); expect(sealed.byteLength).toBe(snapshot.revisions[1].end); expect(bytesEqual(sealed, bytes.subarray(0, sealed.byteLength))).toBe(true); const signedBytes = concat(sealed.subarray(a, a + b), sealed.subarray(c, c + d)); const digest = await doc.signatures.getDigest(first.field, 'sha256'); expect(digest.byteLength).toBe(32); expect(toHex(digest)).toBe(await sha256Hex(signedBytes)); expect((await doc.signatures.getDigest(first.field, 'sha512')).byteLength).toBe(64); const byName = await doc.signatures.getDigest({ kind: 'fqn', name: first.fieldName} , 'sha256', ); expect(toHex(byName)).toBe(toHex(digest)); const fields = await doc.forms.list(); const text = fields.fields.find((f) => f.name === fixture.textField)!; expect(text).toBeTruthy(); await doc.forms.setValue(text.ref, { value: 'unsaved', } ); const again = await doc.signatures.list(); expect(again.revisions).toEqual(snapshot.revisions); expect(again.signatures.map((s) => [s.coverage, s.revisionIndex, s.byteRange])).toEqual( snapshot.signatures.map((s) => [s.coverage, s.revisionIndex, s.byteRange]), ); expect(toHex(await doc.signatures.getDigest(first.field, 'sha256'))).toBe(toHex(digest)); if (isLocalDocument(doc)){ expect((await doc.version()).sha256).toBe(await sha256Hex(bytes)); } } finally{ await doc.close(); } } ); test('a certification takes structural capabilities away; permit lifts it', async () =>{ if (!supported) return; const fixture = options.fixtures.certified; const doc = await open(engine, options, fixture); try{ const snapshot = await doc.signatures.list(); const signed = snapshot.signatures.filter((s) => s.signed); expect(signed).toHaveLength(1); const sig = signed[0]; expect(sig.fieldName).toBe(fixture.fieldName); expect(sig.coverage).toBe('whole-revision'); expect(sig.docMdp).toBe(2); expect(sig.catalogCertification).toBe(true); expect(snapshot.protection.judged).toBe('fill'); expect(snapshot.protection.enforced).toBe('fill'); expect(snapshot.protection.certification).toEqual({ signatureIndex: sig.index, permission: 2, } ); expect(doc.security.allows('doc.forms.read')).toBe(true); expect(doc.security.allows('doc.forms.fill')).toBe(true); expect(doc.security.allows('doc.annotate.modify')).toBe(false); expect(doc.security.allows('doc.pages.assemble')).toBe(false); expect(doc.security.allows('doc.redact')).toBe(false); const list = await doc.pages.list(); let caught: unknown; try{ await doc.pages.delete([list.pages[0].ref]); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.ProtectedDocument)).toBe(true); caught = undefined; try{ await doc.download({ mode: 'rewrite'} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.ProtectedDocument)).toBe(true); const saved = await doc.download(); expect(saved.byteLength >= snapshot.revisions[1].end).toBe(true); } finally{ await doc.close(); } if (!permitEngine) return; const permitted = await open(permitEngine, options, fixture); try{ const snapshot = await permitted.signatures.list(); expect(snapshot.protection.judged).toBe('fill'); expect(snapshot.protection.enforced).toBe('fill'); expect(permitted.security.allows('doc.pages.assemble')).toBe(true); const rewritten = await permitted.download({ mode: 'rewrite'} ); expect(rewritten.byteLength > 0).toBe(true); } finally{ await permitted.close(); } } ); test('a FieldMDP freezes the fields it names; permit lifts it', async () =>{ if (!supported) return; const fixture = options.fixtures.fieldMdp; const doc = await open(engine, options, fixture); const lockedRef ={ kind: 'fqn', name: fixture.lockedField} as const; try{ const snapshot = await doc.signatures.list(); const sig = snapshot.signatures[0]; expect(sig.fieldName).toBe(fixture.fieldName); expect(sig.fieldMdp).toEqual({ action: 'include', fields: [fixture.lockedField]} ); expect(snapshot.protection.judged).toBe('annotate'); expect(snapshot.protection.enforced).toBeNull(); expect(snapshot.protection.fieldLocks[0]).toEqual({ signatureIndex: 0, source: 'fieldmdp', spec:{ action: 'include', fields: [fixture.lockedField]} , } ); for (const lock of snapshot.protection.fieldLocks){ expect(lock.signatureIndex).toBe(0); expect(lock.spec).toEqual({ action: 'include', fields: [fixture.lockedField]} ); } expect(doc.security.allows('doc.forms.fill')).toBe(true); let caught: unknown; try{ await doc.forms.setValue(lockedRef, { value: 'changed'} ); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.ProtectedDocument)).toBe(true); let scripted: unknown; try{ await doc.apply({ ops: [{ type: 'forms.setValue', field: lockedRef, value:{ value: 'changed'} } ], } ); } catch (err){ scripted = err; } expect(EngineError.is(scripted, EngineErrorCode.ProtectedDocument)).toBe(true); const bundle = await doc.forms.export({ fields: [lockedRef]} ); const [row] = bundle.fields; const changed ={ ...bundle, fields: [{ data:{ ...row!.data, valueEntry:{ kind: 'scalar', value: 'changed'} , value: 'changed', } as FormField, } , ], } ; const imported = await doc.forms.importValues(changed, { attribution: 'stamp'} ); expect(imported.dropped).toEqual([{ ref: row!.data.ref, reason: 'locked'} ]); expect(imported.fields).toEqual([]); const field = await doc.forms.get(lockedRef); expect(field.kind).toBe('text'); expect((field as{ value?: string} ).value === 'changed').toBe(false); } finally{ await doc.close(); } if (!permitEngine) return; const permitted = await open(permitEngine, options, fixture); try{ const result = await permitted.forms.setValue(lockedRef, { value: 'changed', } ); expect(result.field.name).toBe(fixture.lockedField); } finally{ await permitted.close(); } } ); test('well-formed ranges that seal no revision are partial, with no revision index', async () =>{ if (!supported) return; const doc = await open(engine, options, options.fixtures.partialChain); try{ const snapshot = await doc.signatures.list(); expect(snapshot.chainValid).toBe(true); expect(snapshot.revisions).toHaveLength(3); expect(snapshot.signatures).toHaveLength(2); for (const sig of snapshot.signatures){ expect(sig.signed).toBe(true); expect(sig.coverage).toBe('partial'); expect(sig.revisionIndex).toBeNull(); expect(sig.contentsSizeBytes).toBe(13); expect((await doc.signatures.getContents(sig.field)).byteLength).toBe(13); expect((await doc.signatures.getDigest(sig.field, 'sha256')).byteLength).toBe(32); } expect(snapshot.revisions.every((r) => r.signatureIndex === null)).toBe(true); expect(snapshot.protection.judged).toBe('annotate'); expect(snapshot.protection.enforced).toBeNull(); let caught: unknown; try{ await doc.signatures.downloadRevision(3); } catch (err){ caught = err; } expect(EngineError.is(caught, EngineErrorCode.NotFound)).toBe(true); } finally{ await doc.close(); } } ); if (options.openKind !== 'id'){ runSigningTests( runner, options, () => engine, () => supported, ); runAnalysisTests( runner, options, () => engine, () => permitEngine, () => supported, ); runValidationInfoTests( runner, options, () => engine, () => permitEngine, () => supported, ); } } ); } runTextDivergenceConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runTextDivergenceConformance.ts): export function runTextDivergenceConformance( runner: ConformanceTestRunner, options: TextDivergenceConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; const fixture = options.fixture; describe(`text divergence conformance: ${ options.label} [${ fixture.id} ]`, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); test('snapshot is schema-valid with the exact text, charCount, and charMap', async () =>{ const doc = await openFixture(engine, options); try{ const snap = await doc.page(toPageRef(fixture.pageObjectNumber)).text.get(); expect(PageTextSnapshotSchema.safeParse(snap).success).toBe(true); expect(snap.text).toBe(fixture.exactText); expect(snap.charCount).toBe(fixture.expectedCharCount); const anchors = snap.charMap ?? null; if (fixture.expectedCharMap === null){ expect(anchors === null || anchors.length === 0).toBe(true); } else{ expect(anchors === null ? null : anchors.map((a) => [a[0], a[1]])).toEqual( fixture.expectedCharMap.map((a) => [a[0], a[1]]), ); } } finally{ await doc.close(); } } ); test('char-space slicing round-trips through the map', async () =>{ const doc = await openFixture(engine, options); try{ const page = doc.page(toPageRef(fixture.pageObjectNumber)); const snap = await page.text.get(); expect(await page.text.slice({ start: 0, count: snap.charCount} )).toBe(snap.text); for (const s of fixture.slices ?? []){ expect(await page.text.slice(s)).toBe(s.text); } } finally{ await doc.close(); } } ); if (fixture.search){ const probe = fixture.search; test('search hits address character space and join the text by slicing', async () =>{ const doc = await openFixture(engine, options); try{ const slice = await doc.search.query({ text: probe.query} ); const hit = slice.matches.find((m) => m.page.objectNumber === fixture.pageObjectNumber); expect(hit === undefined).toBe(false); expect(hit!.start).toBe(probe.start); expect(hit!.count).toBe(probe.count); expect(hit!.segments.length > 0).toBe(true); expect(await doc.page(hit!.page).text.slice(hit!)).toBe(probe.matchedText); } finally{ await doc.close(); } } ); } } ); } runWidgetFindingConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runWidgetFindingConformance.ts): export function runWidgetFindingConformance( runner: ConformanceTestRunner, options: WidgetFindingConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`widget finding conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); for (const [name, found] of Object.entries(WIDGET_FINDING_CASES) as [ WidgetFindingCaseName, WidgetFindingCase, ][]){ test(`${ name} : ${ found.does} `, async () =>{ const doc = await options.open(engine, found.pdf.slice(), name); try{ const{ pages} = await doc.pages.list(); const form = await doc.forms.list(); const rows = form.widgets; if (found.page === null){ expect(rows).toEqual([]); } else{ expect(rows.map((row) => row.page.objectNumber)).toEqual([found.page]); } const field = found.field === null ? undefined : form.fields.find((f) => f.name === found.field); if (found.field !== null){ expect(field?.name).toBe(found.field); expect(field?.widgets.map((w) => w.page?.objectNumber ?? null)).toEqual([found.page]); } for (const row of rows){ expect(row.field === null).toBe(found.field === null); } for (const{ ref} of pages){ const{ annotations} = await doc.page(ref).annotations.list(); expect(annotations.some((annotation) => annotation.subtype === 'widget')).toBe(false); } const shown = (page: PageRef) => doc.page(page).forms.renderAppearances(); for (const{ ref} of pages){ const forms = (await shown(ref)).appearances.map((a) => annotationKey(a.ref)); const annotations = (await doc.page(ref).annotations.renderAppearances()).appearances; expect(annotations).toEqual([]); const here = ref.objectNumber === found.page; expect(forms).toEqual(here ? rows.map((row) => annotationKey(row.ref)) : []); } if (found.page !== null){ expect(pages.some((page) => page.ref.objectNumber === found.page)).toBe(true); expect(toPageRef(found.page)).toEqual(rows[0]!.page); } } finally{ await doc.close(); } } ); } } ); } runWidgetRotationConformance [FunctionDeclaration] (from packages/engine/core/src/conformance/runWidgetRotationConformance.ts): export function runWidgetRotationConformance( runner: ConformanceTestRunner, options: WidgetRotationConformanceOptions, ): void{ const{ describe, test, beforeAll, afterAll, expect} = runner; describe(`widget rotation conformance: ${ options.label} `, () =>{ let engine: Engine; beforeAll(async () =>{ engine = await options.makeEngine(); } ); afterAll(async () =>{ if (engine) await engine.destroy(); } ); const withDoc = async ( body: (doc: DocumentHandle) => Promise, bytes: Uint8Array = TURNED_FIELDS_PDF, ) =>{ const doc = await options.open(engine, bytes.slice()); try{ await body(doc); } finally{ await doc.close(); } } ; const rowOf = async (doc: DocumentHandle, name: string): Promise =>{ const{ fields, widgets} = await doc.forms.list(); const field = fields.find((f) => f.name === name); const ref = field?.widgets[0]?.ref; const row = ref && widgets.find((w) => annotationKey(w.ref) === annotationKey(ref)); if (!row) throw new Error(`no widget of '${ name} '`); return row; } ; const expectBox = (actual: PageBox, expected: PageBox) =>{ for (const edge of ['x', 'y', 'width', 'height'] as const){ expect(Math.abs(actual[edge] - expected[edge]) < 0.01).toBe(true); } } ; const refusalOf = (attempt: Promise) => attempt.then( () => null, (error: unknown) => error, ); const markedField = async ( doc: DocumentHandle, name: string, placement:{ box: PageBox; rotation?: 90 | 180 | 270} , ): Promise =>{ const{ field} = await doc.forms.create({ kind: 'signature', name, widgets: [{ page: FIRST, ...placement} ], } ); await doc.forms.setSignatureAppearance(field.ref, { pdf: MARK_PDF} ); return rowOf(doc, name); } ; const drawn = (doc: DocumentHandle, row: WidgetAnnotation) => appearanceRaster(doc.page(FIRST), row.ref, 'forms'); test('/MK /R reads as the clockwise turn, with the box it turns; rect is where it stands', async () =>{ await withDoc(async (doc) =>{ const turns: Record ={ } ; for (const name of ['upright', 'r90', 'r180', 'r270', 'odd', 'negative', 'on-turned']){ turns[name] = (await rowOf(doc, name)).rotation; } expect(turns).toEqual({ upright: null, r90: 270, r180: 180, r270: 90, odd: null, negative: 90, 'on-turned': 270, } ); const r90 = await rowOf(doc, 'r90'); expectBox(r90.rect, { x: 20, y: 120, width: 24, height: 160} ); expectBox(r90.box, swapped(r90.rect)); const r180 = await rowOf(doc, 'r180'); expectBox(r180.box, r180.rect); } ); } ); test('a turned field fills and saves with its turn', async () =>{ let bytes: Uint8Array | null = null; await withDoc(async (doc) =>{ const name = (await doc.forms.list()).fields.find((f) => f.name === 'r90')!; await doc.forms.setValue(name.ref, { value: 'Turned'} ); bytes = await doc.download(); } ); await withDoc(async (doc) =>{ const row = await rowOf(doc, 'r90'); expect(row.rotation).toBe(270); expectBox(row.rect, { x: 20, y: 120, width: 24, height: 160} ); const field = (await doc.forms.list()).fields.find((f) => f.name === 'r90')!; expect(field).toMatchObject({ value: 'Turned'} ); } , bytes!); } ); test("a placement's rotation turns a new field's contents inside its rect", async () =>{ await withDoc(async (doc) =>{ const rect ={ x: 100, y: 40, width: 24, height: 160} ; const{ field} = await doc.forms.create({ kind: 'text', name: 'side', widgets: [{ page: FIRST, rect, rotation: 270} ], } ); const row = await rowOf(doc, field.name); expect(row.rotation).toBe(270); expectBox(row.rect, rect); expectBox(row.box, swapped(rect)); const refused = await refusalOf( doc.forms.create({ kind: 'text', name: 'tilted', widgets: [{ page: FIRST, rect, rotation: 45 as never} ], } ), ); expect(EngineError.is(refused, EngineErrorCode.InvalidArg)).toBe(true); } ); } ); test('a placement gives where the widget stands or its frame: the same widget either way', async () =>{ await withDoc(async (doc) =>{ const rect ={ x: 150, y: 40, width: 24, height: 160} ; const{ field} = await doc.forms.create({ kind: 'text', name: 'by-box', widgets: [{ page: FIRST, box: swapped(rect), rotation: 270} ], } ); const row = await rowOf(doc, field.name); expect(row.rotation).toBe(270); expectBox(row.rect, rect); expectBox(row.box, swapped(rect)); const neither = await refusalOf( doc.forms.create({ kind: 'text', name: 'nowhere', widgets: [{ page: FIRST} ]} ), ); expect(EngineError.is(neither, EngineErrorCode.InvalidArg)).toBe(true); } ); } ); test('a turn turns the widget about its middle; a new box with it keeps the widget in place', async () =>{ await withDoc(async (doc) =>{ const before = await rowOf(doc, 'upright'); const turned = await doc.forms.updateWidget(before.ref, { rotation: 90} ); expect(turned.widget.rotation).toBe(90); expectBox(turned.widget.box, before.box); expectBox(turned.widget.rect, swapped(before.rect)); const oriented = await doc.forms.updateWidget(before.ref, { rotation: 270, box: swapped(before.rect), } ); expect(oriented.widget.rotation).toBe(270); expectBox(oriented.widget.rect, before.rect); const straight = await doc.forms.updateWidget(before.ref, { rotation: null} ); expect(straight.widget.rotation).toBe(null); } ); } ); test('rect moves and resizes a quarter-turned widget; its turn stays', async () =>{ await withDoc(async (doc) =>{ const row = await rowOf(doc, 'r90'); const rect ={ x: 30, y: 60, width: 40, height: 200} ; const{ widget} = await doc.forms.updateWidget(row.ref, { rect} ); expect(widget.rotation).toBe(270); expectBox(widget.rect, rect); expectBox(widget.box, swapped(rect)); } ); } ); test("a widget's turn is a quarter turn: another is refused", async () =>{ await withDoc(async (doc) =>{ const row = await rowOf(doc, 'upright'); const refused = await refusalOf(doc.forms.updateWidget(row.ref, { rotation: 45 as never} )); expect(EngineError.is(refused, EngineErrorCode.InvalidArg)).toBe(true); expect((await rowOf(doc, 'upright')).rotation).toBe(null); } ); } ); test('undo puts a turn back, and redo turns it again', async () =>{ await withDoc(async (doc) =>{ const row = await rowOf(doc, 'r180'); const turned = await doc.forms.updateWidget(row.ref, { rotation: 90} ); const undo = await doc.apply({ undoOf: turned.meta.opId} ); const back = await rowOf(doc, 'r180'); expect(back.rotation).toBe(180); expectBox(back.rect, row.rect); await doc.apply({ undoOf: undo.meta.opId} ); expect((await rowOf(doc, 'r180')).rotation).toBe(90); } ); } ); test('a mark drawn into a turned signature field is fitted into its frame and turned with it', async () =>{ await withDoc(async (doc) =>{ const upright = await drawn(doc, await markedField(doc, 'plain', { box: MARK_FRAME} )); const turned = await markedField(doc, 'turned', { box:{ ...MARK_FRAME, y: 120} , rotation: 90, } ); expect(turned.hasMark).toBe(true); expectBox(turned.rect, swapped(turned.box)); const raster = await drawn(doc, turned); expect([raster.width, raster.height]).toEqual([upright.height, upright.width]); expect(maxShiftedDifference(raster, quarterTurned(upright)) <= 3).toBe(true); } ); } ); test('a turn turns the mark in a field, a new frame fits it again, and undo puts it back', async () =>{ await withDoc(async (doc) =>{ const row = await markedField(doc, 'marked', { box: MARK_FRAME} ); const upright = await drawn(doc, row); const turned = await doc.forms.updateWidget(row.ref, { rotation: 90} ); expect(turned.appearance.changed).toBe(true); expect(turned.widget.hasMark).toBe(true); expect(maxShiftedDifference(await drawn(doc, row), quarterTurned(upright)) <= 3).toBe(true); const oriented = await doc.forms.updateWidget(row.ref, { rotation: null, box: turned.widget.rect, } ); const fresh = await markedField(doc, 'fresh', { box:{ ...turned.widget.rect, x: 40} , } ); expect(maxShiftedDifference(await drawn(doc, row), await drawn(doc, fresh)) <= 3).toBe( true, ); await doc.apply({ undoOf: oriented.meta.opId} ); await doc.apply({ undoOf: turned.meta.opId} ); expect((await rowOf(doc, 'marked')).rotation).toBe(null); expect(maxShiftedDifference(await drawn(doc, row), upright) <= 3).toBe(true); } ); } ); test("a signed field's mark turns with it as well", async () =>{ if (options.completesSignings === false) return; await withDoc(async (doc) =>{ if (!doc.signatures) return; const{ field} = await doc.forms.create({ kind: 'signature', name: 'signed', widgets: [{ page: FIRST, box: MARK_FRAME} ], } ); const prepared = await doc.signatures.prepare({ field: field.ref, signer:{ name: 'Signer'} , appearance:{ pdf: MARK_PDF} , } ); await doc.signatures.complete({ signingId: prepared.signingId, cms: PLACEHOLDER_CMS, expectedVersion: prepared.expectedVersion, } ); const row = await rowOf(doc, 'signed'); expect(row.hasMark).toBe(true); const upright = await drawn(doc, row); await doc.forms.updateWidget(row.ref, { rotation: 90} ); expect(maxShiftedDifference(await drawn(doc, row), quarterTurned(upright)) <= 3).toBe(true); } ); } ); test('a form bundle carries the turn', async () =>{ let bundle: Awaited> | null = null; await withDoc(async (doc) =>{ bundle = await doc.forms.export({ pages: [FIRST]} ); } ); await withDoc(async (copy) =>{ await copy.forms.import(bundle!, { attribution: 'stamp'} ); for (const name of ['upright', 'r90', 'r180', 'r270']){ const first = bundle!.fields.find((f) => f.data.name === name)!.data.widgets[0]!; const source = bundle!.widgets.find( ({ data} ) => annotationKey(data.ref) === annotationKey(first.ref!), )!.data; const row = await rowOf(copy, name); expect({ name, rotation: row.rotation} ).toEqual({ name, rotation: source.rotation} ); expectBox(row.rect, source.rect); } } , TWO_PAGES_PDF); } ); } ); } withUnknownFields [FunctionDeclaration] (from packages/engine/core/src/conformance/tolerantReading.ts): export function withUnknownFields(schema: z.ZodTypeAny, value: unknown): unknown{ const def = defOf(schema); switch (def.typeName){ case 'ZodObject':{ if (!isPlainObject(value)) return value; const shape = def.shape() as Record; const out: Record ={ } ; for (const [key, child] of Object.entries(value)){ const field = shape[key]; out[key] = field ? withUnknownFields(field, child) : child; } if (defOf(def.catchall).typeName !== 'ZodNever') return out; return{ ...out, [UNKNOWN_FIELD]: UNKNOWN_VALUE} ; } case 'ZodArray': return Array.isArray(value) ? value.map((item) => withUnknownFields(def.type, item)) : value; case 'ZodTuple': return Array.isArray(value) ? value.map((item, index) =>{ const element = def.items[index] ?? def.rest; return element ? withUnknownFields(element, item) : item; } ) : value; case 'ZodRecord': return isPlainObject(value) ? Object.fromEntries( Object.entries(value).map(([key, child]) => [ key, withUnknownFields(def.valueType, child), ]), ) : value; case 'ZodOptional': case 'ZodNullable': case 'ZodDefault': case 'ZodCatch': case 'ZodReadonly': return value === undefined || value === null ? value : withUnknownFields(def.innerType, value); case 'ZodBranded': return withUnknownFields(def.type, value); case 'ZodLazy': return withUnknownFields(def.getter(), value); case 'ZodEffects': return withUnknownFields(def.schema, value); case 'ZodPipeline': return withUnknownFields(def.in, value); case 'ZodIntersection': return withUnknownFields(def.right, withUnknownFields(def.left, value)); case 'ZodDiscriminatedUnion':{ if (!isPlainObject(value)) return value; const option = def.optionsMap.get(value[def.discriminator]); return option ? withUnknownFields(option, value) : value; } case 'ZodUnion':{ const option = (def.options as z.ZodTypeAny[]).find( (candidate) => candidate.safeParse(value).success, ); return option ? withUnknownFields(option, value) : value; } default: return value; } }