@typfolio/dev-tools 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,14 @@ export interface PdfStructureElement {
8
8
  alt?: string;
9
9
  /** The element's `/Lang`. */
10
10
  lang?: string;
11
+ /** A `Table`'s `/Summary`: what the table is about, for a reader who cannot see it. */
12
+ summary?: string;
13
+ /** A `TH`'s `/Scope`: whether it labels its row, its column or both. */
14
+ scope?: 'Row' | 'Column' | 'Both';
15
+ /** A `TH`'s `/ID`, which other cells' `headers` name. */
16
+ id?: string;
17
+ /** A `TH` or `TD`'s `/Headers`: the `id` of each header cell that labels it. */
18
+ headers?: string[];
11
19
  children: PdfStructureElement[];
12
20
  }
13
21
  /**
@@ -45,6 +53,10 @@ export interface PdfStructureSource {
45
53
  }>;
46
54
  }>;
47
55
  }
56
+ /** A rectangle on a page in PDF units, origin at the bottom left: `[left, bottom, right, top]`. */
57
+ export type PdfRect = [number, number, number, number];
58
+ /** Where each element's content is drawn on its page; an element without drawn content has no entry. */
59
+ export type PdfElementBoxes = WeakMap<PdfStructureElement, PdfRect>;
48
60
  /** What pdf.js's `getMarkInfo()` resolves to. */
49
61
  export type PdfMarkInfo = {
50
62
  Marked?: boolean;
@@ -52,8 +64,8 @@ export type PdfMarkInfo = {
52
64
  /** The catalog's `/MarkInfo /Marked` is true. */
53
65
  export declare const isMarked: (markInfo: PdfMarkInfo) => boolean;
54
66
  export declare const headingLevel: (role: string) => number | undefined;
55
- /** A page's part of the structure tree; null when the page has none. */
56
- export declare function pageStructure(page: Awaited<ReturnType<PdfStructureSource['getPage']>>): Promise<PdfStructureElement[] | null>;
67
+ /** A page's part of the structure tree; null when the page has none. With `boxes`, also where each element is drawn. */
68
+ export declare function pageStructure(page: Awaited<ReturnType<PdfStructureSource['getPage']>>, boxes?: PdfElementBoxes): Promise<PdfStructureElement[] | null>;
57
69
  /** Calls `visit` on every element of every page, parents before children, in reading order. */
58
70
  export declare function eachElement(pages: readonly PdfStructurePage[], visit: (element: PdfStructureElement, page: number) => void): void;
59
71
  /**
@@ -87,7 +99,7 @@ export declare function structureWarnings(pages: readonly PdfStructurePage[]): P
87
99
  */
88
100
  export declare function readDocument(document: PdfStructureSource & {
89
101
  getMarkInfo(): Promise<PdfMarkInfo>;
90
- }): Promise<{
102
+ }, boxes?: PdfElementBoxes): Promise<{
91
103
  tagged: boolean;
92
104
  pages: PdfStructurePage[];
93
105
  warnings: PdfStructureWarning[];
package/dist/structure.js CHANGED
@@ -1,6 +1,15 @@
1
1
  // The structure tree, as a screen reader gets it, and the rules that read it. Internal: `@typfolio/dev-tools/pdf`
2
2
  // exports the public part, and the structure panel bundles it. Nothing here loads pdf.js; callers pass a document.
3
3
  import { TypstPdfError } from '@typfolio/core';
4
+ const union = (a, b) => !a ? b : !b ? a : [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])];
5
+ // The box of a run of text: pdf.js gives its baseline origin, its advance and its font size. The share of the font
6
+ // size above and below the baseline is an estimate that fits Latin text; upright text only.
7
+ function textRect({ str, transform, width, height }) {
8
+ if (!str?.trim() || !Array.isArray(transform) || typeof width !== 'number' || typeof height !== 'number' || !(width > 0) || !(height > 0))
9
+ return undefined;
10
+ const [, , , , x, y] = transform;
11
+ return [x, y - height * 0.22, x + width, y + height * 0.8];
12
+ }
4
13
  /** The catalog's `/MarkInfo /Marked` is true. */
5
14
  export const isMarked = (markInfo) => (markInfo instanceof Map ? markInfo.get('Marked') : markInfo?.Marked) === true;
