@projektemacher/vivliostyle-batch-cli 0.2.0 → 0.3.1

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.
@@ -1,5 +1,5 @@
1
1
  import { Command } from 'commander';
2
- import { resolve, join, dirname, posix, relative, isAbsolute, sep, basename } from 'node:path';
2
+ import { resolve, join, dirname, posix, basename, relative, isAbsolute, sep } from 'node:path';
3
3
  import { readFileSync, statSync, existsSync, readdirSync, mkdirSync, writeFileSync, realpathSync, mkdtempSync, rmSync } from 'node:fs';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { platform, homedir, tmpdir } from 'node:os';
@@ -9,6 +9,9 @@ import { createServer } from 'node:http';
9
9
  import { lookup } from 'mime-types';
10
10
  import puppeteer from 'puppeteer-core';
11
11
  import { PDFDocument } from 'pdf-lib';
12
+ import { randomUUID, randomBytes } from 'node:crypto';
13
+ import * as mupdf from 'mupdf';
14
+ import { spawnSync } from 'node:child_process';
12
15
  import { createRequire } from 'node:module';
13
16
 
14
17
  // src/server.ts
@@ -141,7 +144,19 @@ async function startStaticServer(options = {}, port = 0) {
141
144
  return false;
142
145
  if (urlPath === SETTLE_READY_PATH) {
143
146
  const detail = {};
144
- for (const key of ["reason", "ms", "pending", "frames", "canvases", "containers", "mutations", "dpr", "painted", "ready"]) {
147
+ for (const key of [
148
+ "reason",
149
+ "ms",
150
+ "pending",
151
+ "frames",
152
+ "canvases",
153
+ "containers",
154
+ "mutations",
155
+ "dpr",
156
+ "painted",
157
+ "ready",
158
+ "longtasks"
159
+ ]) {
145
160
  const value = query.get(key);
146
161
  if (value === null)
147
162
  continue;
@@ -172,6 +187,11 @@ async function startStaticServer(options = {}, port = 0) {
172
187
  const handler = (req, res) => {
173
188
  const urlPath = decodeRequestPath(req);
174
189
  const query = new URLSearchParams((req.url ?? "").split("?")[1] ?? "");
190
+ // Every request the page makes transits here: log it (path + status) so
191
+ // render problems become traceable from the per-page logs.
192
+ res.on("finish", () => {
193
+ log(`${urlPath} ${res.statusCode}`);
194
+ });
175
195
  if (handleSettle(urlPath, query, res))
176
196
  return;
177
197
  // The viewer page lives next to the document so that scripts the page runs
@@ -317,6 +337,652 @@ function chromeArgs(extra = []) {
317
337
  ];
318
338
  }
319
339
 
340
+ // src/render/xmp.ts
341
+ const NS = {
342
+ rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
343
+ dc: "http://purl.org/dc/elements/1.1/",
344
+ pdf: "http://ns.adobe.com/pdf/1.3/",
345
+ xmp: "http://ns.adobe.com/xap/1.0/",
346
+ xmpMM: "http://ns.adobe.com/xap/1.0/mm/",
347
+ pdfaid: "http://www.aiim.org/pdfa/ns/id/",
348
+ pdfxid: "http://www.npes.org/pdfx/ns/id/"
349
+ };
350
+ /** XMP Specification Part 1 (April 2012), 8.2.1.2 date form. */
351
+ function toXmpDate(date) {
352
+ const pad = (value, length = 2) => String(value).padStart(length, "0");
353
+ return (`${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}` +
354
+ `T${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}Z`);
355
+ }
356
+ // ISO 32000-1:2008, 7.9.4 writes a date as D:YYYYMMDDHHmmSSOHH'mm, the form
357
+ // Skia in Chromium writes. The offset is kept, not normalized to UTC, so the
358
+ // XMP packet shows the same instant the information dictionary shows.
359
+ const PDF_DATE = /^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:Z|([+\-])(\d{2})'(\d{2})'?)$/;
360
+ /** Reformats a PDF date string as an XMP date; `undefined` when not one. */
361
+ function pdfDateToXmpDate(value) {
362
+ const match = PDF_DATE.exec(value);
363
+ if (match === null)
364
+ return undefined;
365
+ const [, year, month, day, hour, minute, second, sign, offsetHour, offsetMinute] = match;
366
+ const zone = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
367
+ return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
368
+ }
369
+ // The inverse of the PDF date form above: XMP Part 1, 8.2.1.2 date.
370
+ const XMP_DATE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+\-]\d{2}:\d{2})$/;
371
+ /** Reformats an XMP date string as a PDF date; `undefined` when not one. */
372
+ function xmpDateToPdfDate(value) {
373
+ const match = XMP_DATE.exec(value);
374
+ if (match === null)
375
+ return undefined;
376
+ const [, year, month, day, hour, minute, second, zone] = match;
377
+ const offset = zone === "Z" ? "Z" : `${zone.slice(0, 3)}'${zone.slice(4, 6)}`;
378
+ return `D:${year}${month}${day}${hour}${minute}${second}${offset}`;
379
+ }
380
+ function xmlEscape(text) {
381
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
382
+ }
383
+ /** dc:title/dc:description: a language alternative with the x-default entry. */
384
+ function languageAlternative(text) {
385
+ return ["<rdf:Alt>", ` <rdf:li xml:lang="x-default">${xmlEscape(text)}</rdf:li>`, "</rdf:Alt>"].join("\n ");
386
+ }
387
+ /** dc:creator: an ordered sequence; ";" separates individual authors. */
388
+ function creatorSequence(author) {
389
+ const names = author
390
+ .split(";")
391
+ .map((name) => name.trim())
392
+ .filter((name) => name !== "");
393
+ const items = (names.length === 0 ? [author] : names).map((name) => ` <rdf:li>${xmlEscape(name)}</rdf:li>`);
394
+ return ["<rdf:Seq>", ...items, "</rdf:Seq>"].join("\n ");
395
+ }
396
+ /**
397
+ * Builds the XMP packet for the document. Only defined fields are written;
398
+ * the packet wrapper uses the fixed header id packet scanners look for
399
+ * (XMP Part 1, 7.3.2 makes the wrapper optional, Acrobat rejects its absence).
400
+ */
401
+ function buildXmpPacket(fields, label) {
402
+ const properties = [];
403
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-4") {
404
+ properties.push(`<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>`);
405
+ }
406
+ if (fields.title !== undefined) {
407
+ properties.push(`<dc:title>\n ${languageAlternative(fields.title)}\n </dc:title>`);
408
+ }
409
+ if (fields.author !== undefined) {
410
+ properties.push(`<dc:creator>\n ${creatorSequence(fields.author)}\n </dc:creator>`);
411
+ }
412
+ if (fields.subject !== undefined) {
413
+ properties.push(`<dc:description>\n ${languageAlternative(fields.subject)}\n </dc:description>`);
414
+ }
415
+ if (fields.keywords !== undefined) {
416
+ properties.push(`<pdf:Keywords>${xmlEscape(fields.keywords)}</pdf:Keywords>`);
417
+ }
418
+ if (fields.producer !== undefined) {
419
+ properties.push(`<pdf:Producer>${xmlEscape(fields.producer)}</pdf:Producer>`);
420
+ }
421
+ if (fields.trapped !== undefined) {
422
+ properties.push(`<pdf:Trapped>${fields.trapped}</pdf:Trapped>`);
423
+ }
424
+ if (fields.creatorTool !== undefined) {
425
+ properties.push(`<xmp:CreatorTool>${xmlEscape(fields.creatorTool)}</xmp:CreatorTool>`);
426
+ }
427
+ if (fields.createDate !== undefined) {
428
+ properties.push(`<xmp:CreateDate>${fields.createDate}</xmp:CreateDate>`);
429
+ }
430
+ if (fields.modifyDate !== undefined) {
431
+ properties.push(`<xmp:ModifyDate>${fields.modifyDate}</xmp:ModifyDate>`);
432
+ }
433
+ if (fields.metadataDate !== undefined) {
434
+ properties.push(`<xmp:MetadataDate>${fields.metadataDate}</xmp:MetadataDate>`);
435
+ }
436
+ if (fields.documentId !== undefined) {
437
+ properties.push(`<xmpMM:DocumentID>${xmlEscape(fields.documentId)}</xmpMM:DocumentID>`, `<xmpMM:VersionID>1</xmpMM:VersionID>`, `<xmpMM:RenditionClass>default</xmpMM:RenditionClass>`);
438
+ }
439
+ if (label !== undefined && label.kind === "pdfa") {
440
+ properties.push(`<pdfaid:part>${label.part}</pdfaid:part>`);
441
+ // PDF/A-4 (ISO 19005-4) identifies through the part value alone; the
442
+ // conformance levels a/b/u exist for parts 1 to 3 only.
443
+ if (label.part !== "4" && label.conformance !== undefined) {
444
+ properties.push(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`);
445
+ }
446
+ }
447
+ const body = [
448
+ `<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>`,
449
+ `<x:xmpmeta xmlns:x="adobe:ns:meta/">`,
450
+ ` <rdf:RDF xmlns:rdf="${NS.rdf}">`,
451
+ ` <rdf:Description rdf:about="" xmlns:dc="${NS.dc}" xmlns:pdf="${NS.pdf}" xmlns:xmp="${NS.xmp}" xmlns:xmpMM="${NS.xmpMM}" xmlns:pdfaid="${NS.pdfaid}" xmlns:pdfxid="${NS.pdfxid}">`,
452
+ ...properties.map((property) => ` ${property}`),
453
+ ` </rdf:Description>`,
454
+ ` </rdf:RDF>`,
455
+ `</x:xmpmeta>`,
456
+ `<?xpacket end="w"?>`
457
+ ].join("\n");
458
+ // XML 1.0 (Fifth Edition), 2.11: a processor turns a literal CR into LF
459
+ // before parsing, so a CR in a value survives only as a character reference.
460
+ return `${body.replaceAll("\r", "&#xD;")}\n`;
461
+ }
462
+
463
+ // src/render/pdf-postprocess.ts
464
+ // Copyright (c) 2026 Christian Mahnke
465
+ // Licensed under the MIT License.
466
+ /**
467
+ * PDF post-processing: document metadata, XMP and standards labeling.
468
+ *
469
+ * Runs on the PDF bytes Chrome printed (Skia output) and applies:
470
+ * - document information entries (title, author, subject, keywords, producer, creator)
471
+ * - the catalog /Lang entry for the document language
472
+ * - an XMP metadata stream kept consistent with the information dictionary
473
+ * - PDF/A or PDF/X identification: XMP identification properties, an
474
+ * OutputIntent with an embedded ICC profile and a stable file identifier
475
+ *
476
+ * This is a "label, don't convert" step — the same semantics vivliostyle-cli
477
+ * gives its PDF/X option: the content is neither converted nor checked, so
478
+ * conformance of the content is the author's responsibility. Verify with
479
+ * veraPDF (or a print provider's preflight) when it matters.
480
+ *
481
+ * The editing follows vivliostyle-cli's mupdf-based post-processing
482
+ * (src/output/pdfx.ts, pdf-document.ts, pdf-version.ts at v11.4).
483
+ */
484
+ /**
485
+ * Tracks MuPDF's native objects and destroys them in reverse order. Every
486
+ * PDFObject/Buffer/ColorSpace keeps native memory behind the wasm binding,
487
+ * which is only reclaimed on an explicit destroy.
488
+ */
489
+ function createScope() {
490
+ const tracked = [];
491
+ return {
492
+ track(value) {
493
+ tracked.push(value);
494
+ return value;
495
+ },
496
+ dispose() {
497
+ while (tracked.length > 0) {
498
+ try {
499
+ tracked.pop()?.destroy();
500
+ }
501
+ catch {
502
+ // Cleanup is best-effort; a failed destroy must not mask the result.
503
+ }
504
+ }
505
+ }
506
+ };
507
+ }
508
+ /**
509
+ * The PDF version each standards label is defined against: PDF/A-1 and
510
+ * PDF/X-1a:2003 on PDF 1.4, PDF/X-4 on PDF 1.6, PDF/A-2 and PDF/A-3 on
511
+ * PDF 1.7 (ISO 32000-1) and PDF/A-4 on PDF 2.0 (ISO 32000-2).
512
+ */
513
+ function minimumVersionForLabel(label) {
514
+ if (label.kind === "pdfa") {
515
+ if (label.part === "1")
516
+ return 14;
517
+ if (label.part === "4")
518
+ return 20;
519
+ return 17;
520
+ }
521
+ return label.version === "X-4" ? 16 : 14;
522
+ }
523
+ // The catalog /Version is written for every required version; MuPDF's wasm
524
+ // binding provides no API for the header version and a full save derives the
525
+ // header from the catalog entry (same approach as vivliostyle-cli).
526
+ function setMinimumPdfVersion(document, minimumVersion, scope) {
527
+ if (document.getVersion() >= minimumVersion)
528
+ return;
529
+ const trailer = scope.track(document.getTrailer());
530
+ const catalog = scope.track(trailer.get("Root"));
531
+ const version = scope.track(document.newName(`${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`));
532
+ catalog.put("Version", version);
533
+ }
534
+ function readInfoString(info, key, scope) {
535
+ const value = scope.track(info.get(key));
536
+ return value.isString() ? value.asString() : undefined;
537
+ }
538
+ /**
539
+ * Parses an explicitly given date (ISO 8601, optionally date-only, or the PDF
540
+ * "D:…" form) into both formats the document needs: the information
541
+ * dictionary date (ISO 32000-1:2008, 7.9.4) and the XMP date (XMP Part 1,
542
+ * 8.2.1.2). A date without offset counts as UTC.
543
+ */
544
+ function parseExplicitDate(value, field) {
545
+ const trimmed = value.trim();
546
+ const pdfFromXmp = xmpDateToPdfDate(trimmed);
547
+ if (pdfFromXmp !== undefined)
548
+ return { pdfDate: pdfFromXmp, xmpDate: trimmed };
549
+ const xmpFromPdf = pdfDateToXmpDate(trimmed);
550
+ if (xmpFromPdf !== undefined)
551
+ return { pdfDate: trimmed, xmpDate: xmpFromPdf };
552
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2}))?)?(?:[Zz]|([+\-])(\d{2}):?(\d{2}))?$/.exec(trimmed);
553
+ if (match === null) {
554
+ throw new Error(`Invalid ${field} date: "${value}". Use ISO 8601, e.g. 2024-11-18T00:00:00+01:00`);
555
+ }
556
+ const [, year, month, day, hour = "00", minute = "00", second = "00", sign, offsetHour, offsetMinute] = match;
557
+ const offset = sign === undefined ? "Z" : `${sign}${offsetHour}'${offsetMinute}`;
558
+ const xmpOffset = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
559
+ return {
560
+ pdfDate: `D:${year}${month}${day}${hour}${minute}${second}${offset}`,
561
+ xmpDate: `${year}-${month}-${day}T${hour}:${minute}:${second}${xmpOffset}`
562
+ };
563
+ }
564
+ function readTrapped(info, scope) {
565
+ const trapped = scope.track(info.get("Trapped"));
566
+ return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
567
+ }
568
+ function openPdfDocument(pdf, scope) {
569
+ // openDocument returns the Document base type; a PDF input yields a PDFDocument.
570
+ const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf");
571
+ return scope.track(document);
572
+ }
573
+ /**
574
+ * Runs `fn` with freshly fetched catalog handles. MuPDF replaces the trailer
575
+ * dict whenever an information entry is written through `setMetaData`, and a
576
+ * PDFObject handle held across such a write ends up detached from the
577
+ * document — edits into it silently disappear on save. Every mutation
578
+ * therefore re-fetches its handles right before it runs.
579
+ */
580
+ function withCatalog(document, scope, fn) {
581
+ const trailer = scope.track(document.getTrailer());
582
+ const catalog = scope.track(trailer.get("Root"));
583
+ return fn(catalog);
584
+ }
585
+ /** Runs `fn` with a freshly fetched information dictionary handle. */
586
+ function withInfo(document, scope, fn) {
587
+ const trailer = scope.track(document.getTrailer());
588
+ const info = scope.track(trailer.get("Info"));
589
+ return fn(info);
590
+ }
591
+ /** Runs `fn` with a freshly fetched trailer handle. */
592
+ function withTrailer(document, scope, fn) {
593
+ return fn(scope.track(document.getTrailer()));
594
+ }
595
+ /**
596
+ * Applies metadata and standards labeling to a printed PDF.
597
+ *
598
+ * Producer/Creator are always stamped (the wrapper owns them), so a build
599
+ * without explicit metadata still gets a consistent information dictionary
600
+ * and XMP packet. Dates come from what Skia wrote: CreationDate is kept,
601
+ * ModifyDate falls back to it, exactly like vivliostyle-cli handles output
602
+ * from print backends that skip the modification date.
603
+ */
604
+ async function postProcessPdf(pdf, options) {
605
+ const scope = createScope();
606
+ try {
607
+ const { metadata, label } = options;
608
+ const document = openPdfDocument(pdf, scope);
609
+ // ── What the print backend already wrote ────────────────────────────────
610
+ const { creationDate, modifyDate, trapped } = withInfo(document, scope, (info) => ({
611
+ creationDate: readInfoString(info, "CreationDate", scope),
612
+ modifyDate: readInfoString(info, "ModDate", scope),
613
+ trapped: readTrapped(info, scope)
614
+ }));
615
+ let infoCreationDate = creationDate;
616
+ let infoModifyDate = modifyDate;
617
+ let createDateXmp = creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined;
618
+ let modifyDateXmp = modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined;
619
+ if (metadata.created !== undefined) {
620
+ const parsed = parseExplicitDate(metadata.created, "--created");
621
+ infoCreationDate = parsed.pdfDate;
622
+ createDateXmp = parsed.xmpDate;
623
+ }
624
+ if (metadata.modified !== undefined) {
625
+ const parsed = parseExplicitDate(metadata.modified, "--modified");
626
+ infoModifyDate = parsed.pdfDate;
627
+ modifyDateXmp = parsed.xmpDate;
628
+ }
629
+ // Acrobat's preflight requires xmp:CreateDate/MetadataDate and, with
630
+ // ModifyDate absent (as with backends like Firefox's cairo), falls back to
631
+ // the creation date — so both dates are always present in the XMP packet.
632
+ createDateXmp ??= toXmpDate(new Date());
633
+ modifyDateXmp ??= createDateXmp;
634
+ // ── Document information entries ────────────────────────────────────────
635
+ document.setMetaData("info:Producer", metadata.producer);
636
+ document.setMetaData("info:Creator", metadata.creator);
637
+ if (metadata.title !== undefined)
638
+ document.setMetaData("info:Title", metadata.title);
639
+ if (metadata.author !== undefined)
640
+ document.setMetaData("info:Author", metadata.author);
641
+ if (metadata.subject !== undefined)
642
+ document.setMetaData("info:Subject", metadata.subject);
643
+ if (metadata.keywords !== undefined)
644
+ document.setMetaData("info:Keywords", metadata.keywords);
645
+ // Explicit dates override the ones the print backend wrote (setMetaData
646
+ // replaces the information dictionary, so these run after the entries
647
+ // above and every later access re-fetches its handles).
648
+ if (infoCreationDate !== undefined && infoCreationDate !== creationDate) {
649
+ document.setMetaData("info:CreationDate", infoCreationDate);
650
+ }
651
+ if (infoModifyDate !== undefined && infoModifyDate !== modifyDate) {
652
+ document.setMetaData("info:ModDate", infoModifyDate);
653
+ }
654
+ // ── Catalog language ────────────────────────────────────────────────────
655
+ const language = metadata.language;
656
+ if (language !== undefined && language !== "") {
657
+ withCatalog(document, scope, (catalog) => {
658
+ catalog.put("Lang", scope.track(document.newString(language)));
659
+ });
660
+ setMinimumPdfVersion(document, 14, scope);
661
+ }
662
+ // ── XMP metadata stream ─────────────────────────────────────────────────
663
+ const xmp = buildXmpPacket({
664
+ title: metadata.title,
665
+ author: metadata.author,
666
+ subject: metadata.subject,
667
+ keywords: metadata.keywords,
668
+ producer: metadata.producer,
669
+ creatorTool: metadata.creator,
670
+ createDate: createDateXmp,
671
+ modifyDate: modifyDateXmp,
672
+ metadataDate: toXmpDate(new Date()),
673
+ documentId: `uuid:${randomUUID()}`,
674
+ ...(label !== undefined && label.kind === "pdfx" && label.version === "X-4" ? { trapped } : {})
675
+ }, label);
676
+ withCatalog(document, scope, (catalog) => {
677
+ const xmpBuffer = scope.track(new mupdf.Buffer(xmp));
678
+ const metadataStream = scope.track(document.addStream(xmpBuffer, { Type: "Metadata", Subtype: "XML" }));
679
+ catalog.put("Metadata", metadataStream);
680
+ });
681
+ // ── OutputIntent with the embedded ICC profile ──────────────────────────
682
+ if (label !== undefined) {
683
+ const profile = options.iccProfile;
684
+ if (profile === undefined) {
685
+ throw new Error(label.kind === "pdfx"
686
+ ? "PDF/X labeling requires an ICC profile for the OutputIntent (--icc-profile)."
687
+ : "PDF/A labeling requires an ICC profile for the OutputIntent.");
688
+ }
689
+ const profileName = options.iccProfileName ?? "output-intent.icc";
690
+ withCatalog(document, scope, (catalog) => {
691
+ const profileBuffer = scope.track(new mupdf.Buffer(profile));
692
+ const colorSpace = scope.track(new mupdf.ColorSpace(profileBuffer, profileName));
693
+ const profileStream = scope.track(document.addStream(profileBuffer, { N: colorSpace.getNumberOfComponents() }));
694
+ const identifier = scope.track(document.newString("Custom"));
695
+ const profileInfo = scope.track(document.newString(profileName));
696
+ // ISO 32000-1:2008, 7.7.2/14.11.5: OutputConditionIdentifier may be
697
+ // "Custom"; Info and DestOutputProfile are required for nonstandard
698
+ // production conditions.
699
+ const intent = scope.track(document.addObject({
700
+ Type: "OutputIntent",
701
+ S: label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX",
702
+ OutputConditionIdentifier: identifier,
703
+ Info: profileInfo,
704
+ DestOutputProfile: profileStream
705
+ }));
706
+ catalog.put("OutputIntents", [intent]);
707
+ });
708
+ setMinimumPdfVersion(document, minimumVersionForLabel(label), scope);
709
+ }
710
+ // ── Standards identification outside the XMP packet ─────────────────────
711
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
712
+ // PDF/X-1a:2003 identification lives in the information dictionary, not
713
+ // in XMP (XMP identification is the PDF/X-4 form).
714
+ document.setMetaData("info:GTS_PDFXVersion", "PDF/X-1a:2003");
715
+ withInfo(document, scope, (info) => {
716
+ info.put("Trapped", scope.track(document.newName(trapped)));
717
+ // Acrobat's PDF/X-1a:2003 preflight requires ModDate, which some print
718
+ // backends never write; it takes the creation date then.
719
+ if (modifyDate === undefined && creationDate !== undefined) {
720
+ info.put("ModDate", scope.track(document.newString(creationDate)));
721
+ }
722
+ });
723
+ }
724
+ // A stable file identifier is required for PDF/A and PDF/X. Written last,
725
+ // against a trailer handle fetched after every information entry write.
726
+ if (label !== undefined) {
727
+ withTrailer(document, scope, (trailer) => {
728
+ const existingId = scope.track(trailer.get("ID"));
729
+ if (!existingId.isArray()) {
730
+ const bytes = randomBytes(16);
731
+ trailer.put("ID", [document.newByteString(bytes), document.newByteString(bytes)]);
732
+ }
733
+ });
734
+ }
735
+ if (!document.hasUnsavedChanges())
736
+ return pdf;
737
+ const output = scope.track(document.saveToBuffer("compress"));
738
+ // Copy so the data stays valid after the buffer is destroyed.
739
+ return new Uint8Array(output.asUint8Array());
740
+ }
741
+ finally {
742
+ scope.dispose();
743
+ }
744
+ }
745
+ /**
746
+ * Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
747
+ *
748
+ * The profile ships unchanged from Debian's icc-profiles-free package
749
+ * (sources.debian.org, sRGB.icc from the "sRGB IEC61966-2.1" distribution by
750
+ * Hewlett-Packard): a monitor-class ("mntr") RGB profile with the embedded
751
+ * copyright tag, as PDF/A requires (ISO 19005-2, 6.2.3: an OutputIntent
752
+ * profile must be of the output or monitor device class and older than
753
+ * ICC v5). The ICC/HP license permits redistribution provided the file,
754
+ * including its embedded copyright notice tag, is not modified
755
+ * (https://registry.color.org/profile-library/#license).
756
+ */
757
+ function loadDefaultIccProfile() {
758
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
759
+ const candidates = [
760
+ // Source layout (vitest, direct TS execution).
761
+ join(moduleDir, "srgb.icc"),
762
+ // Bundled layout: dist/vivliostyle-batch-cli.js ships next to src/.
763
+ resolve(moduleDir, "../src/render/srgb.icc")
764
+ ];
765
+ for (const candidate of candidates) {
766
+ if (existsSync(candidate)) {
767
+ return { bytes: readFileSync(candidate), name: "sRGB IEC61966-2.1" };
768
+ }
769
+ }
770
+ throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
771
+ }
772
+
773
+ // src/render/pdf-validate.ts
774
+ // Copyright (c) 2026 Christian Mahnke
775
+ // Licensed under the MIT License.
776
+ /**
777
+ * Built-in compliance checks for standards-labeled output (PDF/A, PDF/X).
778
+ *
779
+ * veraPDF implements the full ISO rule sets; this module covers the practical
780
+ * subset a print backend can violate and that the post-processing step is
781
+ * responsible for: the PDF version of the labeled part, the XMP
782
+ * identification, the OutputIntent with an embedded ICC profile, the file
783
+ * identifier, embedded fonts and the absence of JavaScript actions.
784
+ * Run the verapdf binary (see verapdf.ts) when the full rule set matters.
785
+ */
786
+ /** Human-readable label, e.g. "PDF/A-2b" or "PDF/X-4". */
787
+ function describeLabel(label) {
788
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
789
+ }
790
+ const decoder = new TextDecoder("utf-8");
791
+ function decodeStream(stream) {
792
+ return decoder.decode(stream.readStream().asUint8Array());
793
+ }
794
+ /** True when the font dictionary carries one of the embedded font file keys. */
795
+ function hasEmbeddedFontFile(fontDescriptor) {
796
+ for (const key of ["FontFile", "FontFile2", "FontFile3"]) {
797
+ if (fontDescriptor.get(key).isStream())
798
+ return true;
799
+ }
800
+ return false;
801
+ }
802
+ /** Checks a single font dictionary; returns a violation detail or null. */
803
+ function checkFont(font) {
804
+ const subtype = font.get("Subtype").asName();
805
+ if (subtype === "Type3") {
806
+ // PDF/A (parts 1-3) requires the character procedures of a Type3 font to
807
+ // be embedded streams; PDF/A-4 additionally allows them in the page.
808
+ return font.get("CharProcs").isDictionary() || font.get("CharProcs").isStream() ? null : "Type3 font without CharProcs";
809
+ }
810
+ let descriptor = font.get("FontDescriptor");
811
+ if (subtype === "Type0") {
812
+ const descendants = font.get("DescendantFonts");
813
+ if (!descendants.isArray())
814
+ return "Type0 font without DescendantFonts";
815
+ descriptor = descendants.get(0).resolve().get("FontDescriptor");
816
+ }
817
+ else if (subtype === "CIDFontType0" || subtype === "CIDFontType2") {
818
+ descriptor = font.get("FontDescriptor");
819
+ }
820
+ if (!descriptor.isDictionary())
821
+ return `${subtype} font without FontDescriptor`;
822
+ if (!hasEmbeddedFontFile(descriptor))
823
+ return `${subtype} font without embedded FontFile`;
824
+ return null;
825
+ }
826
+ function validateLabeledPdf(pdf, label) {
827
+ const violations = [];
828
+ const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf");
829
+ try {
830
+ const trailer = document.getTrailer();
831
+ const catalog = trailer.get("Root");
832
+ // ── PDF version of the labeled part ───────────────────────────────────
833
+ const minimumVersion = minimumVersionForLabel(label);
834
+ if (document.getVersion() < minimumVersion) {
835
+ violations.push({
836
+ check: "pdf-version",
837
+ detail: `document is PDF ${Math.trunc(document.getVersion() / 10)}.${document.getVersion() % 10}, ${describeLabel(label)} requires at least ${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`
838
+ });
839
+ }
840
+ // ── XMP metadata stream with the standards identification ─────────────
841
+ // get() follows indirect references already; resolve() would hide the
842
+ // stream-ness of the handle (see the post-processing test comment).
843
+ const metadataStream = catalog.get("Metadata");
844
+ let xmp = "";
845
+ if (!metadataStream.isStream()) {
846
+ violations.push({ check: "xmp-metadata", detail: "catalog has no Metadata stream" });
847
+ }
848
+ else {
849
+ xmp = decodeStream(metadataStream);
850
+ if (label.kind === "pdfa") {
851
+ if (!xmp.includes(`<pdfaid:part>${label.part}</pdfaid:part>`)) {
852
+ violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:part>${label.part}` });
853
+ }
854
+ if (label.conformance !== undefined &&
855
+ !xmp.includes(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`)) {
856
+ violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:conformance>${label.conformance.toUpperCase()}` });
857
+ }
858
+ }
859
+ else if (label.version === "X-4" && !xmp.includes("<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>")) {
860
+ violations.push({ check: "xmp-identification", detail: "XMP is missing the PDF/X-4 GTS_PDFXVersion" });
861
+ }
862
+ }
863
+ // ── OutputIntent with an embedded ICC profile ──────────────────────────
864
+ if (label.kind === "pdfa" || label.version === "X-4") {
865
+ const intents = catalog.get("OutputIntents");
866
+ if (!intents.isArray() || intents.length < 1) {
867
+ violations.push({ check: "output-intent", detail: "catalog has no OutputIntents array" });
868
+ }
869
+ else {
870
+ const intent = intents.get(0);
871
+ const expectedS = label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX";
872
+ if (!intent.get("S").asName()?.startsWith(expectedS)) {
873
+ violations.push({ check: "output-intent", detail: `OutputIntent /S is not ${expectedS}` });
874
+ }
875
+ // MuPDF's PDFObject.resolve() does not surface stream-ness for
876
+ // indirect refs, so the embedded profile is checked through its
877
+ // stream data (same approach as the post-processing tests).
878
+ let profileReadable = false;
879
+ try {
880
+ profileReadable = intent.get("DestOutputProfile").readStream().asUint8Array().length > 0;
881
+ }
882
+ catch {
883
+ profileReadable = false;
884
+ }
885
+ if (!profileReadable) {
886
+ violations.push({ check: "output-intent", detail: "OutputIntent has no embedded DestOutputProfile" });
887
+ }
888
+ }
889
+ }
890
+ // ── File identifier (required for PDF/A and PDF/X) ──────────────────────
891
+ const fileId = trailer.get("ID");
892
+ if (!fileId.isArray() || fileId.length < 2) {
893
+ violations.push({ check: "file-identifier", detail: "trailer /ID pair missing" });
894
+ }
895
+ // ── Fonts embedded ──────────────────────────────────────────────────────
896
+ const pageCount = document.countPages();
897
+ for (let index = 0; index < pageCount; index++) {
898
+ const page = document.loadPage(index);
899
+ try {
900
+ const fonts = page.getObject().get("Resources").resolve().get("Font");
901
+ if (!fonts.isDictionary())
902
+ continue;
903
+ fonts.forEach((fontRef) => {
904
+ const font = fontRef.resolve();
905
+ if (!font.isDictionary())
906
+ return;
907
+ const failure = checkFont(font);
908
+ if (failure !== null)
909
+ violations.push({ check: "font-embedded", detail: `page ${index + 1}: ${failure}` });
910
+ });
911
+ }
912
+ finally {
913
+ page.destroy();
914
+ }
915
+ }
916
+ // ── No JavaScript actions ────────────────────────────────────────────────
917
+ const names = catalog.get("Names");
918
+ if (names.isDictionary() && names.get("JavaScript").isDictionary()) {
919
+ violations.push({ check: "no-javascript", detail: "document name tree contains JavaScript actions" });
920
+ }
921
+ const openAction = catalog.get("OpenAction");
922
+ if (openAction.isDictionary() && openAction.get("S").asName() === "JavaScript") {
923
+ violations.push({ check: "no-javascript", detail: "OpenAction is a JavaScript action" });
924
+ }
925
+ // ── Information dictionary / XMP consistency ────────────────────────────
926
+ const info = trailer.get("Info");
927
+ if (info.isDictionary()) {
928
+ if (info.get("Title").isString() && xmp !== "" && !xmp.includes("<dc:title>")) {
929
+ violations.push({ check: "metadata-consistency", detail: "information dictionary has a Title but the XMP packet lacks dc:title" });
930
+ }
931
+ if (info.get("Author").isString() && xmp !== "" && !xmp.includes("<dc:creator>")) {
932
+ violations.push({
933
+ check: "metadata-consistency",
934
+ detail: "information dictionary has an Author but the XMP packet lacks dc:creator"
935
+ });
936
+ }
937
+ }
938
+ return violations;
939
+ }
940
+ finally {
941
+ document.destroy();
942
+ }
943
+ }
944
+
945
+ // src/render/verapdf.ts
946
+ // Copyright (c) 2026 Christian Mahnke
947
+ // Licensed under the MIT License.
948
+ /**
949
+ * Optional pass-through to the verapdf binary (https://verapdf.org/), which
950
+ * implements the full ISO conformance rule sets for PDF/A and PDF/X. The
951
+ * binary must be on the PATH; it is never bundled because it needs a Java
952
+ * runtime. Only invoked on explicit request (--verapdf).
953
+ */
954
+ /** Maps a standards label onto a veraPDF --flavour value. */
955
+ function veraPdfFlavour(label) {
956
+ if (label.kind === "pdfa") {
957
+ return label.part === "4" ? "4" : `${label.part}${label.conformance ?? ""}`;
958
+ }
959
+ return label.version === "X-4" ? "X-4" : "X-1a";
960
+ }
961
+ function runVeraPdf(pdfPath, label) {
962
+ const flavour = veraPdfFlavour(label);
963
+ let result;
964
+ try {
965
+ result = spawnSync("verapdf", ["--flavour", flavour, "--format", "text", pdfPath], {
966
+ encoding: "utf-8",
967
+ timeout: 120_000
968
+ });
969
+ }
970
+ catch (error) {
971
+ return { ran: false, reason: error instanceof Error ? error.message : String(error) };
972
+ }
973
+ if (result.error !== undefined) {
974
+ const code = result.error.code;
975
+ return {
976
+ ran: false,
977
+ reason: code === "ENOENT" ? "verapdf binary not found on PATH" : String(result.error)
978
+ };
979
+ }
980
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
981
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
982
+ const output = `${stdout}${stderr}`.slice(0, 4000);
983
+ return { ran: true, passed: /\bPASS\b/.test(stdout), exitCode: result.status, output };
984
+ }
985
+
320
986
  // src/render/pdf.ts
321
987
  // Copyright (c) 2026 Christian Mahnke
322
988
  // Licensed under the MIT License.
@@ -326,6 +992,10 @@ function chromeArgs(extra = []) {
326
992
  * The viewer page is served by our own static server (see src/server.ts), so
327
993
  * the document's origin — and therefore the base URI of the scripts the page
328
994
  * runs — is the site we serve, not an internal viewer base.
995
+ *
996
+ * Printed pages run through the post-processing step (see
997
+ * src/render/pdf-postprocess.ts), which stamps the document metadata and
998
+ * applies the requested PDF/A or PDF/X labeling.
329
999
  */
330
1000
  /** URL of the viewer page, with the publication and layout parameters. */
331
1001
  function buildViewerUrl(viewerPageUrl, params) {
@@ -339,25 +1009,20 @@ function buildViewerUrl(viewerPageUrl, params) {
339
1009
  return query === "" ? viewerPageUrl : `${viewerPageUrl}#${query}`;
340
1010
  }
341
1011
  const DEFAULT_TIMEOUT_MS = 300_000;
342
- /** Writes the PDF and stamps the metadata Vivliostyle would have written. */
343
- async function writePdfWithMetadata(pdf, meta) {
344
- const hasMetadata = meta.title !== undefined || meta.author !== undefined || meta.subject !== undefined || meta.language !== undefined;
345
- if (!hasMetadata)
346
- return pdf;
347
- const document = await PDFDocument.load(pdf, { updateMetadata: false });
348
- if (meta.title !== undefined)
349
- document.setTitle(meta.title);
350
- if (meta.author !== undefined)
351
- document.setAuthor(meta.author);
352
- if (meta.subject !== undefined)
353
- document.setSubject(meta.subject);
354
- if (meta.keywords !== undefined)
355
- document.setKeywords([meta.keywords]);
356
- if (meta.language !== undefined)
357
- document.setLanguage(meta.language);
358
- document.setProducer("vivliostyle-batch-cli");
359
- document.setCreator("vivliostyle-batch-cli");
360
- return document.save();
1012
+ /** The wrapper owns the producer/creator entries of every PDF it prints. */
1013
+ const TOOL_IDENTITY = "vivliostyle-batch-cli";
1014
+ function pdfMetadata(request) {
1015
+ return {
1016
+ ...(request.title === undefined ? {} : { title: request.title }),
1017
+ ...(request.author === undefined ? {} : { author: request.author }),
1018
+ ...(request.subject === undefined ? {} : { subject: request.subject }),
1019
+ ...(request.keywords === undefined ? {} : { keywords: request.keywords }),
1020
+ ...(request.language === undefined ? {} : { language: request.language }),
1021
+ ...(request.created === undefined ? {} : { created: request.created }),
1022
+ ...(request.modified === undefined ? {} : { modified: request.modified }),
1023
+ creator: TOOL_IDENTITY,
1024
+ producer: TOOL_IDENTITY
1025
+ };
361
1026
  }
362
1027
  /**
363
1028
  * Runs inside one frame (viewer window or a document/iframe within it):
@@ -386,8 +1051,179 @@ function buildFrameProbeScript(factor) {
386
1051
  try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
387
1052
  }
388
1053
  try { window.dispatchEvent(new Event("resize")); } catch(e){}
1054
+ // Bridge the viewer's broken page lifecycle. A-Frame scenes can end up
1055
+ // loaded-but-never-playing in the paginated tree (render loop, default
1056
+ // lights and asset loads all missed their window) while the same page
1057
+ // renders fine in a real browser. Start the scene's own loop and give
1058
+ // collapsed scenes a box (their display:block stylesheet does not reach
1059
+ // the re-parented tree, so unsized unknown elements stay inline).
1060
+ try {
1061
+ var bridgeScenes = document.querySelectorAll("a-scene");
1062
+ for (var bi = 0; bi < bridgeScenes.length; bi++) {
1063
+ var bridgeScene = bridgeScenes[bi];
1064
+ if (!bridgeScene.isPlaying && typeof bridgeScene.play === "function") {
1065
+ try { bridgeScene.play(); } catch (e) {}
1066
+ }
1067
+ if (bridgeScene.clientWidth === 0 || bridgeScene.clientHeight === 0) {
1068
+ var sized = bridgeScene.parentElement;
1069
+ while (sized && (sized.clientWidth === 0 || sized.clientHeight === 0)) sized = sized.parentElement;
1070
+ if (sized) {
1071
+ bridgeScene.style.display = "block";
1072
+ bridgeScene.style.width = sized.clientWidth + "px";
1073
+ bridgeScene.style.height = sized.clientHeight + "px";
1074
+ if (typeof bridgeScene.resize === "function") bridgeScene.resize();
1075
+ }
1076
+ }
1077
+ }
1078
+ await nextFrame();
1079
+ } catch(e){}
1080
+ // Give each scene what it needs to render like the browser does, then
1081
+ // materialize its WebGL canvas into a 2D overlay (2D canvases always
1082
+ // survive print-to-PDF): re-kick unloaded assets, swap unlit materials for
1083
+ // flat ones when no lights exist, render, and blit synchronously.
1084
+ var materialized = 0;
1085
+ var sceneDiag = "";
1086
+ try {
1087
+ var scenes = document.querySelectorAll("a-scene");
1088
+ for (var si = 0; si < scenes.length; si++) {
1089
+ var sceneEl = scenes[si];
1090
+ // The viewer clones scenes into its page boxes; only the VISIBLE one
1091
+ // (with a box) is what the PDF will show. The hidden original's render
1092
+ // would materialize nothing.
1093
+ if (!(sceneEl.clientWidth > 0 && sceneEl.clientHeight > 0)) continue;
1094
+ if (!sceneEl.renderer || !sceneEl.camera) continue;
1095
+ try {
1096
+ var gltfEl = sceneEl.querySelector("[gltf-model]");
1097
+ if (gltfEl) {
1098
+ var gmObj = gltfEl.object3D;
1099
+ sceneDiag += " gmKids=" + gmObj.children.length + "/" + (gltfEl.components["gltf-model"] ? String(gltfEl.components["gltf-model"].model !== null) : "nocomp");
1100
+ }
1101
+ sceneDiag += " tree=" + sceneEl.object3D.children.map(function (c) { return c.type + (c.children ? ":" + c.children.length : ""); }).join("|").slice(0, 110);
1102
+ } catch (e) {
1103
+ sceneDiag += " diagErr " + String(e).slice(0, 50);
1104
+ }
1105
+ try {
1106
+ var assetItems = sceneEl.querySelectorAll("a-asset-item");
1107
+ var assetWaits = [];
1108
+ for (var ai = 0; ai < assetItems.length; ai++) {
1109
+ var assetEl = assetItems[ai];
1110
+ if (assetEl.hasLoaded) continue;
1111
+ assetWaits.push(
1112
+ new Promise(function (resolve) {
1113
+ var settled = false;
1114
+ var finish = function () {
1115
+ if (settled) return;
1116
+ settled = true;
1117
+ resolve();
1118
+ };
1119
+ assetEl.addEventListener("loaded", finish, { once: true });
1120
+ assetEl.addEventListener("error", finish, { once: true });
1121
+ setTimeout(finish, 8000);
1122
+ var src = assetEl.getAttribute("src");
1123
+ if (src) assetEl.setAttribute("src", src);
1124
+ })
1125
+ );
1126
+ }
1127
+ if (assetWaits.length > 0) {
1128
+ await Promise.race([Promise.all(assetWaits), new Promise(function (r) { setTimeout(r, 9000); })]);
1129
+ }
1130
+ } catch (e) {}
1131
+ try {
1132
+ var lightsFound = 0;
1133
+ sceneEl.object3D.traverse(function (n) { if (n.isLight) lightsFound++; });
1134
+ if (lightsFound === 0) {
1135
+ var basicCtor = null;
1136
+ sceneEl.object3D.traverse(function (n) {
1137
+ if (n.isMesh && n.material && n.material.isMeshBasicMaterial && basicCtor === null) basicCtor = n.material.constructor;
1138
+ });
1139
+ if (basicCtor) {
1140
+ sceneEl.object3D.traverse(function (n) {
1141
+ if (!n.isMesh || !n.material || n.material.isMeshBasicMaterial) return;
1142
+ try {
1143
+ var m = n.material;
1144
+ var flat = new basicCtor({ color: m.color ? m.color.clone() : undefined });
1145
+ flat.side = m.side;
1146
+ flat.transparent = m.transparent;
1147
+ flat.opacity = m.opacity;
1148
+ if (m.map) flat.map = m.map;
1149
+ n.material = flat;
1150
+ } catch (e) {}
1151
+ });
1152
+ }
1153
+ }
1154
+ } catch(e){}
1155
+ try {
1156
+ sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
1157
+ var glCanvas = sceneEl.canvas;
1158
+ if (!glCanvas || glCanvas.width === 0 || glCanvas.height === 0) continue;
1159
+ var overlay = document.createElement("canvas");
1160
+ overlay.setAttribute("data-viv-gl-overlay", "");
1161
+ overlay.width = glCanvas.width;
1162
+ overlay.height = glCanvas.height;
1163
+ overlay.style.position = "absolute";
1164
+ overlay.style.pointerEvents = "none";
1165
+ overlay.style.width = glCanvas.clientWidth + "px";
1166
+ overlay.style.height = glCanvas.clientHeight + "px";
1167
+ var cr = glCanvas.getBoundingClientRect();
1168
+ var pr = (glCanvas.offsetParent || document.body).getBoundingClientRect();
1169
+ overlay.style.left = cr.left - pr.left + "px";
1170
+ overlay.style.top = cr.top - pr.top + "px";
1171
+ overlay.style.zIndex = "1";
1172
+ (glCanvas.parentNode || document.body).appendChild(overlay);
1173
+ overlay.getContext("2d").drawImage(glCanvas, 0, 0);
1174
+ // Empty capture = the scene never initialized in this tree (its
1175
+ // framework lifecycle was lost to the viewer's re-parenting). Replace
1176
+ // it with a fresh copy: the custom-element upgrade re-runs the full
1177
+ // framework lifecycle (assets, lights, render loop) in the now-sized
1178
+ // tree.
1179
+ var empty = true;
1180
+ try {
1181
+ var dd = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
1182
+ for (var di = 3; di < dd.length; di += 256) {
1183
+ if (dd[di] > 0) {
1184
+ empty = false;
1185
+ break;
1186
+ }
1187
+ }
1188
+ } catch (e) {
1189
+ empty = false;
1190
+ }
1191
+ if (empty) {
1192
+ var fresh = sceneEl.cloneNode(true);
1193
+ sceneEl.parentNode.replaceChild(fresh, sceneEl);
1194
+ sceneEl = fresh;
1195
+ // Enough time for the fresh scene's asset fetches (a real GLB over
1196
+ // the network) + first renders.
1197
+ await new Promise(function (r) {
1198
+ setTimeout(r, 8000);
1199
+ });
1200
+ if (!sceneEl.renderer || !sceneEl.camera) continue;
1201
+ }
1202
+ sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
1203
+ var gl2 = sceneEl.canvas;
1204
+ if (!gl2 || gl2.width === 0 || gl2.height === 0) continue;
1205
+ overlay.width = gl2.width;
1206
+ overlay.height = gl2.height;
1207
+ overlay.getContext("2d").drawImage(gl2, 0, 0);
1208
+ materialized++;
1209
+ try {
1210
+ var od = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
1211
+ var alphaN = 0;
1212
+ var orangeN = 0;
1213
+ for (var oi = 3; oi < od.length; oi += 16) {
1214
+ if (od[oi] > 0) alphaN++;
1215
+ if (od[oi - 3] > 150 && od[oi - 2] > 60 && od[oi - 2] < 200 && od[oi - 1] < 110 && od[oi - 3] > od[oi - 2] + 40) orangeN++;
1216
+ }
1217
+ glSample = [alphaN, orangeN];
1218
+ } catch (e) {}
1219
+ } catch (e) {}
1220
+ }
1221
+ } catch(e){}
389
1222
  // Hooks like echarts re-init dispose the canvas synchronously; let layout
390
1223
  // settle a frame before measuring so sizes reflect the repainted state.
1224
+ // This also lets render loops refill their drawing buffers after the
1225
+ // resize above — drawImage on a just-resized WebGL canvas would read the
1226
+ // cleared buffer.
391
1227
  try { await nextFrame(); } catch(e){}
392
1228
  if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
393
1229
  var webgl = false, webgl2 = false;
@@ -406,7 +1242,9 @@ function buildFrameProbeScript(factor) {
406
1242
  canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
407
1243
  iframeCount: document.querySelectorAll("iframe").length,
408
1244
  dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
409
- resized: resized
1245
+ resized: resized,
1246
+ materialized: materialized,
1247
+ sceneDiag: sceneDiag
410
1248
  };
411
1249
  })(${JSON.stringify(factor)})`;
412
1250
  }
@@ -420,8 +1258,9 @@ async function prepareForPrint(page, options = {}) {
420
1258
  try {
421
1259
  out.push((await frame.evaluate(script)));
422
1260
  }
423
- catch {
1261
+ catch (err) {
424
1262
  // Cross-origin embeds that refuse evaluation still print as pixels.
1263
+ log.trace("frame probe failed", frame.url?.() ?? "(frame)", err instanceof Error ? err.message : String(err));
425
1264
  continue;
426
1265
  }
427
1266
  }
@@ -433,10 +1272,11 @@ async function prepareForPrint(page, options = {}) {
433
1272
  /** One-line summary for logs: capabilities per frame that owns content. */
434
1273
  function summarizeCapabilities(caps) {
435
1274
  return caps
436
- .filter((c) => c.canvasCount > 0 || c.iframeCount > 0 || c.fixture !== null)
1275
+ .filter((c) => c.canvasCount > 0 || (c.iframeCount ?? 0) > 0 || c.fixture !== null)
437
1276
  .map((c) => `${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
438
1277
  `webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
439
- (c.resized !== null ? ` resized=[${c.resized}]` : ""))
1278
+ (c.resized !== null ? ` resized=[${c.resized}]` : "") +
1279
+ (c.materialized ? ` materialized=${c.materialized} ${c.sceneDiag ?? ""}` : ""))
440
1280
  .join(" | ");
441
1281
  }
442
1282
  async function renderPdf(request) {
@@ -466,12 +1306,15 @@ async function renderPdf(request) {
466
1306
  page.setDefaultNavigationTimeout(timeoutMs);
467
1307
  page.on("pageerror", (err) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
468
1308
  // Viewer and page errors are the usual reason a render produces nothing.
1309
+ // Debug/info console messages (fetch traces from the runtime script) are
1310
+ // shown at debug level, so -d traces every page-side request.
1311
+ const debugConsole = log.getLevel() <= log.levels.DEBUG;
469
1312
  page.on("console", (message) => {
470
1313
  const type = message.type();
471
- if (type !== "error" && type !== "warn")
1314
+ if (type !== "error" && type !== "warn" && !(debugConsole && (type === "debug" || type === "info")))
472
1315
  return;
473
1316
  const where = message.location();
474
- log.warn(`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`);
1317
+ log[debugConsole && type !== "error" && type !== "warn" ? "trace" : "warn"](`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`);
475
1318
  });
476
1319
  page.on("requestfailed", (request) => {
477
1320
  log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
@@ -524,9 +1367,33 @@ async function renderPdf(request) {
524
1367
  preferCSSPageSize: true,
525
1368
  tagged: true
526
1369
  });
527
- const stamped = await writePdfWithMetadata(pdf, request);
1370
+ const stamped = await postProcessPdf(pdf, {
1371
+ metadata: pdfMetadata(request),
1372
+ ...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
1373
+ ...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
1374
+ });
1375
+ if (request.pdfLabel !== undefined && request.validate !== false) {
1376
+ const violations = validateLabeledPdf(stamped, request.pdfLabel);
1377
+ if (violations.length > 0) {
1378
+ throw new Error(`${describeLabel(request.pdfLabel)} label failed validation, refusing to write a non-conforming output:\n` +
1379
+ violations.map((violation) => ` - ${violation.check}: ${violation.detail}`).join("\n"));
1380
+ }
1381
+ log.info(`[pdf] built-in ${describeLabel(request.pdfLabel)} validation passed`);
1382
+ }
528
1383
  mkdirSync(dirname(request.output), { recursive: true });
529
1384
  writeFileSync(request.output, stamped);
1385
+ if (request.verapdf === true && request.pdfLabel !== undefined) {
1386
+ const vera = runVeraPdf(request.output, request.pdfLabel);
1387
+ if (!vera.ran) {
1388
+ log.warn(`[pdf] verapdf skipped: ${vera.reason}`);
1389
+ }
1390
+ else if (vera.passed !== true) {
1391
+ throw new Error(`verapdf reports ${describeLabel(request.pdfLabel)} violations (exit ${vera.exitCode ?? "n/a"}):\n${vera.output}`);
1392
+ }
1393
+ else {
1394
+ log.info(`[pdf] verapdf reports ${describeLabel(request.pdfLabel)} conformance: PASS`);
1395
+ }
1396
+ }
530
1397
  const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
531
1398
  return { output: request.output, bytes: stamped.length, pageCount, settle };
532
1399
  }
@@ -567,6 +1434,136 @@ function fileURLOfSelf() {
567
1434
  return new URL(import.meta.url).pathname;
568
1435
  }
569
1436
 
1437
+ // src/metadata.ts
1438
+ /** Language tag assumed when no source provides one (project contract). */
1439
+ const DEFAULT_LANGUAGE = "de";
1440
+ /**
1441
+ * Extracts metadata from the input document: <title>, the usual
1442
+ * author/description/keywords meta tags, the creation/modification dates
1443
+ * (dcterms, falling back to the plain date meta tag) and the document
1444
+ * language.
1445
+ */
1446
+ function extractMetadataFromDocument(document) {
1447
+ const title = document.querySelector("title")?.textContent?.trim();
1448
+ const metaContent = (names) => {
1449
+ for (const name of names) {
1450
+ const element = document.querySelector(`meta[name="${name}" i]`) ?? document.querySelector(`meta[http-equiv="${name}" i]`);
1451
+ const content = element?.getAttribute("content")?.trim();
1452
+ if (content !== undefined && content !== "")
1453
+ return content;
1454
+ }
1455
+ return undefined;
1456
+ };
1457
+ return {
1458
+ ...(title === undefined || title === "" ? {} : { title }),
1459
+ ...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
1460
+ ...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
1461
+ ...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
1462
+ ...optional(metaContent(["dcterms.created", "dc.date", "date"]), (value) => ({ created: value })),
1463
+ ...optional(metaContent(["dcterms.modified", "dc.date.modified", "modified"]), (value) => ({ modified: value })),
1464
+ ...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
1465
+ language: value
1466
+ }))
1467
+ };
1468
+ }
1469
+ /**
1470
+ * Extracts metadata from a publication manifest (W3C Web Publication
1471
+ * Manifest shape): title, author, description, keywords and language.
1472
+ * Returns undefined when the text is not a JSON object.
1473
+ */
1474
+ function extractMetadataFromManifest(text) {
1475
+ let manifest;
1476
+ try {
1477
+ manifest = JSON.parse(text);
1478
+ }
1479
+ catch {
1480
+ return undefined;
1481
+ }
1482
+ if (manifest === null || typeof manifest !== "object")
1483
+ return undefined;
1484
+ const record = manifest;
1485
+ return {
1486
+ ...optional(asString(record.title), (value) => ({ title: value })),
1487
+ ...optional(asAuthorList(record.author), (value) => ({ author: value })),
1488
+ ...optional(asString(record.description), (value) => ({ subject: value })),
1489
+ ...optional(asStringList(record.keywords, ", "), (value) => ({ keywords: value })),
1490
+ ...optional(asStringList(record.language ?? record.inLanguage, " "), (value) => ({ language: value }))
1491
+ };
1492
+ }
1493
+ /**
1494
+ * Merges the sources: the CLI fields win over the extracted ones, and the
1495
+ * language falls back to the project default.
1496
+ */
1497
+ function resolveMetadata(cli, derived) {
1498
+ const merged = { ...derived, ...definedEntries(cli) };
1499
+ if (merged.language === undefined || merged.language === "") {
1500
+ merged.language = DEFAULT_LANGUAGE;
1501
+ }
1502
+ return merged;
1503
+ }
1504
+ /** Parses a `--pdfa` level like `2b`; part 4 takes no conformance level. */
1505
+ function parsePdfaLabel(value) {
1506
+ const match = /^([1-4])([abu])?$/i.exec(value.trim());
1507
+ if (match === null) {
1508
+ throw new Error(`Invalid --pdfa level: "${value}". Allowed: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4`);
1509
+ }
1510
+ const part = match[1];
1511
+ const conformance = match[2]?.toLowerCase();
1512
+ if (part === "4" && conformance !== undefined) {
1513
+ throw new Error(`PDF/A-4 does not take a conformance level: "${value}". Use --pdfa 4`);
1514
+ }
1515
+ if (part !== "4" && conformance === undefined) {
1516
+ throw new Error(`Missing PDF/A conformance level: "${value}". Use e.g. --pdfa 2b`);
1517
+ }
1518
+ return { kind: "pdfa", part, ...(conformance === undefined ? {} : { conformance }) };
1519
+ }
1520
+ /** Parses a `--pdfx` version; `X-1a` is accepted as shorthand for 2003. */
1521
+ function parsePdfxLabel(value) {
1522
+ const normalized = value.trim();
1523
+ if (normalized === "X-4")
1524
+ return { kind: "pdfx", version: "X-4" };
1525
+ if (normalized === "X-1a" || normalized === "X-1a:2003")
1526
+ return { kind: "pdfx", version: "X-1a:2003" };
1527
+ throw new Error(`Invalid --pdfx version: "${value}". Allowed: X-4, X-1a:2003`);
1528
+ }
1529
+ // ---------------------------------------------------------------------------
1530
+ // Helpers
1531
+ // ---------------------------------------------------------------------------
1532
+ function definedEntries(source) {
1533
+ const entries = {};
1534
+ for (const [key, value] of Object.entries(source)) {
1535
+ if (value !== undefined && value !== "")
1536
+ entries[key] = value;
1537
+ }
1538
+ return entries;
1539
+ }
1540
+ function optional(value, wrap) {
1541
+ return value === undefined || value === null || value === "" ? {} : wrap(value);
1542
+ }
1543
+ function asString(value) {
1544
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
1545
+ }
1546
+ /** Flattens string | {name} | ({name} | string)[] into "a; b" form. */
1547
+ function asAuthorList(value) {
1548
+ const names = Array.isArray(value) ? value : [value];
1549
+ const flattened = names
1550
+ .map((entry) => {
1551
+ if (typeof entry === "string")
1552
+ return entry.trim();
1553
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
1554
+ return entry.name.trim();
1555
+ }
1556
+ return "";
1557
+ })
1558
+ .filter((name) => name !== "");
1559
+ return flattened.length === 0 ? undefined : flattened.join("; ");
1560
+ }
1561
+ function asStringList(value, separator) {
1562
+ const entries = Array.isArray(value) ? value : [value];
1563
+ const flattened = entries.map((entry) => (typeof entry === "string" ? entry.trim() : "")).filter((entry) => entry !== "");
1564
+ return flattened.length === 0 ? undefined : flattened.join(separator);
1565
+ }
1566
+
570
1567
  // src/vivliostyle-cli.ts
571
1568
  // Copyright (c) 2026 Christian Mahnke
572
1569
  // Licensed under the MIT License.
@@ -670,7 +1667,38 @@ function buildRuntimeScript(options) {
670
1667
  return `(function(){
671
1668
  var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
672
1669
  var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
673
- var pending=0,frames=0,last=0,mutations=0,done=false;
1670
+ var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
1671
+ // Force preserveDrawingBuffer on every WebGL context the page creates:
1672
+ // print-to-PDF otherwise captures the cleared drawing buffer and WebGL
1673
+ // content ships empty, even though the browser shows it composited.
1674
+ try {
1675
+ var origGetContext = HTMLCanvasElement.prototype.getContext;
1676
+ HTMLCanvasElement.prototype.getContext = function (type, attrs) {
1677
+ if (typeof type === "string" && /^webgl/.test(type)) {
1678
+ attrs = Object.assign({}, attrs || {});
1679
+ attrs.preserveDrawingBuffer = true;
1680
+ return origGetContext.call(this, type, attrs);
1681
+ }
1682
+ return origGetContext.call(this, type, attrs);
1683
+ };
1684
+ } catch (e) {}
1685
+ // Vivliostyle re-dispatches DOMContentLoaded on the window only, so scripts
1686
+ // waiting for it on the document (framework bootstraps, print scripts, asset
1687
+ // bootstraps) never run. Re-dispatch the lifecycle events properly once
1688
+ // loading finished.
1689
+ try {
1690
+ var redeliver = function () {
1691
+ setTimeout(function () {
1692
+ try {
1693
+ document.dispatchEvent(new Event("DOMContentLoaded"));
1694
+ window.dispatchEvent(new Event("DOMContentLoaded"));
1695
+ window.dispatchEvent(new Event("load"));
1696
+ } catch (e) {}
1697
+ }, 0);
1698
+ };
1699
+ if (document.readyState === "complete") redeliver();
1700
+ else window.addEventListener("load", redeliver, { once: true });
1701
+ } catch (e) {}
674
1702
  var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
675
1703
 
676
1704
  // Root-relative URLs resolve against the site root, document-relative ones
@@ -704,7 +1732,7 @@ function signal(why){
704
1732
  var at=Math.round(performance.now());
705
1733
  state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
706
1734
  var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
707
- "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&dpr="+window.devicePixelRatio+
1735
+ "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&longtasks="+longtasks+"&dpr="+window.devicePixelRatio+
708
1736
  "&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
709
1737
  "&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
710
1738
  try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
@@ -734,14 +1762,39 @@ if(of){window.fetch=function(input,init){
734
1762
  else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
735
1763
  }catch(e){}
736
1764
  pending++;last=performance.now();
737
- return of.call(this,input,init).then(function(v){pending--;last=performance.now();return v;},
738
- function(e){pending--;last=performance.now();throw e;});};}
1765
+ var furl=(typeof input==="string"?input:input&&input.url?input.url:"?");
1766
+ return of.call(this,input,init).then(function(v){pending--;last=performance.now();
1767
+ try{console.debug("[viv-fetch]",furl,"->",v.status);}catch(e){}
1768
+ return v;},
1769
+ function(e){pending--;last=performance.now();
1770
+ try{console.debug("[viv-fetch]",furl,"-> FAILED",String(e).slice(0,80));}catch(e2){}
1771
+ throw e;});};}
739
1772
  var XHR=window.XMLHttpRequest;
740
1773
  if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
741
- XHR.prototype.open=function(m,u){this.__vscounted=true;return open.apply(this,arguments);};
1774
+ XHR.prototype.open=function(m,u){this.__vscounted=true;this.__vsurl=fix(u);return open.apply(this,arguments);};
742
1775
  XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
743
- this.addEventListener("loadend",function(){pending--;last=performance.now();});}
1776
+ this.addEventListener("loadend",function(){pending--;last=performance.now();
1777
+ try{console.debug("[viv-xhr]",this.__vsurl,"->",this.status);}catch(e){}});}
744
1778
  return send.apply(this,arguments);};}
1779
+ // WebAssembly compilation runs after its fetch resolves, so the fetch wrapper
1780
+ // alone would report idle mid-compile. Hold pending through it.
1781
+ var WA=window.WebAssembly;
1782
+ if(WA){["instantiate","instantiateStreaming","compile","compileStreaming"].forEach(function(n){
1783
+ var orig=WA[n];if(typeof orig!=="function")return;
1784
+ WA[n]=function(){pending++;last=performance.now();
1785
+ var result;
1786
+ try{result=orig.apply(this,arguments);}catch(e){pending--;last=performance.now();throw e;}
1787
+ if(result&&typeof result.then==="function"){
1788
+ return result.then(function(v){pending--;last=performance.now();return v;},
1789
+ function(e){pending--;last=performance.now();throw e;});
1790
+ }
1791
+ pending--;last=performance.now();return result;};});}
1792
+ // Heavy main-thread work (script eval, wasm compile, shader/layout jank)
1793
+ // emits no network or DOM signal; long tasks keep the quiet window open.
1794
+ try{var PO=window.PerformanceObserver;
1795
+ if(typeof PO==="function"){new PO(function(list){
1796
+ var entries=list.getEntries();for(var i=0;i<entries.length;i++){longtasks++;last=performance.now();}
1797
+ }).observe({entryTypes:["longtask"]});}}catch(e){}
745
1798
  ["Image","Audio"].forEach(function(n){
746
1799
  var Orig=window[n];if(!Orig)return;
747
1800
  var Wrapped=function(u){return new Orig(fix(u));};
@@ -766,6 +1819,8 @@ last=performance.now();
766
1819
  ${expandDetailsTick}
767
1820
  var now=performance.now();
768
1821
  if(now>=DEADLINE){signal("deadline");return;}
1822
+ // Webfonts loading late would leave canvas text painted with fallbacks.
1823
+ try{if(document.fonts&&document.fonts.status==="loading"){setTimeout(check,50);return;}}catch(e){}
769
1824
  // Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
770
1825
  // painted instead of making the gate guess from network quietness. Shader
771
1826
  // compile and tile decode finish after the last fetch, so readiness wins.
@@ -1133,6 +2188,72 @@ function rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl
1133
2188
  };
1134
2189
  return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
1135
2190
  }
2191
+ /**
2192
+ * Resolves relative URLs on custom elements (`<a-asset-item>`,
2193
+ * `<model-viewer>`, and any tag name containing a dash) to absolute server
2194
+ * URLs.
2195
+ *
2196
+ * Vivliostyle resolves the subresource attributes it knows (`<img>`,
2197
+ * `<iframe>`, …) correctly, but mangles relative URLs on elements it does not
2198
+ * understand — `../tiles/model.glb` on an `<a-asset-item>` came back as
2199
+ * `http://tiles/model.glb`. Absolute server URLs always resolve, so pages hand
2200
+ * the viewer those instead. Standard elements are left alone (the viewer and
2201
+ * the runtime URL shim already handle them); only dash-tagged elements, whose
2202
+ * attributes the viewer cannot be trusted with, are rewritten.
2203
+ */
2204
+ function rewriteCustomElementUrlsInDom(document, documentDirUrl) {
2205
+ let changed = false;
2206
+ const resolveOne = (url) => {
2207
+ const current = url.trim();
2208
+ if (current === "" || current.startsWith("#") || current.startsWith("?") || current.startsWith("//"))
2209
+ return current;
2210
+ // Absolute URLs (http:, data:, blob:, …) resolve as-is; root-relative ones
2211
+ // are covered by the server-URL rewrite.
2212
+ if (/^[a-z][a-z0-9+.-]*:/i.test(current) || current.startsWith("/"))
2213
+ return current;
2214
+ try {
2215
+ const resolved = new URL(current, documentDirUrl).href;
2216
+ return resolved === current ? current : resolved;
2217
+ }
2218
+ catch {
2219
+ return current;
2220
+ }
2221
+ };
2222
+ const apply = (el, attr) => {
2223
+ const raw = el.getAttribute(attr);
2224
+ if (raw === null)
2225
+ return;
2226
+ if (attr === "src") {
2227
+ const next = resolveOne(raw);
2228
+ if (next === raw.trim() || next === raw)
2229
+ return;
2230
+ el.setAttribute(attr, next);
2231
+ changed = true;
2232
+ return;
2233
+ }
2234
+ const kept = raw
2235
+ .split(",")
2236
+ .map((candidate) => candidate.trim())
2237
+ .filter(Boolean)
2238
+ .map((candidate) => {
2239
+ const [url, ...descriptor] = candidate.split(/\s+/);
2240
+ return [resolveOne(url), ...descriptor].join(" ");
2241
+ });
2242
+ const next = kept.join(", ");
2243
+ if (next === raw)
2244
+ return;
2245
+ el.setAttribute(attr, next);
2246
+ changed = true;
2247
+ };
2248
+ for (const el of document.querySelectorAll("[src],[srcset]")) {
2249
+ // Tag names are upper-cased in HTML documents; the dash test is case-free.
2250
+ if (!el.tagName.includes("-"))
2251
+ continue;
2252
+ apply(el, "src");
2253
+ apply(el, "srcset");
2254
+ }
2255
+ return changed;
2256
+ }
1136
2257
  /**
1137
2258
  * Returns a predicate that reports whether a root-relative path can be served
1138
2259
  * from one of the configured asset-base local roots.
@@ -1252,10 +2373,18 @@ function buildPreviewHtml(inputAbs, assetBases, options = {}) {
1252
2373
  const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
1253
2374
  if (changed)
1254
2375
  log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
2376
+ // Same custom-element fix as the build path: the viewer mangles relative
2377
+ // URLs on elements it does not understand. Only applied when the caller
2378
+ // knows the document's directory on the server (see startPreview).
2379
+ const customChanged = options.documentBaseUrl === undefined || options.documentBaseUrl === null
2380
+ ? false
2381
+ : rewriteCustomElementUrlsInDom(document, options.documentBaseUrl);
2382
+ if (customChanged)
2383
+ log.trace("buildPreviewHtml: resolved custom-element URLs → server URLs");
1255
2384
  const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
1256
2385
  if (dropped.length > 0)
1257
2386
  reportDroppedRemoteRefs(dropped);
1258
- if (!changed && dropped.length === 0) {
2387
+ if (!changed && !customChanged && dropped.length === 0) {
1259
2388
  log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
1260
2389
  return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
1261
2390
  }
@@ -1302,6 +2431,10 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
1302
2431
  const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
1303
2432
  if (srvChanged)
1304
2433
  log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
2434
+ const customBase = options.documentBaseUrl ?? `${serverBaseUrl}/`;
2435
+ const customChanged = rewriteCustomElementUrlsInDom(document, customBase);
2436
+ if (customChanged)
2437
+ log.trace("prepareInputHtmlForBuild: resolved custom-element URLs → server URLs", { customBase });
1305
2438
  const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
1306
2439
  const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
1307
2440
  if (dropped.length > 0)
@@ -1320,7 +2453,13 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
1320
2453
  injectRuntimeScriptInDom(document, { origin, documentBaseUrl, gate: options.settle ?? null, expandDetails: true });
1321
2454
  log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
1322
2455
  }
1323
- if (!absChanged && !srvChanged && dropped.length === 0 && gone.length === 0 && options.settle == null && !wantsRuntime) {
2456
+ if (!absChanged &&
2457
+ !srvChanged &&
2458
+ !customChanged &&
2459
+ dropped.length === 0 &&
2460
+ gone.length === 0 &&
2461
+ options.settle == null &&
2462
+ !wantsRuntime) {
1324
2463
  log.trace("prepareInputHtmlForBuild: no changes, using original file");
1325
2464
  return { vivliostyleInput: inputAbs, cleanup: () => undefined };
1326
2465
  }
@@ -1577,7 +2716,39 @@ function buildProgram() {
1577
2716
  .option("-o, --output <file>", "Output file path", "output.pdf")
1578
2717
  .option("--title <title>", "Document title (overrides the one in the source)")
1579
2718
  .option("--author <author>", "Document author")
1580
- .option("--language <lang>", "Document language tag (e.g. en, de, ja)", "de")
2719
+ .option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
2720
+ .option("--keywords <keywords>", "Document keywords, comma separated")
2721
+ .option("--language <lang>", "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'")
2722
+ .option("--created <date>", "Document creation date (ISO 8601, e.g. 2024-11-18T00:00:00+01:00). Taken from the document's dcterms.created meta tag when omitted")
2723
+ .option("--modified <date>", "Document modification date (ISO 8601). Taken from the document's dcterms.modified meta tag when omitted")
2724
+ .option("--pdfa <level>", [
2725
+ "Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
2726
+ "an OutputIntent with an embedded ICC profile (bundled sRGB unless",
2727
+ "--icc-profile is given) and a file identifier are written.",
2728
+ "Levels: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4.",
2729
+ "This is a label only: the content is neither converted nor checked,",
2730
+ "so conformance of the content is the author's responsibility."
2731
+ ].join("\n "))
2732
+ .option("--pdfx <version>", [
2733
+ "Label the output PDF as PDF/X (ISO 15930): X-4 writes the",
2734
+ "identification metadata as XMP, X-1a:2003 into the information",
2735
+ "dictionary. Both embed the --icc-profile as the OutputIntent.",
2736
+ "Same label-only semantics as --pdfa."
2737
+ ].join("\n "))
2738
+ .option("--no-validate", [
2739
+ "Skip the built-in compliance checks run for --pdfa/--pdfx output:",
2740
+ "PDF version of the labeled part, XMP identification, OutputIntent,",
2741
+ "file identifier, embedded fonts and the absence of JavaScript."
2742
+ ].join("\n "))
2743
+ .option("--verapdf", [
2744
+ "Additionally run the verapdf binary (must be on the PATH) against the",
2745
+ "output and fail the build on full ISO rule-set violations."
2746
+ ].join("\n "))
2747
+ .option("--icc-profile <path>", [
2748
+ "ICC profile embedded as the PDF output intent, e.g. a print",
2749
+ "provider's profile. Required for --pdfx; --pdfa defaults to the",
2750
+ "bundled sRGB profile."
2751
+ ].join("\n "))
1581
2752
  .option("--static <mapping>", [
1582
2753
  "Map a virtual path to a local directory or file.",
1583
2754
  "Format: /virtual/path:/absolute/local/path",
@@ -1616,8 +2787,10 @@ function buildProgram() {
1616
2787
  ].join("\n "))
1617
2788
  .option("--wait-for-content [ms]", [
1618
2789
  "Delay pagination until the page's own async work finished: no request in",
1619
- "flight and the document height stable for --quiet-ms (default 400).",
1620
- "Without [ms] the hard limit of 25000ms applies; larger values are capped."
2790
+ "flight, no wasm compiling, no long task running and the document height",
2791
+ "stable for --quiet-ms (default 400). Pages with <script> wait",
2792
+ "automatically (deadline 10000ms); 0 disables, larger values capped at",
2793
+ "25000ms."
1621
2794
  ].join("\n "))
1622
2795
  .option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
1623
2796
  .option("--timeout <ms>", ["Give up on a page after <ms> (Vivliostyle default: 300000).", "Lower it for pages with embeds that never finish loading."].join("\n "))
@@ -1649,7 +2822,12 @@ function buildProgram() {
1649
2822
  " • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
1650
2823
  " • the browser prints that page to PDF, so canvases and iframes stay real content.",
1651
2824
  " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
1652
- " • --asset-base localBase is also a fallback root for CSS-referenced assets."
2825
+ " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
2826
+ " • PDF metadata (--title/--author/--subject/--keywords/--language/--created/--modified)",
2827
+ " • values read from the document or the publication manifest; language falls",
2828
+ " • back to 'de'. --pdfa/--pdfx label the output; the built-in validation",
2829
+ " • checks the practical subset (--no-validate skips it) and --verapdf runs",
2830
+ " • the full ISO rule set through the verapdf binary."
1653
2831
  ].join("\n"));
1654
2832
  }
1655
2833
  function printHelp() {
@@ -1684,7 +2862,15 @@ async function runRender(params) {
1684
2862
  ...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
1685
2863
  ...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
1686
2864
  ...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
1687
- ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language })
2865
+ ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
2866
+ ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
2867
+ ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
2868
+ ...(params.metaFields.created === undefined ? {} : { created: params.metaFields.created }),
2869
+ ...(params.metaFields.modified === undefined ? {} : { modified: params.metaFields.modified }),
2870
+ ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
2871
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name }),
2872
+ validate: params.validate,
2873
+ ...(params.verapdf === undefined ? {} : { verapdf: params.verapdf })
1688
2874
  };
1689
2875
  log.trace("renderPdf request", request);
1690
2876
  const result = await renderPdf(request);
@@ -1710,10 +2896,16 @@ function resolveInternalLogLevel(options) {
1710
2896
  * hard limit is capped below that.
1711
2897
  */
1712
2898
  const MAX_SETTLE_DEADLINE_MS = 25_000;
2899
+ /** Deadline for the automatic wait on script-driven pages (see below). */
2900
+ const AUTO_SETTLE_DEADLINE_MS = 10_000;
1713
2901
  function resolveSettleGate(options) {
1714
2902
  const raw = options.waitForContent;
1715
2903
  if (raw === undefined || raw === false)
1716
2904
  return null;
2905
+ // Explicit 0 disables the wait — including the automatic one for pages
2906
+ // with scripts (see resolveEffectiveSettle).
2907
+ if (raw === "0")
2908
+ return null;
1717
2909
  const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
1718
2910
  if (!Number.isFinite(requested) || requested <= 0)
1719
2911
  throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
@@ -1725,6 +2917,86 @@ function resolveSettleGate(options) {
1725
2917
  deadlineMs: Math.min(requested, MAX_SETTLE_DEADLINE_MS)
1726
2918
  };
1727
2919
  }
2920
+ /**
2921
+ * Settle gate that actually applies: an explicit `--wait-for-content` wins;
2922
+ * otherwise pages that run scripts wait automatically (charts, wasm, WebGL
2923
+ * would otherwise race pagination), static pages don't wait at all.
2924
+ */
2925
+ function resolveEffectiveSettle(options, hasScripts) {
2926
+ const explicit = resolveSettleGate(options);
2927
+ if (explicit !== null || options.waitForContent !== undefined)
2928
+ return { gate: explicit, autoArmed: false };
2929
+ if (!hasScripts)
2930
+ return { gate: null, autoArmed: false };
2931
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
2932
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0)
2933
+ throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
2934
+ return { gate: { quietMs: quietRaw, deadlineMs: AUTO_SETTLE_DEADLINE_MS }, autoArmed: true };
2935
+ }
2936
+ // ---------------------------------------------------------------------------
2937
+ // PDF metadata + standards labeling resolution
2938
+ // ---------------------------------------------------------------------------
2939
+ function describePdfLabel(label) {
2940
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
2941
+ }
2942
+ /**
2943
+ * `--pdfa` / `--pdfx`: mutually exclusive standards labels for the output PDF.
2944
+ */
2945
+ function resolvePdfLabel(options) {
2946
+ if (options.pdfa !== undefined && options.pdfx !== undefined) {
2947
+ throw new Error("--pdfa and --pdfx are mutually exclusive — choose one standard label");
2948
+ }
2949
+ if (options.pdfa !== undefined)
2950
+ return parsePdfaLabel(options.pdfa);
2951
+ if (options.pdfx !== undefined)
2952
+ return parsePdfxLabel(options.pdfx);
2953
+ return undefined;
2954
+ }
2955
+ /**
2956
+ * `--icc-profile <path>`: the profile the OutputIntent embeds. PDF/X always
2957
+ * needs one; a PDF/A build without the flag embeds the bundled sRGB profile.
2958
+ */
2959
+ function resolveIccProfile(options, label) {
2960
+ if (options.iccProfile !== undefined) {
2961
+ const path = resolve(options.iccProfile);
2962
+ if (!existsSync(path))
2963
+ throw new Error(`--icc-profile file does not exist: ${path}`);
2964
+ return { bytes: readFileSync(path), name: basename(path) };
2965
+ }
2966
+ if (label === undefined)
2967
+ return undefined;
2968
+ if (label.kind === "pdfx") {
2969
+ throw new Error(`--pdfx ${label.version} requires --icc-profile <path>: PDF/X output intents carry an ICC profile`);
2970
+ }
2971
+ return loadDefaultIccProfile();
2972
+ }
2973
+ /**
2974
+ * Document metadata for the PDF: the flags override values taken from the
2975
+ * input (HTML meta tags or a publication manifest); the language falls back
2976
+ * to "de" when no source provides one.
2977
+ */
2978
+ function resolvePdfMetadata(options, inputAbs, htmlMode) {
2979
+ const cliFields = pickDefinedStrings(options, [
2980
+ "title",
2981
+ "author",
2982
+ "subject",
2983
+ "keywords",
2984
+ "language",
2985
+ "created",
2986
+ "modified"
2987
+ ]);
2988
+ let derived;
2989
+ if (htmlMode) {
2990
+ derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
2991
+ }
2992
+ else if (/\.json$/i.test(inputAbs)) {
2993
+ derived = extractMetadataFromManifest(readFileSync(inputAbs, "utf-8"));
2994
+ if (derived === undefined)
2995
+ log.warn(`[metadata] ${inputAbs} is not a JSON publication manifest — no manifest metadata`);
2996
+ }
2997
+ log.trace("metadata (derived)", derived);
2998
+ return resolveMetadata(cliFields, derived);
2999
+ }
1728
3000
  async function execute(options, extraArgs = []) {
1729
3001
  log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
1730
3002
  log.trace("raw CLI options", options);
@@ -1806,9 +3078,21 @@ async function execute(options, extraArgs = []) {
1806
3078
  }
1807
3079
  const extraConfig = parseExtraArgs(extraArgs);
1808
3080
  log.trace("extraConfig (parsed from -- args)", extraConfig);
1809
- const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
3081
+ const metaFields = resolvePdfMetadata(options, inputAbs, htmlMode);
3082
+ const pdfLabel = resolvePdfLabel(options);
3083
+ if (pdfLabel !== undefined)
3084
+ log.info(`[pdf] labeling the output as ${describePdfLabel(pdfLabel)}`);
3085
+ if (options.iccProfile !== undefined && pdfLabel === undefined) {
3086
+ log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
3087
+ }
3088
+ const iccProfile = resolveIccProfile(options, pdfLabel);
1810
3089
  const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
1811
- const settle = resolveSettleGate(options);
3090
+ // The wait arms automatically on script-driven pages: without it, charts,
3091
+ // wasm and WebGL race pagination and the PDF ships half-painted content.
3092
+ const hasScripts = htmlMode && new JSDOM(readFileSync(inputAbs, "utf-8")).window.document.querySelector("script") !== null;
3093
+ const { gate: settle, autoArmed } = resolveEffectiveSettle(options, hasScripts);
3094
+ if (autoArmed)
3095
+ log.info(`[wait] auto-armed for script-driven page (deadline ${AUTO_SETTLE_DEADLINE_MS}ms, disable with --wait-for-content 0)`);
1812
3096
  const htmlOptions = {
1813
3097
  allowRemote: fetchMissing,
1814
3098
  fetchMissing,
@@ -1902,7 +3186,11 @@ async function execute(options, extraArgs = []) {
1902
3186
  timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
1903
3187
  waitForSettle: htmlOptions.settle != null,
1904
3188
  chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
1905
- canvasScale
3189
+ canvasScale,
3190
+ ...(pdfLabel === undefined ? {} : { pdfLabel }),
3191
+ ...(iccProfile === undefined ? {} : { iccProfile }),
3192
+ validate: options.validate !== false,
3193
+ ...(options.verapdf === true ? { verapdf: true } : {})
1906
3194
  });
1907
3195
  }
1908
3196
  finally {
@@ -1947,7 +3235,12 @@ async function startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraC
1947
3235
  viewerFilePath: join(viewerLibDir, "index.html"),
1948
3236
  log: (message) => log.info(message)
1949
3237
  });
1950
- const prepared = buildPreviewHtml(inputAbs, assetBases, htmlOptions);
3238
+ const prepared = buildPreviewHtml(inputAbs, assetBases, {
3239
+ ...htmlOptions,
3240
+ // The viewer is served next to the document, so custom-element URLs
3241
+ // resolve against the document's own directory (see siteDirectory below).
3242
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
3243
+ });
1951
3244
  entry.localPath = prepared.htmlPath;
1952
3245
  const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
1953
3246
  const documentUrl = `${server.baseUrl}${sitePath}`;
@@ -2033,4 +3326,4 @@ if (isDirectExecution()) {
2033
3326
  });
2034
3327
  }
2035
3328
 
2036
- export { EXPAND_DETAILS_SNIPPET, buildPreviewHtml, buildRuntimeScript, buildSettleGateImage, coerceExtraValue, collectRemoteReferences, collectUnservedVirtualPaths, createAssetBasePathProbe, deriveSitePath, dropRemoteReferencesInDom, dropUnavailableReferencesInDom, execute, extractUrlsFromHtml, injectRuntimeScriptInDom, isHtmlInput, isRemoteUrl, isStaticServerUrl, mapAbsoluteUrlToLocal, normalizeExtraKey, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseMetaRefreshTarget, parseStaticMapping, prepareInputHtmlForBuild, printHelp, probeRemoteReferences, referencesToProbe, resolveSettleGate, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteUrlAttributes, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, siteDirectory, splitArgsAtDoubleDash, startPreview, urlToStaticMapping };
3329
+ export { EXPAND_DETAILS_SNIPPET, buildPreviewHtml, buildRuntimeScript, buildSettleGateImage, coerceExtraValue, collectRemoteReferences, collectUnservedVirtualPaths, createAssetBasePathProbe, deriveSitePath, dropRemoteReferencesInDom, dropUnavailableReferencesInDom, execute, extractUrlsFromHtml, injectRuntimeScriptInDom, isHtmlInput, isRemoteUrl, isStaticServerUrl, mapAbsoluteUrlToLocal, normalizeExtraKey, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseMetaRefreshTarget, parseStaticMapping, prepareInputHtmlForBuild, printHelp, probeRemoteReferences, referencesToProbe, resolveEffectiveSettle, resolveIccProfile, resolvePdfLabel, resolvePdfMetadata, resolveSettleGate, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteCustomElementUrlsInDom, rewriteUrlAttributes, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, siteDirectory, splitArgsAtDoubleDash, startPreview, urlToStaticMapping };