|
| 1 | +/* |
| 2 | + * verapdf.ts |
| 3 | + * |
| 4 | + * Copyright (C) 2020-2022 Posit Software, PBC |
| 5 | + */ |
| 6 | + |
| 7 | +import { info, warning } from "../deno_ral/log.ts"; |
| 8 | +import { basename, join } from "../deno_ral/path.ts"; |
| 9 | +import * as colors from "fmt/colors"; |
| 10 | + |
| 11 | +import { execProcess } from "./process.ts"; |
| 12 | +import { which } from "./path.ts"; |
| 13 | +import { quartoDataDir } from "./appdirs.ts"; |
| 14 | +import { existsSync } from "../deno_ral/fs.ts"; |
| 15 | +import { isWindows } from "../deno_ral/platform.ts"; |
| 16 | + |
| 17 | +// verapdf flavours (profiles) supported for validation |
| 18 | +// Maps quarto pdf-standard values to verapdf --flavour values |
| 19 | +const kVerapdfFlavours: Record<string, string> = { |
| 20 | + // PDF/A standards |
| 21 | + "a-1a": "1a", |
| 22 | + "a-1b": "1b", |
| 23 | + "a-2a": "2a", |
| 24 | + "a-2b": "2b", |
| 25 | + "a-2u": "2u", |
| 26 | + "a-3a": "3a", |
| 27 | + "a-3b": "3b", |
| 28 | + "a-3u": "3u", |
| 29 | + "a-4": "4", |
| 30 | + "a-4e": "4e", |
| 31 | + "a-4f": "4f", |
| 32 | + // PDF/UA standards |
| 33 | + "ua-1": "ua1", |
| 34 | + "ua-2": "ua2", |
| 35 | +}; |
| 36 | + |
| 37 | +// Standards that verapdf can validate (keys of the above map) |
| 38 | +const kVerapdfSupportedStandards = new Set(Object.keys(kVerapdfFlavours)); |
| 39 | + |
| 40 | +/** |
| 41 | + * Check if a pdf-standard value can be validated by verapdf |
| 42 | + */ |
| 43 | +export function isVerapdfSupportedStandard(standard: string): boolean { |
| 44 | + const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, ""); |
| 45 | + return kVerapdfSupportedStandards.has(normalized); |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Get verapdf flavour for a pdf-standard value, or undefined if not supported |
| 50 | + */ |
| 51 | +export function getVerapdfFlavour(standard: string): string | undefined { |
| 52 | + const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, ""); |
| 53 | + return kVerapdfFlavours[normalized]; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Find verapdf binary path - checks PATH and quarto install location |
| 58 | + */ |
| 59 | +export async function findVerapdfPath(): Promise<string | undefined> { |
| 60 | + // First check PATH |
| 61 | + const pathResult = await which("verapdf"); |
| 62 | + if (pathResult) { |
| 63 | + return pathResult; |
| 64 | + } |
| 65 | + |
| 66 | + // Check quarto install location |
| 67 | + const quartoVerapdfDir = quartoDataDir("verapdf"); |
| 68 | + const quartoVerapdfBin = isWindows |
| 69 | + ? join(quartoVerapdfDir, "verapdf.bat") |
| 70 | + : join(quartoVerapdfDir, "verapdf"); |
| 71 | + |
| 72 | + if (existsSync(quartoVerapdfBin)) { |
| 73 | + return quartoVerapdfBin; |
| 74 | + } |
| 75 | + |
| 76 | + return undefined; |
| 77 | +} |
| 78 | + |
| 79 | +export interface VerapdfValidationResult { |
| 80 | + valid: boolean; |
| 81 | + flavour: string; |
| 82 | + errors: string[]; |
| 83 | + output: string; |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * Run verapdf validation on a PDF file |
| 88 | + */ |
| 89 | +export async function validatePdf( |
| 90 | + pdfPath: string, |
| 91 | + flavour: string, |
| 92 | + quiet = false, |
| 93 | +): Promise<VerapdfValidationResult> { |
| 94 | + const verapdfPath = await findVerapdfPath(); |
| 95 | + if (!verapdfPath) { |
| 96 | + throw new Error("verapdf not found"); |
| 97 | + } |
| 98 | + |
| 99 | + if (!quiet) { |
| 100 | + info( |
| 101 | + `[verapdf]: Validating ${ |
| 102 | + basename(pdfPath) |
| 103 | + } against PDF/${flavour.toUpperCase()}...`, |
| 104 | + { newline: false }, |
| 105 | + ); |
| 106 | + } |
| 107 | + |
| 108 | + const result = await execProcess({ |
| 109 | + cmd: verapdfPath, |
| 110 | + args: ["-f", flavour, pdfPath], |
| 111 | + stdout: "piped", |
| 112 | + stderr: "piped", |
| 113 | + }); |
| 114 | + |
| 115 | + const output = result.stdout || ""; |
| 116 | + |
| 117 | + // Parse verapdf XML output to determine compliance |
| 118 | + // Look for isCompliant="true" in validationReport or compliant count in batchSummary |
| 119 | + const isCompliantMatch = output.match(/isCompliant="(true|false)"/); |
| 120 | + const batchSummaryMatch = output.match( |
| 121 | + /validationReports[^>]*compliant="(\d+)"[^>]*nonCompliant="(\d+)"/, |
| 122 | + ); |
| 123 | + |
| 124 | + let valid = false; |
| 125 | + if (isCompliantMatch) { |
| 126 | + valid = isCompliantMatch[1] === "true"; |
| 127 | + } else if (batchSummaryMatch) { |
| 128 | + const compliant = parseInt(batchSummaryMatch[1]); |
| 129 | + const nonCompliant = parseInt(batchSummaryMatch[2]); |
| 130 | + valid = nonCompliant === 0 && compliant > 0; |
| 131 | + } else { |
| 132 | + // Fallback: assume valid if exit code is 0 and no obvious failure indicators |
| 133 | + valid = result.success; |
| 134 | + } |
| 135 | + |
| 136 | + // Extract error messages from output when validation fails |
| 137 | + const errors: string[] = []; |
| 138 | + if (!valid) { |
| 139 | + // Look for failed rules with descriptions |
| 140 | + // Pattern: <rule ...><description>...</description> |
| 141 | + const ruleDescMatches = output.matchAll( |
| 142 | + /<rule[^>]*>[\s\S]*?<description>([^<]+)<\/description>/g, |
| 143 | + ); |
| 144 | + for (const match of ruleDescMatches) { |
| 145 | + const desc = match[1].trim(); |
| 146 | + if (desc && !errors.includes(desc)) { |
| 147 | + errors.push(desc); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // Also look for clause violations in ruleId |
| 152 | + if (errors.length === 0) { |
| 153 | + const clauseMatches = output.matchAll( |
| 154 | + /<ruleId[^>]*clause="([^"]*)"[^>]*specification="([^"]*)"/g, |
| 155 | + ); |
| 156 | + for (const match of clauseMatches) { |
| 157 | + errors.push(`${match[2]} clause ${match[1]} violation`); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + // Extract failedChecks count for summary |
| 162 | + const failedChecksMatch = output.match(/failedChecks="(\d+)"/); |
| 163 | + if (failedChecksMatch && parseInt(failedChecksMatch[1]) > 0) { |
| 164 | + const count = failedChecksMatch[1]; |
| 165 | + if (errors.length === 0) { |
| 166 | + errors.push(`${count} compliance check(s) failed`); |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + if (!quiet) { |
| 172 | + if (valid) { |
| 173 | + info(colors.green("PASSED\n")); |
| 174 | + } else { |
| 175 | + info(colors.red("FAILED\n")); |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + return { |
| 180 | + valid, |
| 181 | + flavour, |
| 182 | + errors, |
| 183 | + output, |
| 184 | + }; |
| 185 | +} |
| 186 | + |
| 187 | +export interface PdfValidationOptions { |
| 188 | + quiet?: boolean; |
| 189 | + warnOnMissingVerapdf?: boolean; |
| 190 | +} |
| 191 | + |
| 192 | +/** |
| 193 | + * Validate a PDF against specified standards using verapdf |
| 194 | + * Returns true if all validations pass (or if no validatable standards specified) |
| 195 | + */ |
| 196 | +export async function validatePdfStandards( |
| 197 | + pdfPath: string, |
| 198 | + standards: string[], |
| 199 | + options: PdfValidationOptions = {}, |
| 200 | +): Promise<boolean> { |
| 201 | + const quiet = options.quiet ?? false; |
| 202 | + const warnOnMissingVerapdf = options.warnOnMissingVerapdf ?? true; |
| 203 | + |
| 204 | + // Filter to standards that verapdf can validate |
| 205 | + const validatableStandards: { standard: string; flavour: string }[] = []; |
| 206 | + const nonValidatableStandards: string[] = []; |
| 207 | + |
| 208 | + for (const standard of standards) { |
| 209 | + const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, ""); |
| 210 | + // Skip version numbers (1.4, 1.5, etc.) |
| 211 | + if (/^\d+\.\d+$/.test(normalized)) { |
| 212 | + continue; |
| 213 | + } |
| 214 | + const flavour = getVerapdfFlavour(normalized); |
| 215 | + if (flavour) { |
| 216 | + validatableStandards.push({ standard: normalized, flavour }); |
| 217 | + } else { |
| 218 | + nonValidatableStandards.push(standard); |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | + // Nothing to validate |
| 223 | + if (validatableStandards.length === 0) { |
| 224 | + return true; |
| 225 | + } |
| 226 | + |
| 227 | + // Check if verapdf is available |
| 228 | + const verapdfPath = await findVerapdfPath(); |
| 229 | + if (!verapdfPath) { |
| 230 | + if (warnOnMissingVerapdf) { |
| 231 | + warning( |
| 232 | + `PDF standard validation requested but verapdf is not installed.\n` + |
| 233 | + `Install with: quarto install verapdf\n` + |
| 234 | + `Standards requested: ${ |
| 235 | + validatableStandards.map((s) => s.standard).join(", ") |
| 236 | + }`, |
| 237 | + ); |
| 238 | + } |
| 239 | + return true; // Don't fail the build, just warn |
| 240 | + } |
| 241 | + |
| 242 | + // Warn about standards we can't validate |
| 243 | + if (nonValidatableStandards.length > 0) { |
| 244 | + warning( |
| 245 | + `The following PDF standards cannot be validated by verapdf and will be skipped: ` + |
| 246 | + nonValidatableStandards.join(", "), |
| 247 | + ); |
| 248 | + } |
| 249 | + |
| 250 | + // Run validation for each standard |
| 251 | + let allValid = true; |
| 252 | + for (const { standard, flavour } of validatableStandards) { |
| 253 | + try { |
| 254 | + const result = await validatePdf(pdfPath, flavour, quiet); |
| 255 | + if (!result.valid) { |
| 256 | + allValid = false; |
| 257 | + if (!quiet) { |
| 258 | + warning( |
| 259 | + `PDF validation failed for ${standard}:\n` + |
| 260 | + (result.errors.length > 0 |
| 261 | + ? result.errors.slice(0, 5).join("\n") |
| 262 | + : "See verapdf output for details"), |
| 263 | + ); |
| 264 | + } |
| 265 | + } |
| 266 | + } catch (error) { |
| 267 | + if (!quiet) { |
| 268 | + warning(`Failed to run verapdf validation: ${error}`); |
| 269 | + } |
| 270 | + } |
| 271 | + } |
| 272 | + |
| 273 | + return allValid; |
| 274 | +} |
0 commit comments