6
15
  export const headingLevel = (role) => {
@@ -11,7 +20,7 @@ export const headingLevel = (role) => {
11
20
  * The text of each marked-content section that has an id, by id. Text goes to its innermost section with an id;
12
21
  * an artifact's text (a running header, a page number) goes to none, as a screen reader skips it.
13
22
  */
14
- function textByContentId(items) {
23
+ function textByContentId(items, rects) {
15
24
  const byId = new Map();
16
25
  const open = [];
17
26
  for (const item of items) {
@@ -25,6 +34,9 @@ function textByContentId(items) {
25
34
  const id = open.at(-1);
26
35
  if (id)
27
36
  byId.set(id, (byId.get(id) ?? '') + item.str + (item.hasEOL ? ' ' : ''));
37
+ const rect = id && rects ? union(rects.get(id), textRect(item)) : undefined;
38
+ if (id && rect)
39
+ rects.set(id, rect);
28
40
  }
29
41
  }
30
42
  return byId;
@@ -33,37 +45,54 @@ function textByContentId(items) {
33
45
  // them, where a block element's text is a separate run.
34
46
  const inlineRoles = new Set(['Span', 'Quote', 'Note', 'Reference', 'BibEntry', 'Code', 'Link', 'Annot', 'Ruby', 'RB', 'RT', 'RP', 'Warichu', 'WT', 'WP', 'Em', 'Strong', 'Sub']);
35
47
  const isElement = (node) => typeof node.role === 'string';
36
- function toElement(node, textById) {
48
+ // An element's `/BBox`, as a figure has. pdf.js gives a `/Width` and `/Height` without a position as a box at the
49
+ // origin, which is not a place on the page.
50
+ function ownBox(bbox) {
51
+ if (!Array.isArray(bbox) || bbox.length !== 4 || !bbox.every(value => typeof value === 'number' && Number.isFinite(value)))
52
+ return undefined;
53
+ const [left, bottom, right, top] = bbox;
54
+ return (left === 0 && bottom === 0) || !(right > left) || !(top > bottom) ? undefined : [left, bottom, right, top];
55
+ }
56
+ function toElement(node, textById, placement) {
37
57
  const children = [];
38
58
  let raw = '';
59
+ let box = placement ? ownBox(node.bbox) : undefined;
39
60
  for (const child of node.children ?? []) {
40
61
  if (isElement(child)) {
41
- const built = toElement(child, textById);
62
+ const built = toElement(child, textById, placement);
42
63
  children.push(built.element);
43
64
  raw += inlineRoles.has(built.element.role) ? built.raw : ` ${built.raw} `;
65
+ box = union(box, built.box);
44
66
  }
45
- else if (child.type === 'content' && typeof child.id === 'string')
67
+ else if (child.type === 'content' && typeof child.id === 'string') {
46
68
  raw += textById.get(child.id) ?? '';
69
+ box = union(box, placement?.rects.get(child.id));
70
+ }
47
71
  }
48
- return {
49
- element: {
50
- role: node.role,
51
- text: raw.replace(/\s+/g, ' ').trim(),
52
- ...(typeof node.alt === 'string' ? { alt: node.alt } : {}),
53
- ...(typeof node.lang === 'string' ? { lang: node.lang } : {}),
54
- children,
55
- },
56
- raw,
72
+ const element = {
73
+ role: node.role,
74
+ text: raw.replace(/\s+/g, ' ').trim(),
75
+ ...(typeof node.alt === 'string' ? { alt: node.alt } : {}),
76
+ ...(typeof node.lang === 'string' ? { lang: node.lang } : {}),
77
+ ...(typeof node.summary === 'string' ? { summary: node.summary } : {}),
78
+ ...(node.scope === 'Row' || node.scope === 'Column' || node.scope === 'Both' ? { scope: node.scope } : {}),
79
+ ...(typeof node.structId === 'string' ? { id: node.structId } : {}),
80
+ ...(Array.isArray(node.headers) ? { headers: node.headers.filter((id) => typeof id === 'string') } : {}),
81
+ children,
57
82
  };
83
+ if (box)
84
+ placement.boxes.set(element, box);
85
+ return { element, raw, box };
58
86
  }
59
- /** A page's part of the structure tree; null when the page has none. */
60
- export async function pageStructure(page) {
87
+ /** A page's part of the structure tree; null when the page has none. With `boxes`, also where each element is drawn. */
88
+ export async function pageStructure(page, boxes) {
61
89
  const tree = await page.getStructTree();
62
90
  if (!tree)
63
91
  return null;
64
92
  const { items } = await page.getTextContent({ includeMarkedContent: true });
65
- const textById = textByContentId(items);
66
- return (tree.children ?? []).filter(isElement).map(child => toElement(child, textById).element);
93
+ const placement = boxes && { rects: new Map(), boxes };
94
+ const textById = textByContentId(items, placement?.rects);
95
+ return (tree.children ?? []).filter(isElement).map(child => toElement(child, textById, placement).element);
67
96
  }
68
97
  /** Calls `visit` on every element of every page, parents before children, in reading order. */
69
98
  export function eachElement(pages, visit) {
@@ -81,13 +110,16 @@ export function eachElement(pages, visit) {
81
110
  * has, such as one a browser page loaded with its own pdf.js. Needs nothing installed: `inspectPdf` returns the
82
111
  * same pages as `structure`.
83
112
  */
84
- export async function readStructure(document) {
113
+ export function readStructure(document) {
114
+ return readPages(document);
115
+ }
116
+ async function readPages(document, boxes) {
85
117
  if (!document || typeof document.getPage !== 'function' || !Number.isSafeInteger(document.numPages)) {
86
118
  throw new TypstPdfError('INVALID_REQUEST', 'readStructure takes a pdf.js document (PDFDocumentProxy)');
87
119
  }
88
120
  const pages = [];
89
121
  for (let page = 1; page <= document.numPages; page += 1) {
90
- pages.push({ page, elements: await pageStructure(await document.getPage(page)) ?? [] });
122
+ pages.push({ page, elements: await pageStructure(await document.getPage(page), boxes) ?? [] });
91
123
  }
92
124
  return pages;
93
125
  }
@@ -167,9 +199,9 @@ export function structureWarnings(pages) {
167
199
  * A pdf.js document's pages and their warnings: one `untagged` warning when it is not tagged, else the
168
200
  * `structureWarnings` of its pages. What `checkStructure` reports, and what the panel shows.
169
201
  */
170
- export async function readDocument(document) {
202
+ export async function readDocument(document, boxes) {
171
203
  const tagged = isMarked(await document.getMarkInfo());
172
- const pages = await readStructure(document);
204
+ const pages = await readPages(document, boxes);
173
205
  const warnings = tagged
174
206
  ? structureWarnings(pages)
175
207
  : [{ kind: 'untagged', message: 'The PDF is not tagged, so a screen reader gets its text with no headings, tables or figures.' }];
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ // typfolio-validate: validates PDF files with veraPDF (`@typfolio/dev-tools/validate`), for a script or CI.
3
+ // Exit status: 0 when every file passes, 1 when one fails, 2 for wrong usage or a file that could not be validated.
4
+ import { readFile } from 'node:fs/promises';
5
+ import { createPdfValidator, formatValidationReport, pdfValidationFlavourIds, pdfValidationFlavours } from './validate.js';
6
+ const usage = `Usage: typfolio-validate [options] <file.pdf>...
7
+
8
+ Validates each file with veraPDF and prints a report. A pass is a machine check of
9
+ one flavour's rules; it does not establish that a document is accessible.
10
+
11
+ Options:
12
+ -f, --flavour <id> What to validate against (default: ua1). "auto" validates each file against
13
+ every standard it declares in its metadata; a file that declares none
14
+ counts as not validated.
15
+ ${pdfValidationFlavourIds.map(id => ` ${id.padEnd(6)}${pdfValidationFlavours[id]}`).join('\n')}
16
+ --format <kind> text (default) or json
17
+ --max-checks <n> How many failed checks of one rule to list (default: 3 as text, 20 as json)
18
+ --wasm <file> The validator's binary, when not the installed @typfolio/verapdf-wasm
19
+ -h, --help Show this text
20
+
21
+ Exit status: 0 all files pass, 1 a file fails, 2 wrong usage or a file could not be validated.`;
22
+ function fail(message) {
23
+ process.stderr.write(`typfolio-validate: ${message}\n`);
24
+ process.exit(2);
25
+ }
26
+ const args = process.argv.slice(2);
27
+ let flavour = 'ua1';
28
+ let format = 'text';
29
+ let wasmPath;
30
+ let maxChecks;
31
+ const files = [];
32
+ for (let index = 0; index < args.length; index++) {
33
+ const arg = args[index];
34
+ const value = (name) => args[++index] ?? fail(`${name} needs a value`);
35
+ if (arg === '-h' || arg === '--help') {
36
+ process.stdout.write(usage + '\n');
37
+ process.exit(0);
38
+ }
39
+ else if (arg === '-f' || arg === '--flavour' || arg === '--flavor')
40
+ flavour = value(arg);
41
+ else if (arg.startsWith('--flavour=') || arg.startsWith('--flavor='))
42
+ flavour = arg.slice(arg.indexOf('=') + 1);
43
+ else if (arg === '--format')
44
+ format = value(arg);
45
+ else if (arg.startsWith('--format='))
46
+ format = arg.slice('--format='.length);
47
+ else if (arg === '--max-checks')
48
+ maxChecks = value(arg);
49
+ else if (arg.startsWith('--max-checks='))
50
+ maxChecks = arg.slice('--max-checks='.length);
51
+ else if (arg === '--wasm')
52
+ wasmPath = value(arg);
53
+ else if (arg.startsWith('--wasm='))
54
+ wasmPath = arg.slice('--wasm='.length);
55
+ else if (arg === '--') {
56
+ files.push(...args.slice(index + 1));
57
+ break;
58
+ }
59
+ else if (arg.startsWith('-') && arg !== '-')
60
+ fail(`unknown option ${arg}\n\n${usage}`);
61
+ else
62
+ files.push(arg);
63
+ }
64
+ if (flavour !== 'auto' && !(flavour in pdfValidationFlavours))
65
+ fail(`unknown flavour ${JSON.stringify(flavour)}; the flavours are auto, ${pdfValidationFlavourIds.join(', ')}`);
66
+ if (format !== 'text' && format !== 'json')
67
+ fail(`unknown format ${JSON.stringify(format)}; it is text or json`);
68
+ const maxChecksPerRule = maxChecks === undefined ? (format === 'json' ? 20 : 3) : Number(maxChecks);
69
+ if (!Number.isInteger(maxChecksPerRule) || maxChecksPerRule < 1 || maxChecksPerRule > 10000)
70
+ fail(`--max-checks must be a whole number from 1 to 10000, not ${JSON.stringify(maxChecks)}`);
71
+ if (files.length === 0)
72
+ fail(`no file given\n\n${usage}`);
73
+ const message = (error) => error instanceof Error ? error.message : String(error);
74
+ let validator;
75
+ try {
76
+ validator = await createPdfValidator({ wasm: wasmPath === undefined ? undefined : await readFile(wasmPath) });
77
+ }
78
+ catch (error) {
79
+ fail(message(error));
80
+ }
81
+ const results = [];
82
+ for (const file of files) {
83
+ try {
84
+ const bytes = await readFile(file);
85
+ if (flavour === 'auto') {
86
+ const reports = validator.validateDeclared(bytes, { maxChecksPerRule });
87
+ if (reports.length === 0)
88
+ results.push({ file, error: 'the file declares no standard in its metadata; name one with --flavour' });
89
+ for (const report of reports)
90
+ results.push({ file, ...report });
91
+ }
92
+ else {
93
+ results.push({ file, ...validator.validate(bytes, { flavour: flavour, maxChecksPerRule }) });
94
+ }
95
+ }
96
+ catch (error) {
97
+ results.push({ file, error: message(error) });
98
+ }
99
+ }
100
+ if (format === 'json')
101
+ process.stdout.write(JSON.stringify(results, null, 2) + '\n');
102
+ else {
103
+ for (const result of results) {
104
+ if ('error' in result)
105
+ process.stdout.write(`${result.file}: ERROR ${result.error}\n`);
106
+ else
107
+ process.stdout.write(formatValidationReport(result, result.file) + '\n');
108
+ }
109
+ }
110
+ process.exitCode = results.some(result => 'error' in result) ? 2 : results.some(result => !('error' in result) && !result.compliant) ? 1 : 0;
@@ -0,0 +1,58 @@
1
+ import { type PdfValidationFlavour, type PdfValidationReport } from './validation.js';
2
+ export { pdfValidationFlavourIds, pdfValidationFlavours } from './validation.js';
3
+ export type { PdfValidationCheck, PdfValidationFlavour, PdfValidationLog, PdfValidationReport, PdfValidationRule } from './validation.js';
4
+ export interface PdfValidateOptions {
5
+ flavour: PdfValidationFlavour;
6
+ /** How many failed checks of one rule to list, from 1 to 10000; 20 unless given. The counts are exact either way. */
7
+ maxChecksPerRule?: number;
8
+ }
9
+ export interface PdfValidator {
10
+ /** Synchronous, and from milliseconds to seconds long: in a page, consider a worker. */
11
+ validate(pdf: Uint8Array, options: PdfValidateOptions): PdfValidationReport;
12
+ /**
13
+ * The flavours the file declares in its metadata, as veraPDF reads them: `['2a', 'ua1']` for a file compiled as
14
+ * PDF/A-2a and PDF/UA-1, empty when it declares none. A declaration is a claim, not a verdict.
15
+ */
16
+ detectFlavours(pdf: Uint8Array): PdfValidationFlavour[];
17
+ /**
18
+ * Validates the file against every flavour it declares: one report each, and none for a file that declares none,
19
+ * which is not a pass.
20
+ */
21
+ validateDeclared(pdf: Uint8Array, options?: {
22
+ maxChecksPerRule?: number;
23
+ }): PdfValidationReport[];
24
+ }
25
+ export interface PdfValidatorOptions {
26
+ /**
27
+ * The validator's binary, `@typfolio/verapdf-wasm/verapdf.wasm`: its bytes or a compiled module. In Node it may be
28
+ * left out, and the file is read from the installed package. A browser has to pass it.
29
+ */
30
+ wasm?: BufferSource | WebAssembly.Module;
31
+ }
32
+ /**
33
+ * Starts a veraPDF validator of your own, to validate many files or to run in a worker. Rejects with a
34
+ * `TypstPdfError`: `INITIALIZATION` when `@typfolio/verapdf-wasm` is not installed or its binary cannot be started,
35
+ * `INVALID_REQUEST` when a browser passes no `wasm`. Its `validate` throws `INVALID_REQUEST` for a flavour it does not
36
+ * know and for bytes veraPDF cannot read as a PDF.
37
+ */
38
+ export declare function createPdfValidator(options?: PdfValidatorOptions): Promise<PdfValidator>;
39
+ /**
40
+ * Validates one PDF against one flavour with veraPDF, for a test or a script: `(await validatePdf(bytes, { flavour:
41
+ * 'ua1' })).compliant`. The validator is started on the first call and kept; `wasm` is used by that first call only.
42
+ * Rejects like `createPdfValidator` and its `validate`.
43
+ */
44
+ export declare function validatePdf(bytes: Uint8Array, options: PdfValidateOptions & PdfValidatorOptions): Promise<PdfValidationReport>;
45
+ /**
46
+ * Validates one PDF against every flavour it declares in its metadata: `const reports = await
47
+ * validateDeclaredPdf(bytes)`. One report per declared flavour, and none for a file that declares none, so check the
48
+ * length before `every(report => report.compliant)`. For a test that a template produces a given standard, name the
49
+ * flavour with `validatePdf`: this only checks what the file claims. Shares `validatePdf`'s validator.
50
+ */
51
+ export declare function validateDeclaredPdf(bytes: Uint8Array, options?: {
52
+ maxChecksPerRule?: number;
53
+ } & PdfValidatorOptions): Promise<PdfValidationReport[]>;
54
+ /**
55
+ * A report as lines of text: the verdict, then each failed rule with its clause, test, count and description, and
56
+ * under it the failed checks that are listed, each with what was wrong and where.
57
+ */
58
+ export declare function formatValidationReport(report: PdfValidationReport, name?: string): string;
@@ -0,0 +1,134 @@
1
+ // PDF/A and PDF/UA validation with veraPDF, compiled to WebAssembly. `@typfolio/verapdf-wasm` is an optional peer
2
+ // dependency, loaded on the first call and only from this entry, so the other entries never see it. It is a package
3
+ // of its own because its binary is not open source as a whole (see its README); nothing here bundles it.
4
+ //
5
+ // A report says whether a file passes the machine-checkable rules of one flavour as veraPDF implements them. A pass
6
+ // does not establish that a document is accessible: whether the tags, the reading order and the alternative text make
7
+ // sense still needs a person.
8
+ import { TypstPdfError } from '@typfolio/core';
9
+ import { pdfValidationFlavours } from './validation.js';
10
+ export { pdfValidationFlavourIds, pdfValidationFlavours } from './validation.js';
11
+ /** Shared by concurrent callers, so it carries no call identity. */
12
+ class VerapdfImportError extends Error {
13
+ }
14
+ let module;
15
+ function loadVerapdf() {
16
+ module ??= (async () => {
17
+ let imported;
18
+ try {
19
+ imported = await import('@typfolio/verapdf-wasm');
20
+ }
21
+ catch (cause) {
22
+ throw new VerapdfImportError('@typfolio/verapdf-wasm could not be imported', { cause });
23
+ }
24
+ if (typeof imported?.createValidator !== 'function') {
25
+ throw new TypeError('@typfolio/verapdf-wasm did not provide the API this version of @typfolio/dev-tools uses (createValidator)');
26
+ }
27
+ return imported;
28
+ })().catch(cause => {
29
+ module = undefined;
30
+ throw cause;
31
+ });
32
+ return module;
33
+ }
34
+ async function installedBinary(caller) {
35
+ if (typeof globalThis.process?.versions?.node !== 'string') {
36
+ throw new TypstPdfError('INVALID_REQUEST', `${caller} needs \`wasm\` outside Node: the bytes of @typfolio/verapdf-wasm/verapdf.wasm, or a compiled WebAssembly.Module`);
37
+ }
38
+ // Not a literal, so that a bundler building this entry for a browser does not go looking for Node's modules.
39
+ const fs = 'node:fs/promises';
40
+ const { readFile } = await import(/* @vite-ignore */ fs);
41
+ return readFile(new URL(import.meta.resolve('@typfolio/verapdf-wasm/verapdf.wasm')));
42
+ }
43
+ // A veraPDF error keeps its message; its code becomes one of core's.
44
+ function translated(caller, error) {
45
+ const code = error?.code;
46
+ if (!(error instanceof Error) || error.name !== 'VerapdfError' || typeof code !== 'string')
47
+ return error;
48
+ return new TypstPdfError(code === 'INITIALIZATION' ? 'INITIALIZATION' : 'INVALID_REQUEST', `${caller}: ${error.message}`, [], { cause: error });
49
+ }
50
+ /**
51
+ * Starts a veraPDF validator of your own, to validate many files or to run in a worker. Rejects with a
52
+ * `TypstPdfError`: `INITIALIZATION` when `@typfolio/verapdf-wasm` is not installed or its binary cannot be started,
53
+ * `INVALID_REQUEST` when a browser passes no `wasm`. Its `validate` throws `INVALID_REQUEST` for a flavour it does not
54
+ * know and for bytes veraPDF cannot read as a PDF.
55
+ */
56
+ export async function createPdfValidator(options = {}) {
57
+ const caller = 'createPdfValidator';
58
+ let verapdf;
59
+ try {
60
+ verapdf = await loadVerapdf();
61
+ }
62
+ catch (error) {
63
+ if (!(error instanceof VerapdfImportError))
64
+ throw error;
65
+ throw new TypstPdfError('INITIALIZATION', `${caller} could not load @typfolio/verapdf-wasm. Install @typfolio/verapdf-wasm (an optional peer dependency of @typfolio/dev-tools) to use @typfolio/dev-tools/validate.`, [], { cause: error.cause });
66
+ }
67
+ let validator;
68
+ try {
69
+ validator = await verapdf.createValidator({ wasm: options?.wasm ?? await installedBinary(caller) });
70
+ }
71
+ catch (error) {
72
+ throw translated(caller, error);
73
+ }
74
+ const guarded = (name, call) => {
75
+ try {
76
+ return call();
77
+ }
78
+ catch (error) {
79
+ throw translated(name, error);
80
+ }
81
+ };
82
+ return {
83
+ validate: (pdf, validateOptions) => guarded('validate', () => validator.validate(pdf, validateOptions)),
84
+ detectFlavours: pdf => guarded('detectFlavours', () => validator.detectFlavours(pdf)),
85
+ validateDeclared: (pdf, declaredOptions) => guarded('validateDeclared', () => validator.validateDeclared(pdf, declaredOptions)),
86
+ };
87
+ }
88
+ let shared;
89
+ function sharedValidator(wasm) {
90
+ shared ??= createPdfValidator({ wasm }).catch(cause => {
91
+ shared = undefined;
92
+ throw cause;
93
+ });
94
+ return shared;
95
+ }
96
+ /**
97
+ * Validates one PDF against one flavour with veraPDF, for a test or a script: `(await validatePdf(bytes, { flavour:
98
+ * 'ua1' })).compliant`. The validator is started on the first call and kept; `wasm` is used by that first call only.
99
+ * Rejects like `createPdfValidator` and its `validate`.
100
+ */
101
+ export async function validatePdf(bytes, options) {
102
+ return (await sharedValidator(options?.wasm)).validate(bytes, { flavour: options?.flavour, maxChecksPerRule: options?.maxChecksPerRule });
103
+ }
104
+ /**
105
+ * Validates one PDF against every flavour it declares in its metadata: `const reports = await
106
+ * validateDeclaredPdf(bytes)`. One report per declared flavour, and none for a file that declares none, so check the
107
+ * length before `every(report => report.compliant)`. For a test that a template produces a given standard, name the
108
+ * flavour with `validatePdf`: this only checks what the file claims. Shares `validatePdf`'s validator.
109
+ */
110
+ export async function validateDeclaredPdf(bytes, options = {}) {
111
+ return (await sharedValidator(options?.wasm)).validateDeclared(bytes, { maxChecksPerRule: options?.maxChecksPerRule });
112
+ }
113
+ /**
114
+ * A report as lines of text: the verdict, then each failed rule with its clause, test, count and description, and
115
+ * under it the failed checks that are listed, each with what was wrong and where.
116
+ */
117
+ export function formatValidationReport(report, name) {
118
+ const flavour = pdfValidationFlavours[report.flavour] ?? report.flavour;
119
+ const subject = name === undefined ? '' : `${name}: `;
120
+ // What veraPDF logged while reading the file: a pass with messages means it validated what it could read.
121
+ const logs = (report.logs ?? []).map(log => ` ${log.level}${log.occurrences > 1 ? ` (${log.occurrences}x)` : ''}: ${log.message}`);
122
+ if (report.compliant)
123
+ return [`${subject}PASS ${flavour} (${report.totalAssertions} checks)${logs.length > 0 ? `, with ${logs.length} veraPDF message${logs.length === 1 ? '' : 's'}` : ''}`, ...logs].join('\n');
124
+ const failed = report.failedRules.reduce((sum, rule) => sum + rule.failedChecks, 0);
125
+ const lines = [`${subject}FAIL ${flavour}: ${report.failedRules.length} rule${report.failedRules.length === 1 ? '' : 's'}, ${failed} of ${report.totalAssertions} checks`];
126
+ for (const rule of report.failedRules) {
127
+ lines.push(` ${rule.specification} ${rule.clause}, test ${rule.test} (${rule.failedChecks}x)${rule.tags.length > 0 ? ` [${rule.tags.join(', ')}]` : ''}: ${rule.message}`);
128
+ for (const check of rule.checks)
129
+ lines.push(...(check.error ? [` ${check.error}`] : []), ` at ${check.context}`);
130
+ if (rule.failedChecks > rule.checks.length)
131
+ lines.push(` … and ${rule.failedChecks - rule.checks.length} more`);
132
+ }
133
+ return [...lines, ...logs].join('\n');
134
+ }
@@ -0,0 +1,63 @@
1
+ /** veraPDF's ids of the flavours that can be validated against. */
2
+ export type PdfValidationFlavour = '1a' | '1b' | '2a' | '2b' | '2u' | '3a' | '3b' | '3u' | '4' | '4e' | '4f' | 'ua1' | 'ua2' | 'wt1a' | 'wt1r';
3
+ /** The flavours in the order to list them: the accessibility standards first. */
4
+ export declare const pdfValidationFlavourIds: readonly PdfValidationFlavour[];
5
+ /** What each flavour is, for a choice shown to a person. */
6
+ export declare const pdfValidationFlavours: Readonly<Record<PdfValidationFlavour, string>>;
7
+ /** One failed check: where it was, and what was wrong there. */
8
+ export interface PdfValidationCheck {
9
+ /**
10
+ * A path in veraPDF's model of the file, with PDF object numbers where it has them. A glyph is named by, among
11
+ * other things, a number that changes from run to run, so two reports on the same file can differ there.
12
+ */
13
+ context: string;
14
+ /** What was wrong at this place, with the values found; empty when veraPDF gives none. */
15
+ error: string;
16
+ }
17
+ export interface PdfValidationRule {
18
+ /** The specification the rule comes from, for example `ISO 14289-1:2014`. */
19
+ specification: string;
20
+ clause: string;
21
+ /** The number of the test within the clause. */
22
+ test: number;
23
+ /** How many checks of this rule failed: exact, also when `checks` lists fewer. */
24
+ failedChecks: number;
25
+ /** veraPDF's description of the rule: what the standard requires. */
26
+ message: string;
27
+ /** Where the first failed check was: `checks[0].context`. */
28
+ context: string;
29
+ /** The kind of object in veraPDF's model that the rule is checked on, such as `SETable` or `PDFont`. */
30
+ object: string;
31
+ /** The expression over that object that has to hold, in veraPDF's profile language. */
32
+ condition: string;
33
+ /** veraPDF's topics for the rule, sorted: `structure`, `table`, `font`, `metadata`, `alt-text` and so on. */
34
+ tags: string[];
35
+ /** The failed checks, in the order veraPDF met them, up to `maxChecksPerRule` (20 unless you say). */
36
+ checks: PdfValidationCheck[];
37
+ }
38
+ /** Something veraPDF logged while it read and validated the file. */
39
+ export interface PdfValidationLog {
40
+ level: 'SEVERE' | 'WARNING';
41
+ message: string;
42
+ /** How often the same message came. */
43
+ occurrences: number;
44
+ }
45
+ export interface PdfValidationReport {
46
+ flavour: PdfValidationFlavour;
47
+ compliant: boolean;
48
+ /** How many checks veraPDF ran. */
49
+ totalAssertions: number;
50
+ /** The validation profile that was applied: its name, what it validates against, and how many rules it has. */
51
+ profile: {
52
+ name: string;
53
+ description: string;
54
+ rules: number;
55
+ };
56
+ /** One entry per rule with at least one failed check, ordered by specification, clause and test. */
57
+ failedRules: PdfValidationRule[];
58
+ /**
59
+ * What veraPDF logged at WARNING and above while reading the file, such as a font program or a content stream it
60
+ * could not parse. A file can pass with messages here: veraPDF then validated what it could read.
61
+ */
62
+ logs: PdfValidationLog[];
63
+ }
@@ -0,0 +1,11 @@
1
+ // The shapes of a veraPDF validation, without any code that loads the validator: the panel uses them too, and its
2
+ // bundle must not reach `@typfolio/verapdf-wasm`.
3
+ /** The flavours in the order to list them: the accessibility standards first. */
4
+ export const pdfValidationFlavourIds = ['ua1', 'ua2', '1a', '1b', '2a', '2b', '2u', '3a', '3b', '3u', '4', '4e', '4f', 'wt1a', 'wt1r'];
5
+ /** What each flavour is, for a choice shown to a person. */
6
+ export const pdfValidationFlavours = {
7
+ 'ua1': 'PDF/UA-1', 'ua2': 'PDF/UA-2',
8
+ '1a': 'PDF/A-1a', '1b': 'PDF/A-1b', '2a': 'PDF/A-2a', '2b': 'PDF/A-2b', '2u': 'PDF/A-2u', '3a': 'PDF/A-3a', '3b': 'PDF/A-3b', '3u': 'PDF/A-3u',
9
+ '4': 'PDF/A-4', '4e': 'PDF/A-4e', '4f': 'PDF/A-4f',
10
+ 'wt1a': 'WTPDF 1.0 Accessibility', 'wt1r': 'WTPDF 1.0 Reuse',
11
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typfolio/dev-tools",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Dev-time tools for Typfolio templates: schema-based template checks, PDF inspection and an in-page structure panel (install as a devDependency)",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -17,21 +17,28 @@
17
17
  "exports": {
18
18
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
19
19
  "./pdf": { "types": "./dist/pdf.d.ts", "import": "./dist/pdf.js" },
20
- "./panel": { "types": "./dist/panel.d.ts", "import": "./dist/panel.js" }
20
+ "./panel": { "types": "./dist/panel.d.ts", "import": "./dist/panel.js" },
21
+ "./validate": { "types": "./dist/validate.d.ts", "import": "./dist/validate.js" }
22
+ },
23
+ "bin": {
24
+ "typfolio-validate": "./dist/validate-cli.js"
21
25
  },
22
26
  "typesVersions": {
23
27
  "*": {
24
28
  "pdf": ["./dist/pdf.d.ts"],
25
- "panel": ["./dist/panel.d.ts"]
29
+ "panel": ["./dist/panel.d.ts"],
30
+ "validate": ["./dist/validate.d.ts"]
26
31
  }
27
32
  },
28
33
  "dependencies": {
29
34
  "@typfolio/core": "^0.5.0"
30
35
  },
31
36
  "peerDependencies": {
37
+ "@typfolio/verapdf-wasm": "^0.1.0",
32
38
  "pdfjs-dist": "^6.3.0"
33
39
  },
34
40
  "peerDependenciesMeta": {
41
+ "@typfolio/verapdf-wasm": { "optional": true },
35
42
  "pdfjs-dist": { "optional": true }
36
43
  },
37
44
  "publishConfig": {