@projektemacher/vivliostyle-batch-cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,16 @@ import log, { type LogLevelDesc } from "loglevel";
13
13
  import { VIEWER_PAGE_NAME, startStaticServer, type AssetBaseMapping, type SettleGate, type StaticMap } from "./server.js";
14
14
  import { buildViewerUrl, renderPdf, type ViewerParams } from "./render/pdf.js";
15
15
  import { resolveViewerLibDir } from "./render/viewer.js";
16
+ import { loadDefaultIccProfile } from "./render/pdf-postprocess.js";
17
+ import {
18
+ extractMetadataFromDocument,
19
+ extractMetadataFromManifest,
20
+ parsePdfaLabel,
21
+ parsePdfxLabel,
22
+ resolveMetadata,
23
+ type DocumentMetadata
24
+ } from "./metadata.js";
25
+ import type { PdfLabel } from "./render/xmp.js";
16
26
 
17
27
  type OutputFormat = "pdf";
18
28
  type LogLevel = "silent" | "info" | "verbose" | "debug";
@@ -23,7 +33,12 @@ type CliOptions = {
23
33
  output: string;
24
34
  title?: string;
25
35
  author?: string;
36
+ subject?: string;
37
+ keywords?: string;
26
38
  language?: string;
39
+ pdfa?: string;
40
+ pdfx?: string;
41
+ iccProfile?: string;
27
42
  static: string[];
28
43
  scripts: boolean;
29
44
  format: string;
@@ -194,7 +209,38 @@ export function buildRuntimeScript(options: RuntimeScriptOptions): string {
194
209
  return `(function(){
195
210
  var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
196
211
  var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
197
- var pending=0,frames=0,last=0,mutations=0,done=false;
212
+ var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
213
+ // Force preserveDrawingBuffer on every WebGL context the page creates:
214
+ // print-to-PDF otherwise captures the cleared drawing buffer and WebGL
215
+ // content ships empty, even though the browser shows it composited.
216
+ try {
217
+ var origGetContext = HTMLCanvasElement.prototype.getContext;
218
+ HTMLCanvasElement.prototype.getContext = function (type, attrs) {
219
+ if (typeof type === "string" && /^webgl/.test(type)) {
220
+ attrs = Object.assign({}, attrs || {});
221
+ attrs.preserveDrawingBuffer = true;
222
+ return origGetContext.call(this, type, attrs);
223
+ }
224
+ return origGetContext.call(this, type, attrs);
225
+ };
226
+ } catch (e) {}
227
+ // Vivliostyle re-dispatches DOMContentLoaded on the window only, so scripts
228
+ // waiting for it on the document (framework bootstraps, print scripts, asset
229
+ // bootstraps) never run. Re-dispatch the lifecycle events properly once
230
+ // loading finished.
231
+ try {
232
+ var redeliver = function () {
233
+ setTimeout(function () {
234
+ try {
235
+ document.dispatchEvent(new Event("DOMContentLoaded"));
236
+ window.dispatchEvent(new Event("DOMContentLoaded"));
237
+ window.dispatchEvent(new Event("load"));
238
+ } catch (e) {}
239
+ }, 0);
240
+ };
241
+ if (document.readyState === "complete") redeliver();
242
+ else window.addEventListener("load", redeliver, { once: true });
243
+ } catch (e) {}
198
244
  var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
199
245
 
200
246
  // Root-relative URLs resolve against the site root, document-relative ones
@@ -228,7 +274,7 @@ function signal(why){
228
274
  var at=Math.round(performance.now());
229
275
  state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
230
276
  var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
231
- "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&dpr="+window.devicePixelRatio+
277
+ "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&longtasks="+longtasks+"&dpr="+window.devicePixelRatio+
232
278
  "&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
233
279
  "&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
234
280
  try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
@@ -258,14 +304,39 @@ if(of){window.fetch=function(input,init){
258
304
  else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
259
305
  }catch(e){}
260
306
  pending++;last=performance.now();
261
- return of.call(this,input,init).then(function(v){pending--;last=performance.now();return v;},
262
- function(e){pending--;last=performance.now();throw e;});};}
307
+ var furl=(typeof input==="string"?input:input&&input.url?input.url:"?");
308
+ return of.call(this,input,init).then(function(v){pending--;last=performance.now();
309
+ try{console.debug("[viv-fetch]",furl,"->",v.status);}catch(e){}
310
+ return v;},
311
+ function(e){pending--;last=performance.now();
312
+ try{console.debug("[viv-fetch]",furl,"-> FAILED",String(e).slice(0,80));}catch(e2){}
313
+ throw e;});};}
263
314
  var XHR=window.XMLHttpRequest;
264
315
  if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
265
- XHR.prototype.open=function(m,u){this.__vscounted=true;return open.apply(this,arguments);};
316
+ XHR.prototype.open=function(m,u){this.__vscounted=true;this.__vsurl=fix(u);return open.apply(this,arguments);};
266
317
  XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
267
- this.addEventListener("loadend",function(){pending--;last=performance.now();});}
318
+ this.addEventListener("loadend",function(){pending--;last=performance.now();
319
+ try{console.debug("[viv-xhr]",this.__vsurl,"->",this.status);}catch(e){}});}
268
320
  return send.apply(this,arguments);};}
321
+ // WebAssembly compilation runs after its fetch resolves, so the fetch wrapper
322
+ // alone would report idle mid-compile. Hold pending through it.
323
+ var WA=window.WebAssembly;
324
+ if(WA){["instantiate","instantiateStreaming","compile","compileStreaming"].forEach(function(n){
325
+ var orig=WA[n];if(typeof orig!=="function")return;
326
+ WA[n]=function(){pending++;last=performance.now();
327
+ var result;
328
+ try{result=orig.apply(this,arguments);}catch(e){pending--;last=performance.now();throw e;}
329
+ if(result&&typeof result.then==="function"){
330
+ return result.then(function(v){pending--;last=performance.now();return v;},
331
+ function(e){pending--;last=performance.now();throw e;});
332
+ }
333
+ pending--;last=performance.now();return result;};});}
334
+ // Heavy main-thread work (script eval, wasm compile, shader/layout jank)
335
+ // emits no network or DOM signal; long tasks keep the quiet window open.
336
+ try{var PO=window.PerformanceObserver;
337
+ if(typeof PO==="function"){new PO(function(list){
338
+ var entries=list.getEntries();for(var i=0;i<entries.length;i++){longtasks++;last=performance.now();}
339
+ }).observe({entryTypes:["longtask"]});}}catch(e){}
269
340
  ["Image","Audio"].forEach(function(n){
270
341
  var Orig=window[n];if(!Orig)return;
271
342
  var Wrapped=function(u){return new Orig(fix(u));};
@@ -290,6 +361,8 @@ last=performance.now();
290
361
  ${expandDetailsTick}
291
362
  var now=performance.now();
292
363
  if(now>=DEADLINE){signal("deadline");return;}
364
+ // Webfonts loading late would leave canvas text painted with fallbacks.
365
+ try{if(document.fonts&&document.fonts.status==="loading"){setTimeout(check,50);return;}}catch(e){}
293
366
  // Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
294
367
  // painted instead of making the gate guess from network quietness. Shader
295
368
  // compile and tile decode finish after the last fetch, so readiness wins.
@@ -712,6 +785,70 @@ export function rewriteVirtualPathsToServerInDom(
712
785
  return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
713
786
  }
714
787
 
788
+ /**
789
+ * Resolves relative URLs on custom elements (`<a-asset-item>`,
790
+ * `<model-viewer>`, and any tag name containing a dash) to absolute server
791
+ * URLs.
792
+ *
793
+ * Vivliostyle resolves the subresource attributes it knows (`<img>`,
794
+ * `<iframe>`, …) correctly, but mangles relative URLs on elements it does not
795
+ * understand — `../tiles/model.glb` on an `<a-asset-item>` came back as
796
+ * `http://tiles/model.glb`. Absolute server URLs always resolve, so pages hand
797
+ * the viewer those instead. Standard elements are left alone (the viewer and
798
+ * the runtime URL shim already handle them); only dash-tagged elements, whose
799
+ * attributes the viewer cannot be trusted with, are rewritten.
800
+ */
801
+ export function rewriteCustomElementUrlsInDom(document: Document, documentDirUrl: string): boolean {
802
+ let changed = false;
803
+
804
+ const resolveOne = (url: string): string => {
805
+ const current = url.trim();
806
+ if (current === "" || current.startsWith("#") || current.startsWith("?") || current.startsWith("//")) return current;
807
+ // Absolute URLs (http:, data:, blob:, …) resolve as-is; root-relative ones
808
+ // are covered by the server-URL rewrite.
809
+ if (/^[a-z][a-z0-9+.-]*:/i.test(current) || current.startsWith("/")) return current;
810
+ try {
811
+ const resolved = new URL(current, documentDirUrl).href;
812
+ return resolved === current ? current : resolved;
813
+ } catch {
814
+ return current;
815
+ }
816
+ };
817
+
818
+ const apply = (el: Element, attr: "src" | "srcset"): void => {
819
+ const raw = el.getAttribute(attr);
820
+ if (raw === null) return;
821
+ if (attr === "src") {
822
+ const next = resolveOne(raw);
823
+ if (next === raw.trim() || next === raw) return;
824
+ el.setAttribute(attr, next);
825
+ changed = true;
826
+ return;
827
+ }
828
+ const kept = raw
829
+ .split(",")
830
+ .map((candidate) => candidate.trim())
831
+ .filter(Boolean)
832
+ .map((candidate) => {
833
+ const [url, ...descriptor] = candidate.split(/\s+/);
834
+ return [resolveOne(url), ...descriptor].join(" ");
835
+ });
836
+ const next = kept.join(", ");
837
+ if (next === raw) return;
838
+ el.setAttribute(attr, next);
839
+ changed = true;
840
+ };
841
+
842
+ for (const el of document.querySelectorAll("[src],[srcset]")) {
843
+ // Tag names are upper-cased in HTML documents; the dash test is case-free.
844
+ if (!el.tagName.includes("-")) continue;
845
+ apply(el, "src");
846
+ apply(el, "srcset");
847
+ }
848
+
849
+ return changed;
850
+ }
851
+
715
852
  /**
716
853
  * Returns a predicate that reports whether a root-relative path can be served
717
854
  * from one of the configured asset-base local roots.
@@ -846,10 +983,19 @@ export function buildPreviewHtml(
846
983
  const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
847
984
  if (changed) log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
848
985
 
986
+ // Same custom-element fix as the build path: the viewer mangles relative
987
+ // URLs on elements it does not understand. Only applied when the caller
988
+ // knows the document's directory on the server (see startPreview).
989
+ const customChanged =
990
+ options.documentBaseUrl === undefined || options.documentBaseUrl === null
991
+ ? false
992
+ : rewriteCustomElementUrlsInDom(document, options.documentBaseUrl);
993
+ if (customChanged) log.trace("buildPreviewHtml: resolved custom-element URLs → server URLs");
994
+
849
995
  const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
850
996
  if (dropped.length > 0) reportDroppedRemoteRefs(dropped);
851
997
 
852
- if (!changed && dropped.length === 0) {
998
+ if (!changed && !customChanged && dropped.length === 0) {
853
999
  log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
854
1000
  return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
855
1001
  }
@@ -908,6 +1054,10 @@ export function prepareInputHtmlForBuild(
908
1054
  const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
909
1055
  if (srvChanged) log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
910
1056
 
1057
+ const customBase = options.documentBaseUrl ?? `${serverBaseUrl}/`;
1058
+ const customChanged = rewriteCustomElementUrlsInDom(document, customBase);
1059
+ if (customChanged) log.trace("prepareInputHtmlForBuild: resolved custom-element URLs → server URLs", { customBase });
1060
+
911
1061
  const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
912
1062
 
913
1063
  const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
@@ -928,7 +1078,15 @@ export function prepareInputHtmlForBuild(
928
1078
  log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
929
1079
  }
930
1080
 
931
- if (!absChanged && !srvChanged && dropped.length === 0 && gone.length === 0 && options.settle == null && !wantsRuntime) {
1081
+ if (
1082
+ !absChanged &&
1083
+ !srvChanged &&
1084
+ !customChanged &&
1085
+ dropped.length === 0 &&
1086
+ gone.length === 0 &&
1087
+ options.settle == null &&
1088
+ !wantsRuntime
1089
+ ) {
932
1090
  log.trace("prepareInputHtmlForBuild: no changes, using original file");
933
1091
  return { vivliostyleInput: inputAbs, cleanup: () => undefined };
934
1092
  }
@@ -1233,7 +1391,40 @@ function buildProgram(): Command {
1233
1391
  .option("-o, --output <file>", "Output file path", "output.pdf")
1234
1392
  .option("--title <title>", "Document title (overrides the one in the source)")
1235
1393
  .option("--author <author>", "Document author")
1236
- .option("--language <lang>", "Document language tag (e.g. en, de, ja)", "de")
1394
+ .option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
1395
+ .option("--keywords <keywords>", "Document keywords, comma separated")
1396
+ .option(
1397
+ "--language <lang>",
1398
+ "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'"
1399
+ )
1400
+ .option(
1401
+ "--pdfa <level>",
1402
+ [
1403
+ "Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
1404
+ "an OutputIntent with an embedded ICC profile (bundled sRGB unless",
1405
+ "--icc-profile is given) and a file identifier are written.",
1406
+ "Levels: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4.",
1407
+ "This is a label only: the content is neither converted nor checked,",
1408
+ "so conformance of the content is the author's responsibility."
1409
+ ].join("\n ")
1410
+ )
1411
+ .option(
1412
+ "--pdfx <version>",
1413
+ [
1414
+ "Label the output PDF as PDF/X (ISO 15930): X-4 writes the",
1415
+ "identification metadata as XMP, X-1a:2003 into the information",
1416
+ "dictionary. Both embed the --icc-profile as the OutputIntent.",
1417
+ "Same label-only semantics as --pdfa."
1418
+ ].join("\n ")
1419
+ )
1420
+ .option(
1421
+ "--icc-profile <path>",
1422
+ [
1423
+ "ICC profile embedded as the PDF output intent, e.g. a print",
1424
+ "provider's profile. Required for --pdfx; --pdfa defaults to the",
1425
+ "bundled sRGB profile."
1426
+ ].join("\n ")
1427
+ )
1237
1428
  .option(
1238
1429
  "--static <mapping>",
1239
1430
  [
@@ -1298,8 +1489,10 @@ function buildProgram(): Command {
1298
1489
  "--wait-for-content [ms]",
1299
1490
  [
1300
1491
  "Delay pagination until the page's own async work finished: no request in",
1301
- "flight and the document height stable for --quiet-ms (default 400).",
1302
- "Without [ms] the hard limit of 25000ms applies; larger values are capped."
1492
+ "flight, no wasm compiling, no long task running and the document height",
1493
+ "stable for --quiet-ms (default 400). Pages with <script> wait",
1494
+ "automatically (deadline 10000ms); 0 disables, larger values capped at",
1495
+ "25000ms."
1303
1496
  ].join("\n ")
1304
1497
  )
1305
1498
  .option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
@@ -1345,7 +1538,10 @@ function buildProgram(): Command {
1345
1538
  " • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
1346
1539
  " • the browser prints that page to PDF, so canvases and iframes stay real content.",
1347
1540
  " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
1348
- " • --asset-base localBase is also a fallback root for CSS-referenced assets."
1541
+ " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
1542
+ " • PDF metadata (--title/--author/--subject/--keywords/--language) overrides",
1543
+ " • values read from the document or the publication manifest; language falls",
1544
+ " • back to 'de'. --pdfa/--pdfx label the output, they do not convert content."
1349
1545
  ].join("\n")
1350
1546
  );
1351
1547
  }
@@ -1379,16 +1575,24 @@ export function parseArgs(argv: string[]): {
1379
1575
  // Build runner helper
1380
1576
  // ---------------------------------------------------------------------------
1381
1577
 
1578
+ /** Metadata fields the CLI layer resolves before handing them to the renderer. */
1579
+ type MetadataFieldName = "title" | "author" | "subject" | "keywords" | "language";
1580
+
1581
+ /** ICC profile bytes with the name they get in the PDF's OutputIntent. */
1582
+ type IccProfile = { bytes: Uint8Array; name: string };
1583
+
1382
1584
  type RenderParams = {
1383
1585
  documentUrl: string;
1384
1586
  viewerPageUrl: string;
1385
1587
  outputAbs: string;
1386
- metaFields: Partial<Record<"title" | "author" | "language", string>>;
1588
+ metaFields: Partial<Record<MetadataFieldName, string>>;
1387
1589
  viewerParams: ViewerParams;
1388
1590
  timeoutMs?: number;
1389
1591
  waitForSettle: boolean;
1390
1592
  chromeExecutable?: string;
1391
1593
  canvasScale?: number;
1594
+ pdfLabel?: PdfLabel;
1595
+ iccProfile?: IccProfile;
1392
1596
  };
1393
1597
 
1394
1598
  async function runRender(params: RenderParams): Promise<void> {
@@ -1403,7 +1607,11 @@ async function runRender(params: RenderParams): Promise<void> {
1403
1607
  ...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
1404
1608
  ...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
1405
1609
  ...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
1406
- ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language })
1610
+ ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
1611
+ ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
1612
+ ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
1613
+ ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
1614
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
1407
1615
  };
1408
1616
 
1409
1617
  log.trace("renderPdf request", request);
@@ -1433,9 +1641,15 @@ function resolveInternalLogLevel(options: CliOptions): LogLevel {
1433
1641
  */
1434
1642
  const MAX_SETTLE_DEADLINE_MS = 25_000;
1435
1643
 
1644
+ /** Deadline for the automatic wait on script-driven pages (see below). */
1645
+ const AUTO_SETTLE_DEADLINE_MS = 10_000;
1646
+
1436
1647
  export function resolveSettleGate(options: CliOptions): SettleGate | null {
1437
1648
  const raw = options.waitForContent;
1438
1649
  if (raw === undefined || raw === false) return null;
1650
+ // Explicit 0 disables the wait — including the automatic one for pages
1651
+ // with scripts (see resolveEffectiveSettle).
1652
+ if (raw === "0") return null;
1439
1653
 
1440
1654
  const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
1441
1655
  if (!Number.isFinite(requested) || requested <= 0) throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
@@ -1449,6 +1663,80 @@ export function resolveSettleGate(options: CliOptions): SettleGate | null {
1449
1663
  };
1450
1664
  }
1451
1665
 
1666
+ /**
1667
+ * Settle gate that actually applies: an explicit `--wait-for-content` wins;
1668
+ * otherwise pages that run scripts wait automatically (charts, wasm, WebGL
1669
+ * would otherwise race pagination), static pages don't wait at all.
1670
+ */
1671
+ export function resolveEffectiveSettle(options: CliOptions, hasScripts: boolean): { gate: SettleGate | null; autoArmed: boolean } {
1672
+ const explicit = resolveSettleGate(options);
1673
+ if (explicit !== null || options.waitForContent !== undefined) return { gate: explicit, autoArmed: false };
1674
+ if (!hasScripts) return { gate: null, autoArmed: false };
1675
+
1676
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
1677
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0) throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
1678
+ return { gate: { quietMs: quietRaw, deadlineMs: AUTO_SETTLE_DEADLINE_MS }, autoArmed: true };
1679
+ }
1680
+
1681
+ // ---------------------------------------------------------------------------
1682
+ // PDF metadata + standards labeling resolution
1683
+ // ---------------------------------------------------------------------------
1684
+
1685
+ function describePdfLabel(label: PdfLabel): string {
1686
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
1687
+ }
1688
+
1689
+ /**
1690
+ * `--pdfa` / `--pdfx`: mutually exclusive standards labels for the output PDF.
1691
+ */
1692
+ export function resolvePdfLabel(options: Pick<CliOptions, "pdfa" | "pdfx">): PdfLabel | undefined {
1693
+ if (options.pdfa !== undefined && options.pdfx !== undefined) {
1694
+ throw new Error("--pdfa and --pdfx are mutually exclusive — choose one standard label");
1695
+ }
1696
+ if (options.pdfa !== undefined) return parsePdfaLabel(options.pdfa);
1697
+ if (options.pdfx !== undefined) return parsePdfxLabel(options.pdfx);
1698
+ return undefined;
1699
+ }
1700
+
1701
+ /**
1702
+ * `--icc-profile <path>`: the profile the OutputIntent embeds. PDF/X always
1703
+ * needs one; a PDF/A build without the flag embeds the bundled sRGB profile.
1704
+ */
1705
+ export function resolveIccProfile(options: Pick<CliOptions, "iccProfile">, label: PdfLabel | undefined): IccProfile | undefined {
1706
+ if (options.iccProfile !== undefined) {
1707
+ const path = resolve(options.iccProfile);
1708
+ if (!existsSync(path)) throw new Error(`--icc-profile file does not exist: ${path}`);
1709
+ return { bytes: readFileSync(path), name: basename(path) };
1710
+ }
1711
+ if (label === undefined) return undefined;
1712
+ if (label.kind === "pdfx") {
1713
+ throw new Error(`--pdfx ${label.version} requires --icc-profile <path>: PDF/X output intents carry an ICC profile`);
1714
+ }
1715
+ return loadDefaultIccProfile();
1716
+ }
1717
+
1718
+ /**
1719
+ * Document metadata for the PDF: the flags override values taken from the
1720
+ * input (HTML meta tags or a publication manifest); the language falls back
1721
+ * to "de" when no source provides one.
1722
+ */
1723
+ export function resolvePdfMetadata(
1724
+ options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language">,
1725
+ inputAbs: string,
1726
+ htmlMode: boolean
1727
+ ): DocumentMetadata & { language: string } {
1728
+ const cliFields = pickDefinedStrings(options, ["title", "author", "subject", "keywords", "language"]) as DocumentMetadata;
1729
+ let derived: DocumentMetadata | undefined;
1730
+ if (htmlMode) {
1731
+ derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
1732
+ } else if (/\.json$/i.test(inputAbs)) {
1733
+ derived = extractMetadataFromManifest(readFileSync(inputAbs, "utf-8"));
1734
+ if (derived === undefined) log.warn(`[metadata] ${inputAbs} is not a JSON publication manifest — no manifest metadata`);
1735
+ }
1736
+ log.trace("metadata (derived)", derived);
1737
+ return resolveMetadata(cliFields, derived);
1738
+ }
1739
+
1452
1740
  export async function execute(options: CliOptions, extraArgs: string[] = []): Promise<void> {
1453
1741
  log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
1454
1742
  log.trace("raw CLI options", options);
@@ -1550,10 +1838,21 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
1550
1838
  const extraConfig = parseExtraArgs(extraArgs);
1551
1839
  log.trace("extraConfig (parsed from -- args)", extraConfig);
1552
1840
 
1553
- const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
1841
+ const metaFields = resolvePdfMetadata(options, inputAbs, htmlMode);
1842
+ const pdfLabel = resolvePdfLabel(options);
1843
+ if (pdfLabel !== undefined) log.info(`[pdf] labeling the output as ${describePdfLabel(pdfLabel)}`);
1844
+ if (options.iccProfile !== undefined && pdfLabel === undefined) {
1845
+ log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
1846
+ }
1847
+ const iccProfile = resolveIccProfile(options, pdfLabel);
1554
1848
 
1555
1849
  const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
1556
- const settle = resolveSettleGate(options);
1850
+ // The wait arms automatically on script-driven pages: without it, charts,
1851
+ // wasm and WebGL race pagination and the PDF ships half-painted content.
1852
+ const hasScripts = htmlMode && new JSDOM(readFileSync(inputAbs, "utf-8")).window.document.querySelector("script") !== null;
1853
+ const { gate: settle, autoArmed } = resolveEffectiveSettle(options, hasScripts);
1854
+ if (autoArmed)
1855
+ log.info(`[wait] auto-armed for script-driven page (deadline ${AUTO_SETTLE_DEADLINE_MS}ms, disable with --wait-for-content 0)`);
1557
1856
  const htmlOptions: HtmlRewriteOptions = {
1558
1857
  allowRemote: fetchMissing,
1559
1858
  fetchMissing,
@@ -1656,7 +1955,9 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
1656
1955
  timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
1657
1956
  waitForSettle: htmlOptions.settle != null,
1658
1957
  chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
1659
- canvasScale
1958
+ canvasScale,
1959
+ ...(pdfLabel === undefined ? {} : { pdfLabel }),
1960
+ ...(iccProfile === undefined ? {} : { iccProfile })
1660
1961
  });
1661
1962
  } finally {
1662
1963
  htmlResource.cleanup();
@@ -1720,7 +2021,12 @@ export async function startPreview(
1720
2021
  log: (message) => log.info(message)
1721
2022
  });
1722
2023
 
1723
- const prepared = buildPreviewHtml(inputAbs, assetBases, htmlOptions);
2024
+ const prepared = buildPreviewHtml(inputAbs, assetBases, {
2025
+ ...htmlOptions,
2026
+ // The viewer is served next to the document, so custom-element URLs
2027
+ // resolve against the document's own directory (see siteDirectory below).
2028
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
2029
+ });
1724
2030
  entry.localPath = prepared.htmlPath;
1725
2031
 
1726
2032
  const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;