@projektemacher/vivliostyle-batch-cli 0.1.2 → 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.
@@ -1,182 +1,1960 @@
1
1
  import { Command } from 'commander';
2
- import { build, preview } from '@vivliostyle/cli';
3
- import { resolve, dirname, posix, join } from 'node:path';
4
- import { realpathSync, existsSync, readFileSync, mkdtempSync, writeFileSync, rmSync, statSync } from 'node:fs';
2
+ import { resolve, join, dirname, posix, basename, relative, isAbsolute, sep } from 'node:path';
3
+ import { readFileSync, statSync, existsSync, readdirSync, mkdirSync, writeFileSync, realpathSync, mkdtempSync, rmSync } from 'node:fs';
5
4
  import { fileURLToPath } from 'node:url';
6
- import { tmpdir } from 'node:os';
7
- import { lookup } from 'mime-types';
8
- import express from 'express';
9
- import serveStatic from 'serve-static';
5
+ import { platform, homedir, tmpdir } from 'node:os';
10
6
  import { JSDOM } from 'jsdom';
7
+ import log from 'loglevel';
8
+ import { createServer } from 'node:http';
9
+ import { lookup } from 'mime-types';
10
+ import puppeteer from 'puppeteer-core';
11
+ import { PDFDocument } from 'pdf-lib';
12
+ import { randomUUID, randomBytes } from 'node:crypto';
13
+ import * as mupdf from 'mupdf';
14
+ import { createRequire } from 'node:module';
15
+
16
+ // src/server.ts
17
+ // Copyright (c) 2026 Christian Mahnke
18
+ // Licensed under the MIT License.
19
+ /**
20
+ * The static server the renderer serves the document and its assets from.
21
+ *
22
+ * It replaces the Vite based server this package used before: everything is
23
+ * served by us, which is what makes the document's origin (and therefore the
24
+ * base URI of scripts the page runs) ours as well.
25
+ */
26
+ /** Paths the wrapper owns inside the site it serves. */
27
+ const VIEWER_PAGE_NAME = "__viv-viewer.html";
28
+ const VIEWER_LIB_PATH = "/__viv-viewer";
29
+ const SETTLE_GATE_PATH = "/__viv-settle";
30
+ const SETTLE_READY_PATH = "/__viv-settle-ready";
31
+ const TRANSPARENT_GIF = Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64");
32
+ /** CSP that lets the Vivliostyle viewer embed the served documents. */
33
+ function frameAncestors() {
34
+ return ["'self'", "http://localhost:*", "https://localhost:*", "http://127.0.0.1:*", "https://127.0.0.1:*"].join(" ");
35
+ }
36
+ /** Only redirect requests that ask for a file, never bare directory URLs. */
37
+ function looksLikeFileRequest(urlPath) {
38
+ const last = urlPath.slice(urlPath.lastIndexOf("/") + 1);
39
+ return last !== "" && last !== "/" && last.includes(".");
40
+ }
41
+ function decodeRequestPath(req) {
42
+ const raw = (req.url ?? "/").split("?")[0];
43
+ try {
44
+ return decodeURIComponent(raw);
45
+ }
46
+ catch {
47
+ return raw;
48
+ }
49
+ }
50
+ /**
51
+ * Resolves a request path against the explicit static map, then against the
52
+ * asset-base roots.
53
+ */
54
+ function resolveRequestPath(urlPath, staticMap, assetBases) {
55
+ // An exact entry whose file is gone (e.g. a derived mapping for an already
56
+ // virtual path) must not shadow a prefix mount that actually serves the file.
57
+ if (Object.hasOwn(staticMap, urlPath)) {
58
+ const localPath = resolve(staticMap[urlPath]);
59
+ if (existsSync(localPath))
60
+ return { localPath, remoteUrl: null };
61
+ }
62
+ for (const [virtual, localBase] of Object.entries(staticMap)) {
63
+ const prefix = virtual.endsWith("/") ? virtual : `${virtual}/`;
64
+ if (!urlPath.startsWith(prefix))
65
+ continue;
66
+ const localPath = resolve(localBase, urlPath.slice(prefix.length));
67
+ if (existsSync(localPath))
68
+ return { localPath, remoteUrl: null };
69
+ }
70
+ for (const ab of assetBases) {
71
+ const localPath = resolve(ab.localBase, urlPath.replace(/^\//, ""));
72
+ if (existsSync(localPath))
73
+ return { localPath, remoteUrl: null };
74
+ }
75
+ for (const ab of assetBases) {
76
+ if (!looksLikeFileRequest(urlPath))
77
+ continue;
78
+ return { localPath: null, remoteUrl: `${ab.urlBase.replace(/\/$/, "")}${urlPath}` };
79
+ }
80
+ return { localPath: null, remoteUrl: null };
81
+ }
82
+ function sendFile(res, localPath) {
83
+ let size;
84
+ try {
85
+ const stat = statSync(localPath);
86
+ if (!stat.isFile())
87
+ return false;
88
+ size = stat.size;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ const mime = lookup(localPath);
94
+ if (mime)
95
+ res.setHeader("Content-Type", mime);
96
+ res.setHeader("Content-Length", String(size));
97
+ res.setHeader("Cache-Control", "no-cache");
98
+ res.setHeader("Content-Security-Policy", `frame-ancestors ${frameAncestors()}`);
99
+ res.statusCode = 200;
100
+ res.end(readFileSync(localPath));
101
+ return true;
102
+ }
103
+ /**
104
+ * Serves the viewer page with its asset references made absolute, so that it
105
+ * can live in the document's directory without dragging its own assets along.
106
+ */
107
+ function buildViewerPage(viewerHtml, viewerLibPath = VIEWER_LIB_PATH) {
108
+ return viewerHtml
109
+ .replace(/(src|href)="(?!https?:|data:|\/)([^"]+)"/g, (_match, attr, path) => `${attr}="${viewerLibPath}/${path}"`)
110
+ .replace(/<base[^>]*>/g, "");
111
+ }
112
+ async function startStaticServer(options = {}, port = 0) {
113
+ const staticMap = options.staticMap ?? {};
114
+ const assetBases = options.assetBases ?? [];
115
+ const fetchMissing = options.fetchMissing === true;
116
+ const settle = options.settle ?? null;
117
+ const log = options.log ?? (() => undefined);
118
+ let released = false;
119
+ let holdStartedAt = 0;
120
+ let deadlineTimer = null;
121
+ let pending = [];
122
+ const release = (reason, detail) => {
123
+ if (released)
124
+ return;
125
+ released = true;
126
+ if (deadlineTimer !== null)
127
+ clearTimeout(deadlineTimer);
128
+ const waitedMs = holdStartedAt === 0 ? 0 : Date.now() - holdStartedAt;
129
+ options.onSettled?.({ reason, waitedMs, detail });
130
+ const waiting = pending;
131
+ pending = [];
132
+ for (const res of waiting) {
133
+ if (res.headersSent || res.writableEnded)
134
+ continue;
135
+ res.statusCode = 200;
136
+ res.setHeader("Content-Type", "image/gif");
137
+ res.setHeader("Content-Length", String(TRANSPARENT_GIF.length));
138
+ res.end(TRANSPARENT_GIF);
139
+ }
140
+ };
141
+ const handleSettle = (urlPath, query, res) => {
142
+ if (settle === null)
143
+ return false;
144
+ if (urlPath === SETTLE_READY_PATH) {
145
+ const detail = {};
146
+ for (const key of [
147
+ "reason",
148
+ "ms",
149
+ "pending",
150
+ "frames",
151
+ "canvases",
152
+ "containers",
153
+ "mutations",
154
+ "dpr",
155
+ "painted",
156
+ "ready",
157
+ "longtasks"
158
+ ]) {
159
+ const value = query.get(key);
160
+ if (value === null)
161
+ continue;
162
+ detail[key] = /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
163
+ }
164
+ res.statusCode = 204;
165
+ res.end();
166
+ release("settled", detail);
167
+ return true;
168
+ }
169
+ if (urlPath !== SETTLE_GATE_PATH)
170
+ return false;
171
+ if (released) {
172
+ release("deadline");
173
+ return true;
174
+ }
175
+ if (holdStartedAt === 0) {
176
+ holdStartedAt = Date.now();
177
+ deadlineTimer = setTimeout(() => release("deadline"), settle.deadlineMs);
178
+ deadlineTimer.unref?.();
179
+ }
180
+ pending.push(res);
181
+ res.on("close", () => {
182
+ pending = pending.filter((candidate) => candidate !== res);
183
+ });
184
+ return true;
185
+ };
186
+ const handler = (req, res) => {
187
+ const urlPath = decodeRequestPath(req);
188
+ const query = new URLSearchParams((req.url ?? "").split("?")[1] ?? "");
189
+ // Every request the page makes transits here: log it (path + status) so
190
+ // render problems become traceable from the per-page logs.
191
+ res.on("finish", () => {
192
+ log(`${urlPath} ${res.statusCode}`);
193
+ });
194
+ if (handleSettle(urlPath, query, res))
195
+ return;
196
+ // The viewer page lives next to the document so that scripts the page runs
197
+ // resolve relative URLs against the document's directory.
198
+ if (urlPath.endsWith(`/${VIEWER_PAGE_NAME}`)) {
199
+ const html = options.viewerFilePath === null || options.viewerFilePath === undefined ? "" : readFileSync(options.viewerFilePath, "utf-8");
200
+ if (html !== "") {
201
+ res.statusCode = 200;
202
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
203
+ res.setHeader("Cache-Control", "no-cache");
204
+ res.end(buildViewerPage(html));
205
+ return;
206
+ }
207
+ }
208
+ if (options.viewerLibDir != null && urlPath.startsWith(`${VIEWER_LIB_PATH}/`)) {
209
+ const relative = urlPath.slice(VIEWER_LIB_PATH.length + 1);
210
+ if (sendFile(res, resolve(options.viewerLibDir, relative)))
211
+ return;
212
+ }
213
+ const entry = options.entry;
214
+ if (entry !== null && entry !== undefined && entry.localPath !== null && urlPath === entry.sitePath) {
215
+ if (sendFile(res, resolve(entry.localPath)))
216
+ return;
217
+ }
218
+ const { localPath, remoteUrl } = resolveRequestPath(urlPath, staticMap, assetBases);
219
+ if (localPath !== null && sendFile(res, localPath))
220
+ return;
221
+ if (remoteUrl !== null && fetchMissing) {
222
+ log(`[fetch] ${urlPath} → ${remoteUrl}`);
223
+ res.statusCode = 302;
224
+ res.setHeader("Location", remoteUrl);
225
+ res.end();
226
+ return;
227
+ }
228
+ res.statusCode = 404;
229
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
230
+ res.end("Not found");
231
+ };
232
+ const server = createServer(handler);
233
+ await new Promise((resolvePromise, reject) => {
234
+ server.once("error", reject);
235
+ server.listen(port, "127.0.0.1", () => {
236
+ server.off("error", reject);
237
+ resolvePromise();
238
+ });
239
+ });
240
+ const address = server.address();
241
+ const boundPort = typeof address === "object" && address !== null ? address.port : port;
242
+ return {
243
+ baseUrl: `http://127.0.0.1:${boundPort}`,
244
+ close: () => new Promise((resolvePromise) => {
245
+ release("deadline");
246
+ server.closeAllConnections?.();
247
+ server.close(() => resolvePromise());
248
+ })
249
+ };
250
+ }
251
+
252
+ // src/render/chrome.ts
253
+ // Copyright (c) 2026 Christian Mahnke
254
+ // Licensed under the MIT License.
255
+ /**
256
+ * Locates a Chrome/Chromium binary for the renderer.
257
+ *
258
+ * `--executable-browser` wins, then a binary installed by @puppeteer/browsers
259
+ * (the same cache Vivliostyle CLI used), then the usual system locations.
260
+ */
261
+ const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
262
+ const MAC_CHROMIUM = "/Applications/Chromium.app/Contents/MacOS/Chromium";
263
+ const LINUX_PATHS = [
264
+ "/usr/bin/google-chrome",
265
+ "/usr/bin/google-chrome-stable",
266
+ "/usr/bin/chromium",
267
+ "/usr/bin/chromium-browser",
268
+ "/snap/bin/chromium"
269
+ ];
270
+ /** Directory @puppeteer/browsers installs into. */
271
+ function puppeteerCacheDir() {
272
+ return process.env.PUPPETEER_CACHE_DIR ?? join(homedir(), ".cache", "puppeteer");
273
+ }
274
+ /** Finds an installed browser in the @puppeteer/browsers cache. */
275
+ function findCachedBrowser() {
276
+ const root = join(puppeteerCacheDir(), "chrome");
277
+ if (!existsSync(root))
278
+ return null;
279
+ const candidates = [];
280
+ for (const build of readdirSync(root)) {
281
+ const buildDir = join(root, build);
282
+ let stat;
283
+ try {
284
+ stat = statSync(buildDir);
285
+ }
286
+ catch {
287
+ continue;
288
+ }
289
+ if (!stat.isDirectory())
290
+ continue;
291
+ for (const flavour of readdirSync(buildDir)) {
292
+ candidates.push(join(buildDir, flavour, "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join(buildDir, flavour, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join(buildDir, flavour, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join(buildDir, flavour, "chrome-linux64", "chrome"), join(buildDir, flavour, "chrome-headless-shell-linux64", "chrome-headless-shell"));
293
+ }
294
+ }
295
+ return candidates.find((candidate) => existsSync(candidate)) ?? null;
296
+ }
297
+ function systemBrowser() {
298
+ const candidates = platform() === "darwin" ? [MAC_CHROME, MAC_CHROMIUM] : LINUX_PATHS;
299
+ return candidates.find((candidate) => existsSync(candidate)) ?? null;
300
+ }
301
+ /**
302
+ * Path of the browser to launch, or `null` when none is installed.
303
+ */
304
+ function resolveBrowserExecutable(explicit) {
305
+ const candidates = [explicit, process.env.CHROME_PATH, findCachedBrowser(), systemBrowser()];
306
+ for (const candidate of candidates) {
307
+ if (candidate !== undefined && candidate !== null && candidate !== "" && existsSync(candidate))
308
+ return candidate;
309
+ }
310
+ return null;
311
+ }
312
+ /**
313
+ * Chrome flags for headless rendering.
314
+ *
315
+ * SwiftShader keeps WebGL (three.js, A-Frame) working without a GPU, and the
316
+ * ANGLE/WebGPU flags extend that to WebGPU on headless machines (best effort:
317
+ * pages report `navigator.gpu == null` when the build still lacks it).
318
+ * `--disable-web-security` lets the page load the cross-origin embeds it shows.
319
+ */
320
+ function chromeArgs(extra = []) {
321
+ return [
322
+ "--disable-field-trial-config",
323
+ "--disable-back-forward-cache",
324
+ "--disable-component-update",
325
+ "--no-default-browser-check",
326
+ "--disable-features=AcceptCHFrame,AvoidUnnecessaryBeforeUnloadCheckSync,DestroyProfileInBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,MediaRouter,PaintHolding,ThirdPartyPartitioning,Translate,AutofillServerCommunication,DestroyProfileOnBrowserClose",
327
+ "--no-service-autorun",
328
+ "--enable-unsafe-swiftshader",
329
+ "--use-angle=swiftshader",
330
+ "--enable-unsafe-webgpu",
331
+ "--disable-web-security",
332
+ "--hide-scrollbars",
333
+ "--mute-audio",
334
+ "--force-device-scale-factor=1",
335
+ ...extra
336
+ ];
337
+ }
338
+
339
+ // src/render/xmp.ts
340
+ const NS = {
341
+ rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
342
+ dc: "http://purl.org/dc/elements/1.1/",
343
+ pdf: "http://ns.adobe.com/pdf/1.3/",
344
+ xmp: "http://ns.adobe.com/xap/1.0/",
345
+ xmpMM: "http://ns.adobe.com/xap/1.0/mm/",
346
+ pdfaid: "http://www.aiim.org/pdfa/ns/id/",
347
+ pdfxid: "http://www.npes.org/pdfx/ns/id/"
348
+ };
349
+ /** XMP Specification Part 1 (April 2012), 8.2.1.2 date form. */
350
+ function toXmpDate(date) {
351
+ const pad = (value, length = 2) => String(value).padStart(length, "0");
352
+ return (`${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}` +
353
+ `T${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}Z`);
354
+ }
355
+ // ISO 32000-1:2008, 7.9.4 writes a date as D:YYYYMMDDHHmmSSOHH'mm, the form
356
+ // Skia in Chromium writes. The offset is kept, not normalized to UTC, so the
357
+ // XMP packet shows the same instant the information dictionary shows.
358
+ const PDF_DATE = /^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:Z|([+\-])(\d{2})'(\d{2})'?)$/;
359
+ /** Reformats a PDF date string as an XMP date; `undefined` when not one. */
360
+ function pdfDateToXmpDate(value) {
361
+ const match = PDF_DATE.exec(value);
362
+ if (match === null)
363
+ return undefined;
364
+ const [, year, month, day, hour, minute, second, sign, offsetHour, offsetMinute] = match;
365
+ const zone = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
366
+ return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
367
+ }
368
+ function xmlEscape(text) {
369
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
370
+ }
371
+ /** dc:title/dc:description: a language alternative with the x-default entry. */
372
+ function languageAlternative(text) {
373
+ return ["<rdf:Alt>", ` <rdf:li xml:lang="x-default">${xmlEscape(text)}</rdf:li>`, "</rdf:Alt>"].join("\n ");
374
+ }
375
+ /** dc:creator: an ordered sequence; ";" separates individual authors. */
376
+ function creatorSequence(author) {
377
+ const names = author
378
+ .split(";")
379
+ .map((name) => name.trim())
380
+ .filter((name) => name !== "");
381
+ const items = (names.length === 0 ? [author] : names).map((name) => ` <rdf:li>${xmlEscape(name)}</rdf:li>`);
382
+ return ["<rdf:Seq>", ...items, "</rdf:Seq>"].join("\n ");
383
+ }
384
+ /**
385
+ * Builds the XMP packet for the document. Only defined fields are written;
386
+ * the packet wrapper uses the fixed header id packet scanners look for
387
+ * (XMP Part 1, 7.3.2 makes the wrapper optional, Acrobat rejects its absence).
388
+ */
389
+ function buildXmpPacket(fields, label) {
390
+ const properties = [];
391
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-4") {
392
+ properties.push(`<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>`);
393
+ }
394
+ if (fields.title !== undefined) {
395
+ properties.push(`<dc:title>\n ${languageAlternative(fields.title)}\n </dc:title>`);
396
+ }
397
+ if (fields.author !== undefined) {
398
+ properties.push(`<dc:creator>\n ${creatorSequence(fields.author)}\n </dc:creator>`);
399
+ }
400
+ if (fields.subject !== undefined) {
401
+ properties.push(`<dc:description>\n ${languageAlternative(fields.subject)}\n </dc:description>`);
402
+ }
403
+ if (fields.keywords !== undefined) {
404
+ properties.push(`<pdf:Keywords>${xmlEscape(fields.keywords)}</pdf:Keywords>`);
405
+ }
406
+ if (fields.producer !== undefined) {
407
+ properties.push(`<pdf:Producer>${xmlEscape(fields.producer)}</pdf:Producer>`);
408
+ }
409
+ if (fields.trapped !== undefined) {
410
+ properties.push(`<pdf:Trapped>${fields.trapped}</pdf:Trapped>`);
411
+ }
412
+ if (fields.creatorTool !== undefined) {
413
+ properties.push(`<xmp:CreatorTool>${xmlEscape(fields.creatorTool)}</xmp:CreatorTool>`);
414
+ }
415
+ if (fields.createDate !== undefined) {
416
+ properties.push(`<xmp:CreateDate>${fields.createDate}</xmp:CreateDate>`);
417
+ }
418
+ if (fields.modifyDate !== undefined) {
419
+ properties.push(`<xmp:ModifyDate>${fields.modifyDate}</xmp:ModifyDate>`);
420
+ }
421
+ if (fields.metadataDate !== undefined) {
422
+ properties.push(`<xmp:MetadataDate>${fields.metadataDate}</xmp:MetadataDate>`);
423
+ }
424
+ if (fields.documentId !== undefined) {
425
+ properties.push(`<xmpMM:DocumentID>${xmlEscape(fields.documentId)}</xmpMM:DocumentID>`, `<xmpMM:VersionID>1</xmpMM:VersionID>`, `<xmpMM:RenditionClass>default</xmpMM:RenditionClass>`);
426
+ }
427
+ if (label !== undefined && label.kind === "pdfa") {
428
+ properties.push(`<pdfaid:part>${label.part}</pdfaid:part>`);
429
+ // PDF/A-4 (ISO 19005-4) identifies through the part value alone; the
430
+ // conformance levels a/b/u exist for parts 1 to 3 only.
431
+ if (label.part !== "4" && label.conformance !== undefined) {
432
+ properties.push(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`);
433
+ }
434
+ }
435
+ const body = [
436
+ `<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>`,
437
+ `<x:xmpmeta xmlns:x="adobe:ns:meta/">`,
438
+ ` <rdf:RDF xmlns:rdf="${NS.rdf}">`,
439
+ ` <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}">`,
440
+ ...properties.map((property) => ` ${property}`),
441
+ ` </rdf:Description>`,
442
+ ` </rdf:RDF>`,
443
+ `</x:xmpmeta>`,
444
+ `<?xpacket end="w"?>`
445
+ ].join("\n");
446
+ // XML 1.0 (Fifth Edition), 2.11: a processor turns a literal CR into LF
447
+ // before parsing, so a CR in a value survives only as a character reference.
448
+ return `${body.replaceAll("\r", "&#xD;")}\n`;
449
+ }
11
450
 
12
- const validFormats = ["pdf", "epub", "webpub"];
451
+ // src/render/pdf-postprocess.ts
452
+ // Copyright (c) 2026 Christian Mahnke
453
+ // Licensed under the MIT License.
454
+ /**
455
+ * PDF post-processing: document metadata, XMP and standards labeling.
456
+ *
457
+ * Runs on the PDF bytes Chrome printed (Skia output) and applies:
458
+ * - document information entries (title, author, subject, keywords, producer, creator)
459
+ * - the catalog /Lang entry for the document language
460
+ * - an XMP metadata stream kept consistent with the information dictionary
461
+ * - PDF/A or PDF/X identification: XMP identification properties, an
462
+ * OutputIntent with an embedded ICC profile and a stable file identifier
463
+ *
464
+ * This is a "label, don't convert" step — the same semantics vivliostyle-cli
465
+ * gives its PDF/X option: the content is neither converted nor checked, so
466
+ * conformance of the content is the author's responsibility. Verify with
467
+ * veraPDF (or a print provider's preflight) when it matters.
468
+ *
469
+ * The editing follows vivliostyle-cli's mupdf-based post-processing
470
+ * (src/output/pdfx.ts, pdf-document.ts, pdf-version.ts at v11.4).
471
+ */
472
+ /**
473
+ * Tracks MuPDF's native objects and destroys them in reverse order. Every
474
+ * PDFObject/Buffer/ColorSpace keeps native memory behind the wasm binding,
475
+ * which is only reclaimed on an explicit destroy.
476
+ */
477
+ function createScope() {
478
+ const tracked = [];
479
+ return {
480
+ track(value) {
481
+ tracked.push(value);
482
+ return value;
483
+ },
484
+ dispose() {
485
+ while (tracked.length > 0) {
486
+ try {
487
+ tracked.pop()?.destroy();
488
+ }
489
+ catch {
490
+ // Cleanup is best-effort; a failed destroy must not mask the result.
491
+ }
492
+ }
493
+ }
494
+ };
495
+ }
496
+ // The catalog /Version is written for every required version; MuPDF's wasm
497
+ // binding provides no API for the header version and a full save derives the
498
+ // header from the catalog entry (same approach as vivliostyle-cli).
499
+ function setMinimumPdfVersion(document, minimumVersion, scope) {
500
+ if (document.getVersion() >= minimumVersion)
501
+ return;
502
+ const trailer = scope.track(document.getTrailer());
503
+ const catalog = scope.track(trailer.get("Root"));
504
+ const version = scope.track(document.newName(`${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`));
505
+ catalog.put("Version", version);
506
+ }
507
+ function readInfoString(info, key, scope) {
508
+ const value = scope.track(info.get(key));
509
+ return value.isString() ? value.asString() : undefined;
510
+ }
511
+ function readTrapped(info, scope) {
512
+ const trapped = scope.track(info.get("Trapped"));
513
+ return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
514
+ }
515
+ function openPdfDocument(pdf, scope) {
516
+ // openDocument returns the Document base type; a PDF input yields a PDFDocument.
517
+ const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf");
518
+ return scope.track(document);
519
+ }
520
+ /**
521
+ * Runs `fn` with freshly fetched catalog handles. MuPDF replaces the trailer
522
+ * dict whenever an information entry is written through `setMetaData`, and a
523
+ * PDFObject handle held across such a write ends up detached from the
524
+ * document — edits into it silently disappear on save. Every mutation
525
+ * therefore re-fetches its handles right before it runs.
526
+ */
527
+ function withCatalog(document, scope, fn) {
528
+ const trailer = scope.track(document.getTrailer());
529
+ const catalog = scope.track(trailer.get("Root"));
530
+ return fn(catalog);
531
+ }
532
+ /** Runs `fn` with a freshly fetched information dictionary handle. */
533
+ function withInfo(document, scope, fn) {
534
+ const trailer = scope.track(document.getTrailer());
535
+ const info = scope.track(trailer.get("Info"));
536
+ return fn(info);
537
+ }
538
+ /** Runs `fn` with a freshly fetched trailer handle. */
539
+ function withTrailer(document, scope, fn) {
540
+ return fn(scope.track(document.getTrailer()));
541
+ }
542
+ /**
543
+ * Applies metadata and standards labeling to a printed PDF.
544
+ *
545
+ * Producer/Creator are always stamped (the wrapper owns them), so a build
546
+ * without explicit metadata still gets a consistent information dictionary
547
+ * and XMP packet. Dates come from what Skia wrote: CreationDate is kept,
548
+ * ModifyDate falls back to it, exactly like vivliostyle-cli handles output
549
+ * from print backends that skip the modification date.
550
+ */
551
+ async function postProcessPdf(pdf, options) {
552
+ const scope = createScope();
553
+ try {
554
+ const { metadata, label } = options;
555
+ const document = openPdfDocument(pdf, scope);
556
+ // ── What the print backend already wrote ────────────────────────────────
557
+ const { creationDate, modifyDate, trapped } = withInfo(document, scope, (info) => ({
558
+ creationDate: readInfoString(info, "CreationDate", scope),
559
+ modifyDate: readInfoString(info, "ModDate", scope),
560
+ trapped: readTrapped(info, scope)
561
+ }));
562
+ const createDateXmp = (creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined) ?? toXmpDate(new Date());
563
+ // Acrobat's preflight requires xmp:ModifyDate/MetadataDate; backends like
564
+ // Firefox's cairo skip them, so they take the creation date then.
565
+ const modifyDateXmp = (modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined) ?? createDateXmp;
566
+ // ── Document information entries ────────────────────────────────────────
567
+ document.setMetaData("info:Producer", metadata.producer);
568
+ document.setMetaData("info:Creator", metadata.creator);
569
+ if (metadata.title !== undefined)
570
+ document.setMetaData("info:Title", metadata.title);
571
+ if (metadata.author !== undefined)
572
+ document.setMetaData("info:Author", metadata.author);
573
+ if (metadata.subject !== undefined)
574
+ document.setMetaData("info:Subject", metadata.subject);
575
+ if (metadata.keywords !== undefined)
576
+ document.setMetaData("info:Keywords", metadata.keywords);
577
+ // ── Catalog language ────────────────────────────────────────────────────
578
+ const language = metadata.language;
579
+ if (language !== undefined && language !== "") {
580
+ withCatalog(document, scope, (catalog) => {
581
+ catalog.put("Lang", scope.track(document.newString(language)));
582
+ });
583
+ setMinimumPdfVersion(document, 14, scope);
584
+ }
585
+ // ── XMP metadata stream ─────────────────────────────────────────────────
586
+ const xmp = buildXmpPacket({
587
+ title: metadata.title,
588
+ author: metadata.author,
589
+ subject: metadata.subject,
590
+ keywords: metadata.keywords,
591
+ producer: metadata.producer,
592
+ creatorTool: metadata.creator,
593
+ createDate: createDateXmp,
594
+ modifyDate: modifyDateXmp,
595
+ metadataDate: toXmpDate(new Date()),
596
+ documentId: `uuid:${randomUUID()}`,
597
+ ...(label !== undefined && label.kind === "pdfx" && label.version === "X-4" ? { trapped } : {})
598
+ }, label);
599
+ withCatalog(document, scope, (catalog) => {
600
+ const xmpBuffer = scope.track(new mupdf.Buffer(xmp));
601
+ const metadataStream = scope.track(document.addStream(xmpBuffer, { Type: "Metadata", Subtype: "XML" }));
602
+ catalog.put("Metadata", metadataStream);
603
+ });
604
+ // ── OutputIntent with the embedded ICC profile ──────────────────────────
605
+ if (label !== undefined) {
606
+ const profile = options.iccProfile;
607
+ if (profile === undefined) {
608
+ throw new Error(label.kind === "pdfx"
609
+ ? "PDF/X labeling requires an ICC profile for the OutputIntent (--icc-profile)."
610
+ : "PDF/A labeling requires an ICC profile for the OutputIntent.");
611
+ }
612
+ const profileName = options.iccProfileName ?? "output-intent.icc";
613
+ withCatalog(document, scope, (catalog) => {
614
+ const profileBuffer = scope.track(new mupdf.Buffer(profile));
615
+ const colorSpace = scope.track(new mupdf.ColorSpace(profileBuffer, profileName));
616
+ const profileStream = scope.track(document.addStream(profileBuffer, { N: colorSpace.getNumberOfComponents() }));
617
+ const identifier = scope.track(document.newString("Custom"));
618
+ const profileInfo = scope.track(document.newString(profileName));
619
+ // ISO 32000-1:2008, 7.7.2/14.11.5: OutputConditionIdentifier may be
620
+ // "Custom"; Info and DestOutputProfile are required for nonstandard
621
+ // production conditions.
622
+ const intent = scope.track(document.addObject({
623
+ Type: "OutputIntent",
624
+ S: label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX",
625
+ OutputConditionIdentifier: identifier,
626
+ Info: profileInfo,
627
+ DestOutputProfile: profileStream
628
+ }));
629
+ catalog.put("OutputIntents", [intent]);
630
+ });
631
+ setMinimumPdfVersion(document, 14, scope);
632
+ }
633
+ // ── Standards identification outside the XMP packet ─────────────────────
634
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
635
+ // PDF/X-1a:2003 identification lives in the information dictionary, not
636
+ // in XMP (XMP identification is the PDF/X-4 form).
637
+ document.setMetaData("info:GTS_PDFXVersion", "PDF/X-1a:2003");
638
+ withInfo(document, scope, (info) => {
639
+ info.put("Trapped", scope.track(document.newName(trapped)));
640
+ // Acrobat's PDF/X-1a:2003 preflight requires ModDate, which some print
641
+ // backends never write; it takes the creation date then.
642
+ if (modifyDate === undefined && creationDate !== undefined) {
643
+ info.put("ModDate", scope.track(document.newString(creationDate)));
644
+ }
645
+ });
646
+ }
647
+ // A stable file identifier is required for PDF/A and PDF/X. Written last,
648
+ // against a trailer handle fetched after every information entry write.
649
+ if (label !== undefined) {
650
+ withTrailer(document, scope, (trailer) => {
651
+ const existingId = scope.track(trailer.get("ID"));
652
+ if (!existingId.isArray()) {
653
+ const bytes = randomBytes(16);
654
+ trailer.put("ID", [document.newByteString(bytes), document.newByteString(bytes)]);
655
+ }
656
+ });
657
+ }
658
+ if (!document.hasUnsavedChanges())
659
+ return pdf;
660
+ const output = scope.track(document.saveToBuffer("compress"));
661
+ // Copy so the data stays valid after the buffer is destroyed.
662
+ return new Uint8Array(output.asUint8Array());
663
+ }
664
+ finally {
665
+ scope.dispose();
666
+ }
667
+ }
668
+ /**
669
+ * Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
670
+ * The profile ships unchanged from the ICC ("sRGB_v4_ICC_preference.icc"); its
671
+ * license permits redistribution provided the file, including its embedded
672
+ * copyright notice tag, is not modified (https://www.color.org/srgbprofiles.xalter).
673
+ */
674
+ function loadDefaultIccProfile() {
675
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
676
+ const candidates = [
677
+ // Source layout (vitest, direct TS execution).
678
+ join(moduleDir, "srgb.icc"),
679
+ // Bundled layout: dist/vivliostyle-batch-cli.js ships next to src/.
680
+ resolve(moduleDir, "../src/render/srgb.icc")
681
+ ];
682
+ for (const candidate of candidates) {
683
+ if (existsSync(candidate)) {
684
+ return { bytes: readFileSync(candidate), name: "sRGB_v4_ICC_preference.icc" };
685
+ }
686
+ }
687
+ throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
688
+ }
689
+
690
+ // src/render/pdf.ts
691
+ // Copyright (c) 2026 Christian Mahnke
692
+ // Licensed under the MIT License.
693
+ /**
694
+ * PDF rendering on top of the Vivliostyle viewer and Chrome's print-to-PDF.
695
+ *
696
+ * The viewer page is served by our own static server (see src/server.ts), so
697
+ * the document's origin — and therefore the base URI of the scripts the page
698
+ * runs — is the site we serve, not an internal viewer base.
699
+ *
700
+ * Printed pages run through the post-processing step (see
701
+ * src/render/pdf-postprocess.ts), which stamps the document metadata and
702
+ * applies the requested PDF/A or PDF/X labeling.
703
+ */
704
+ /** URL of the viewer page, with the publication and layout parameters. */
705
+ function buildViewerUrl(viewerPageUrl, params) {
706
+ const parts = [];
707
+ for (const [key, value] of Object.entries(params)) {
708
+ if (value === undefined || value === "")
709
+ continue;
710
+ parts.push(`${key}=${String(value).replaceAll("&", "%26")}`);
711
+ }
712
+ const query = parts.join("&");
713
+ return query === "" ? viewerPageUrl : `${viewerPageUrl}#${query}`;
714
+ }
715
+ const DEFAULT_TIMEOUT_MS = 300_000;
716
+ /** The wrapper owns the producer/creator entries of every PDF it prints. */
717
+ const TOOL_IDENTITY = "vivliostyle-batch-cli";
718
+ function pdfMetadata(request) {
719
+ return {
720
+ ...(request.title === undefined ? {} : { title: request.title }),
721
+ ...(request.author === undefined ? {} : { author: request.author }),
722
+ ...(request.subject === undefined ? {} : { subject: request.subject }),
723
+ ...(request.keywords === undefined ? {} : { keywords: request.keywords }),
724
+ ...(request.language === undefined ? {} : { language: request.language }),
725
+ creator: TOOL_IDENTITY,
726
+ producer: TOOL_IDENTITY
727
+ };
728
+ }
729
+ /**
730
+ * Runs inside one frame (viewer window or a document/iframe within it):
731
+ * scrolls JS-painted elements into view so out-of-process iframes rasterize,
732
+ * reports GPU capabilities and canvas sizes, and — when the page exposes the
733
+ * `window.__vivResize(factor)` hook — redraws at HiDPI backing resolution.
734
+ *
735
+ * Blindly rewriting `canvas.width` here would blank WebGL contexts without
736
+ * `preserveDrawingBuffer`, so generic canvases are left for the page to redraw
737
+ * via the dispatched `resize` event; only the explicit hook changes pixels.
738
+ */
739
+ function buildFrameProbeScript(factor) {
740
+ return `(async function(factor){
741
+ function nextFrame(){ return new Promise(function(r){ requestAnimationFrame(function(){ requestAnimationFrame(r); }); }); }
742
+ var canvases = Array.prototype.slice.call(document.querySelectorAll("canvas"));
743
+ var iframes = Array.prototype.slice.call(document.querySelectorAll("iframe"));
744
+ canvases.forEach(function(c){ try{ c.scrollIntoView({block:"nearest"}); }catch(e){} });
745
+ iframes.forEach(function(f){ try{ f.scrollIntoView({block:"nearest"}); }catch(e){} });
746
+ function canvasSizes(){
747
+ return Array.prototype.slice.call(document.querySelectorAll("canvas")).map(function(c){
748
+ return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);
749
+ }).join(",");
750
+ }
751
+ var resized = null;
752
+ if (factor > 1 && typeof window.__vivResize === "function") {
753
+ try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
754
+ }
755
+ try { window.dispatchEvent(new Event("resize")); } catch(e){}
756
+ // Bridge the viewer's broken page lifecycle. A-Frame scenes can end up
757
+ // loaded-but-never-playing in the paginated tree (render loop, default
758
+ // lights and asset loads all missed their window) while the same page
759
+ // renders fine in a real browser. Start the scene's own loop and give
760
+ // collapsed scenes a box (their display:block stylesheet does not reach
761
+ // the re-parented tree, so unsized unknown elements stay inline).
762
+ try {
763
+ var bridgeScenes = document.querySelectorAll("a-scene");
764
+ for (var bi = 0; bi < bridgeScenes.length; bi++) {
765
+ var bridgeScene = bridgeScenes[bi];
766
+ if (!bridgeScene.isPlaying && typeof bridgeScene.play === "function") {
767
+ try { bridgeScene.play(); } catch (e) {}
768
+ }
769
+ if (bridgeScene.clientWidth === 0 || bridgeScene.clientHeight === 0) {
770
+ var sized = bridgeScene.parentElement;
771
+ while (sized && (sized.clientWidth === 0 || sized.clientHeight === 0)) sized = sized.parentElement;
772
+ if (sized) {
773
+ bridgeScene.style.display = "block";
774
+ bridgeScene.style.width = sized.clientWidth + "px";
775
+ bridgeScene.style.height = sized.clientHeight + "px";
776
+ if (typeof bridgeScene.resize === "function") bridgeScene.resize();
777
+ }
778
+ }
779
+ }
780
+ await nextFrame();
781
+ } catch(e){}
782
+ // Give each scene what it needs to render like the browser does, then
783
+ // materialize its WebGL canvas into a 2D overlay (2D canvases always
784
+ // survive print-to-PDF): re-kick unloaded assets, swap unlit materials for
785
+ // flat ones when no lights exist, render, and blit synchronously.
786
+ var materialized = 0;
787
+ var sceneDiag = "";
788
+ try {
789
+ var scenes = document.querySelectorAll("a-scene");
790
+ for (var si = 0; si < scenes.length; si++) {
791
+ var sceneEl = scenes[si];
792
+ // The viewer clones scenes into its page boxes; only the VISIBLE one
793
+ // (with a box) is what the PDF will show. The hidden original's render
794
+ // would materialize nothing.
795
+ if (!(sceneEl.clientWidth > 0 && sceneEl.clientHeight > 0)) continue;
796
+ if (!sceneEl.renderer || !sceneEl.camera) continue;
797
+ try {
798
+ var gltfEl = sceneEl.querySelector("[gltf-model]");
799
+ if (gltfEl) {
800
+ var gmObj = gltfEl.object3D;
801
+ sceneDiag += " gmKids=" + gmObj.children.length + "/" + (gltfEl.components["gltf-model"] ? String(gltfEl.components["gltf-model"].model !== null) : "nocomp");
802
+ }
803
+ sceneDiag += " tree=" + sceneEl.object3D.children.map(function (c) { return c.type + (c.children ? ":" + c.children.length : ""); }).join("|").slice(0, 110);
804
+ } catch (e) {
805
+ sceneDiag += " diagErr " + String(e).slice(0, 50);
806
+ }
807
+ try {
808
+ var assetItems = sceneEl.querySelectorAll("a-asset-item");
809
+ var assetWaits = [];
810
+ for (var ai = 0; ai < assetItems.length; ai++) {
811
+ var assetEl = assetItems[ai];
812
+ if (assetEl.hasLoaded) continue;
813
+ assetWaits.push(
814
+ new Promise(function (resolve) {
815
+ var settled = false;
816
+ var finish = function () {
817
+ if (settled) return;
818
+ settled = true;
819
+ resolve();
820
+ };
821
+ assetEl.addEventListener("loaded", finish, { once: true });
822
+ assetEl.addEventListener("error", finish, { once: true });
823
+ setTimeout(finish, 8000);
824
+ var src = assetEl.getAttribute("src");
825
+ if (src) assetEl.setAttribute("src", src);
826
+ })
827
+ );
828
+ }
829
+ if (assetWaits.length > 0) {
830
+ await Promise.race([Promise.all(assetWaits), new Promise(function (r) { setTimeout(r, 9000); })]);
831
+ }
832
+ } catch (e) {}
833
+ try {
834
+ var lightsFound = 0;
835
+ sceneEl.object3D.traverse(function (n) { if (n.isLight) lightsFound++; });
836
+ if (lightsFound === 0) {
837
+ var basicCtor = null;
838
+ sceneEl.object3D.traverse(function (n) {
839
+ if (n.isMesh && n.material && n.material.isMeshBasicMaterial && basicCtor === null) basicCtor = n.material.constructor;
840
+ });
841
+ if (basicCtor) {
842
+ sceneEl.object3D.traverse(function (n) {
843
+ if (!n.isMesh || !n.material || n.material.isMeshBasicMaterial) return;
844
+ try {
845
+ var m = n.material;
846
+ var flat = new basicCtor({ color: m.color ? m.color.clone() : undefined });
847
+ flat.side = m.side;
848
+ flat.transparent = m.transparent;
849
+ flat.opacity = m.opacity;
850
+ if (m.map) flat.map = m.map;
851
+ n.material = flat;
852
+ } catch (e) {}
853
+ });
854
+ }
855
+ }
856
+ } catch(e){}
857
+ try {
858
+ sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
859
+ var glCanvas = sceneEl.canvas;
860
+ if (!glCanvas || glCanvas.width === 0 || glCanvas.height === 0) continue;
861
+ var overlay = document.createElement("canvas");
862
+ overlay.setAttribute("data-viv-gl-overlay", "");
863
+ overlay.width = glCanvas.width;
864
+ overlay.height = glCanvas.height;
865
+ overlay.style.position = "absolute";
866
+ overlay.style.pointerEvents = "none";
867
+ overlay.style.width = glCanvas.clientWidth + "px";
868
+ overlay.style.height = glCanvas.clientHeight + "px";
869
+ var cr = glCanvas.getBoundingClientRect();
870
+ var pr = (glCanvas.offsetParent || document.body).getBoundingClientRect();
871
+ overlay.style.left = cr.left - pr.left + "px";
872
+ overlay.style.top = cr.top - pr.top + "px";
873
+ overlay.style.zIndex = "1";
874
+ (glCanvas.parentNode || document.body).appendChild(overlay);
875
+ overlay.getContext("2d").drawImage(glCanvas, 0, 0);
876
+ // Empty capture = the scene never initialized in this tree (its
877
+ // framework lifecycle was lost to the viewer's re-parenting). Replace
878
+ // it with a fresh copy: the custom-element upgrade re-runs the full
879
+ // framework lifecycle (assets, lights, render loop) in the now-sized
880
+ // tree.
881
+ var empty = true;
882
+ try {
883
+ var dd = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
884
+ for (var di = 3; di < dd.length; di += 256) {
885
+ if (dd[di] > 0) {
886
+ empty = false;
887
+ break;
888
+ }
889
+ }
890
+ } catch (e) {
891
+ empty = false;
892
+ }
893
+ if (empty) {
894
+ var fresh = sceneEl.cloneNode(true);
895
+ sceneEl.parentNode.replaceChild(fresh, sceneEl);
896
+ sceneEl = fresh;
897
+ // Enough time for the fresh scene's asset fetches (a real GLB over
898
+ // the network) + first renders.
899
+ await new Promise(function (r) {
900
+ setTimeout(r, 8000);
901
+ });
902
+ if (!sceneEl.renderer || !sceneEl.camera) continue;
903
+ }
904
+ sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
905
+ var gl2 = sceneEl.canvas;
906
+ if (!gl2 || gl2.width === 0 || gl2.height === 0) continue;
907
+ overlay.width = gl2.width;
908
+ overlay.height = gl2.height;
909
+ overlay.getContext("2d").drawImage(gl2, 0, 0);
910
+ materialized++;
911
+ try {
912
+ var od = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
913
+ var alphaN = 0;
914
+ var orangeN = 0;
915
+ for (var oi = 3; oi < od.length; oi += 16) {
916
+ if (od[oi] > 0) alphaN++;
917
+ 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++;
918
+ }
919
+ glSample = [alphaN, orangeN];
920
+ } catch (e) {}
921
+ } catch (e) {}
922
+ }
923
+ } catch(e){}
924
+ // Hooks like echarts re-init dispose the canvas synchronously; let layout
925
+ // settle a frame before measuring so sizes reflect the repainted state.
926
+ // This also lets render loops refill their drawing buffers after the
927
+ // resize above — drawImage on a just-resized WebGL canvas would read the
928
+ // cleared buffer.
929
+ try { await nextFrame(); } catch(e){}
930
+ if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
931
+ var webgl = false, webgl2 = false;
932
+ try {
933
+ var t = document.createElement("canvas");
934
+ webgl = !!t.getContext("webgl");
935
+ var t2 = document.createElement("canvas");
936
+ webgl2 = !!t2.getContext("webgl2");
937
+ } catch(e){}
938
+ return {
939
+ url: String(location.href),
940
+ ready: window.__vivReady === true,
941
+ fixture: typeof window.__vivFixture === "string" ? window.__vivFixture : null,
942
+ webgl: webgl, webgl2: webgl2,
943
+ webgpu: typeof navigator !== "undefined" && "gpu" in navigator,
944
+ canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
945
+ iframeCount: document.querySelectorAll("iframe").length,
946
+ dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
947
+ resized: resized,
948
+ materialized: materialized,
949
+ sceneDiag: sceneDiag
950
+ };
951
+ })(${JSON.stringify(factor)})`;
952
+ }
953
+ /** Best-effort capability + HiDPI pass over every frame before `page.pdf()`. */
954
+ async function prepareForPrint(page, options = {}) {
955
+ const factor = options.settleMs !== undefined && options.canvasScale === undefined ? 1 : (options.canvasScale ?? 1);
956
+ const scale = Number.isFinite(factor) && factor > 1 ? factor : 1;
957
+ const script = buildFrameProbeScript(scale);
958
+ const out = [];
959
+ for (const frame of page.frames()) {
960
+ try {
961
+ out.push((await frame.evaluate(script)));
962
+ }
963
+ catch (err) {
964
+ // Cross-origin embeds that refuse evaluation still print as pixels.
965
+ log.trace("frame probe failed", frame.url?.() ?? "(frame)", err instanceof Error ? err.message : String(err));
966
+ continue;
967
+ }
968
+ }
969
+ if (scale > 1) {
970
+ await new Promise((resolve) => setTimeout(resolve, options.settleMs ?? 500));
971
+ }
972
+ return out;
973
+ }
974
+ /** One-line summary for logs: capabilities per frame that owns content. */
975
+ function summarizeCapabilities(caps) {
976
+ return caps
977
+ .filter((c) => c.canvasCount > 0 || (c.iframeCount ?? 0) > 0 || c.fixture !== null)
978
+ .map((c) => `${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
979
+ `webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
980
+ (c.resized !== null ? ` resized=[${c.resized}]` : "") +
981
+ (c.materialized ? ` materialized=${c.materialized} ${c.sceneDiag ?? ""}` : ""))
982
+ .join(" | ");
983
+ }
984
+ async function renderPdf(request) {
985
+ const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS;
986
+ const executablePath = resolveBrowserExecutable(request.chromeExecutable);
987
+ if (executablePath === null) {
988
+ throw new Error("No Chrome/Chromium found. Install one (e.g. `npx @puppeteer/browsers install chrome@stable`) or pass --executable-browser <path>.");
989
+ }
990
+ const viewerUrl = buildViewerUrl(request.viewerPageUrl, {
991
+ src: request.documentUrl,
992
+ bookMode: false,
993
+ renderAllPages: true,
994
+ ...request.viewerParams
995
+ });
996
+ log.trace("viewerUrl", viewerUrl);
997
+ const browser = await puppeteer.launch({
998
+ executablePath,
999
+ headless: true,
1000
+ args: chromeArgs(request.extraChromeArgs ?? []),
1001
+ acceptInsecureCerts: true
1002
+ });
1003
+ const startedAt = Date.now();
1004
+ let settle = null;
1005
+ try {
1006
+ const page = await browser.newPage();
1007
+ page.setDefaultTimeout(timeoutMs);
1008
+ page.setDefaultNavigationTimeout(timeoutMs);
1009
+ page.on("pageerror", (err) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
1010
+ // Viewer and page errors are the usual reason a render produces nothing.
1011
+ // Debug/info console messages (fetch traces from the runtime script) are
1012
+ // shown at debug level, so -d traces every page-side request.
1013
+ const debugConsole = log.getLevel() <= log.levels.DEBUG;
1014
+ page.on("console", (message) => {
1015
+ const type = message.type();
1016
+ if (type !== "error" && type !== "warn" && !(debugConsole && (type === "debug" || type === "info")))
1017
+ return;
1018
+ const where = message.location();
1019
+ log[debugConsole && type !== "error" && type !== "warn" ? "trace" : "warn"](`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`);
1020
+ });
1021
+ page.on("requestfailed", (request) => {
1022
+ log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
1023
+ });
1024
+ // Print media has to be active *before* the document loads: the page's print
1025
+ // stylesheet is what gives JS-driven containers their size, and a chart that
1026
+ // initialises against a zero-sized box never recovers.
1027
+ await page.emulateMediaType("print");
1028
+ await page.goto(viewerUrl, { waitUntil: "domcontentloaded" });
1029
+ // The viewer's contract: coreViewer exists and has finished typesetting.
1030
+ await page.waitForFunction(() => window.coreViewer !== undefined);
1031
+ await page.waitForFunction(() => window.coreViewer?.readyState === "complete", {
1032
+ polling: 500
1033
+ });
1034
+ if (request.waitForSettle === true) {
1035
+ const handle = await page.waitForFunction(() => {
1036
+ const settleState = window.__vivSettle;
1037
+ // Pages with mocked/measured async work set __vivReady when painted;
1038
+ // Vivliostyle re-runs document scripts in the viewer context, so both
1039
+ // live on the same window the renderer polls here.
1040
+ const ready = window.__vivReady === true;
1041
+ if (ready)
1042
+ return { reason: "ready", at: 0 };
1043
+ return settleState?.done === true ? { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 } : false;
1044
+ }, { polling: 200, timeout: timeoutMs });
1045
+ const state = (await handle.jsonValue());
1046
+ settle = { reason: state.reason, waitedMs: Date.now() - startedAt };
1047
+ log.trace("settle", settle);
1048
+ }
1049
+ // Iframes/canvas/WebGL/WebGPU rasterize as pixels in print-to-PDF: force
1050
+ // off-screen frames to paint, redraw HiDPI-aware pages at backing scale.
1051
+ try {
1052
+ const caps = await prepareForPrint(page, {
1053
+ canvasScale: request.canvasScale,
1054
+ settleMs: request.canvasSettleMs
1055
+ });
1056
+ const summary = summarizeCapabilities(caps);
1057
+ if (summary !== "")
1058
+ log.info(`[render] frames: ${summary}`);
1059
+ if (caps.length > 0 && caps.every((c) => !c.webgpu)) {
1060
+ log.trace("[render] WebGPU unavailable in this Chrome (best-effort software rendering)");
1061
+ }
1062
+ }
1063
+ catch (err) {
1064
+ log.warn(`[render] pre-print probe failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
1065
+ }
1066
+ const pdf = await page.pdf({
1067
+ margin: { top: 0, bottom: 0, left: 0, right: 0 },
1068
+ printBackground: true,
1069
+ preferCSSPageSize: true,
1070
+ tagged: true
1071
+ });
1072
+ const stamped = await postProcessPdf(pdf, {
1073
+ metadata: pdfMetadata(request),
1074
+ ...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
1075
+ ...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
1076
+ });
1077
+ mkdirSync(dirname(request.output), { recursive: true });
1078
+ writeFileSync(request.output, stamped);
1079
+ const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
1080
+ return { output: request.output, bytes: stamped.length, pageCount, settle };
1081
+ }
1082
+ finally {
1083
+ await browser.close();
1084
+ }
1085
+ }
1086
+
1087
+ // src/render/viewer.ts
1088
+ // Copyright (c) 2026 Christian Mahnke
1089
+ // Licensed under the MIT License.
1090
+ /**
1091
+ * Locates the Vivliostyle viewer that renders the document.
1092
+ *
1093
+ * The viewer is served by our own static server (see src/server.ts) so that the
1094
+ * document's origin — and with it the base URI of the scripts the page runs — is
1095
+ * the site we serve.
1096
+ */
1097
+ const require$1 = createRequire(import.meta.url);
1098
+ /** Directory of `@vivliostyle/viewer/lib`, which holds index.html and assets. */
1099
+ function resolveViewerLibDir() {
1100
+ const candidates = [];
1101
+ try {
1102
+ candidates.push(dirname(require$1.resolve("@vivliostyle/viewer/package.json")));
1103
+ }
1104
+ catch {
1105
+ // fall through to the paths below
1106
+ }
1107
+ candidates.push(resolve(dirname(fileURLOfSelf()), "../node_modules/@vivliostyle/viewer"), "/usr/local/lib/node_modules/@vivliostyle/viewer", "/usr/lib/node_modules/@vivliostyle/viewer");
1108
+ for (const candidate of candidates) {
1109
+ const libDir = join(candidate, "lib");
1110
+ if (existsSync(join(libDir, "index.html")))
1111
+ return libDir;
1112
+ }
1113
+ throw new Error("Could not find @vivliostyle/viewer. Install it as a dependency of this package.");
1114
+ }
1115
+ function fileURLOfSelf() {
1116
+ return new URL(import.meta.url).pathname;
1117
+ }
1118
+
1119
+ // src/metadata.ts
1120
+ /** Language tag assumed when no source provides one (project contract). */
1121
+ const DEFAULT_LANGUAGE = "de";
1122
+ /**
1123
+ * Extracts metadata from the input document: <title>, the usual
1124
+ * author/description/keywords meta tags and the document language.
1125
+ */
1126
+ function extractMetadataFromDocument(document) {
1127
+ const title = document.querySelector("title")?.textContent?.trim();
1128
+ const metaContent = (names) => {
1129
+ for (const name of names) {
1130
+ const element = document.querySelector(`meta[name="${name}" i]`) ?? document.querySelector(`meta[http-equiv="${name}" i]`);
1131
+ const content = element?.getAttribute("content")?.trim();
1132
+ if (content !== undefined && content !== "")
1133
+ return content;
1134
+ }
1135
+ return undefined;
1136
+ };
1137
+ return {
1138
+ ...(title === undefined || title === "" ? {} : { title }),
1139
+ ...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
1140
+ ...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
1141
+ ...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
1142
+ ...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
1143
+ language: value
1144
+ }))
1145
+ };
1146
+ }
1147
+ /**
1148
+ * Extracts metadata from a publication manifest (W3C Web Publication
1149
+ * Manifest shape): title, author, description, keywords and language.
1150
+ * Returns undefined when the text is not a JSON object.
1151
+ */
1152
+ function extractMetadataFromManifest(text) {
1153
+ let manifest;
1154
+ try {
1155
+ manifest = JSON.parse(text);
1156
+ }
1157
+ catch {
1158
+ return undefined;
1159
+ }
1160
+ if (manifest === null || typeof manifest !== "object")
1161
+ return undefined;
1162
+ const record = manifest;
1163
+ return {
1164
+ ...optional(asString(record.title), (value) => ({ title: value })),
1165
+ ...optional(asAuthorList(record.author), (value) => ({ author: value })),
1166
+ ...optional(asString(record.description), (value) => ({ subject: value })),
1167
+ ...optional(asStringList(record.keywords, ", "), (value) => ({ keywords: value })),
1168
+ ...optional(asStringList(record.language ?? record.inLanguage, " "), (value) => ({ language: value }))
1169
+ };
1170
+ }
1171
+ /**
1172
+ * Merges the sources: the CLI fields win over the extracted ones, and the
1173
+ * language falls back to the project default.
1174
+ */
1175
+ function resolveMetadata(cli, derived) {
1176
+ const merged = { ...derived, ...definedEntries(cli) };
1177
+ if (merged.language === undefined || merged.language === "") {
1178
+ merged.language = DEFAULT_LANGUAGE;
1179
+ }
1180
+ return merged;
1181
+ }
1182
+ /** Parses a `--pdfa` level like `2b`; part 4 takes no conformance level. */
1183
+ function parsePdfaLabel(value) {
1184
+ const match = /^([1-4])([abu])?$/i.exec(value.trim());
1185
+ if (match === null) {
1186
+ throw new Error(`Invalid --pdfa level: "${value}". Allowed: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4`);
1187
+ }
1188
+ const part = match[1];
1189
+ const conformance = match[2]?.toLowerCase();
1190
+ if (part === "4" && conformance !== undefined) {
1191
+ throw new Error(`PDF/A-4 does not take a conformance level: "${value}". Use --pdfa 4`);
1192
+ }
1193
+ if (part !== "4" && conformance === undefined) {
1194
+ throw new Error(`Missing PDF/A conformance level: "${value}". Use e.g. --pdfa 2b`);
1195
+ }
1196
+ return { kind: "pdfa", part, ...(conformance === undefined ? {} : { conformance }) };
1197
+ }
1198
+ /** Parses a `--pdfx` version; `X-1a` is accepted as shorthand for 2003. */
1199
+ function parsePdfxLabel(value) {
1200
+ const normalized = value.trim();
1201
+ if (normalized === "X-4")
1202
+ return { kind: "pdfx", version: "X-4" };
1203
+ if (normalized === "X-1a" || normalized === "X-1a:2003")
1204
+ return { kind: "pdfx", version: "X-1a:2003" };
1205
+ throw new Error(`Invalid --pdfx version: "${value}". Allowed: X-4, X-1a:2003`);
1206
+ }
1207
+ // ---------------------------------------------------------------------------
1208
+ // Helpers
1209
+ // ---------------------------------------------------------------------------
1210
+ function definedEntries(source) {
1211
+ const entries = {};
1212
+ for (const [key, value] of Object.entries(source)) {
1213
+ if (value !== undefined && value !== "")
1214
+ entries[key] = value;
1215
+ }
1216
+ return entries;
1217
+ }
1218
+ function optional(value, wrap) {
1219
+ return value === undefined || value === null || value === "" ? {} : wrap(value);
1220
+ }
1221
+ function asString(value) {
1222
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
1223
+ }
1224
+ /** Flattens string | {name} | ({name} | string)[] into "a; b" form. */
1225
+ function asAuthorList(value) {
1226
+ const names = Array.isArray(value) ? value : [value];
1227
+ const flattened = names
1228
+ .map((entry) => {
1229
+ if (typeof entry === "string")
1230
+ return entry.trim();
1231
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
1232
+ return entry.name.trim();
1233
+ }
1234
+ return "";
1235
+ })
1236
+ .filter((name) => name !== "");
1237
+ return flattened.length === 0 ? undefined : flattened.join("; ");
1238
+ }
1239
+ function asStringList(value, separator) {
1240
+ const entries = Array.isArray(value) ? value : [value];
1241
+ const flattened = entries.map((entry) => (typeof entry === "string" ? entry.trim() : "")).filter((entry) => entry !== "");
1242
+ return flattened.length === 0 ? undefined : flattened.join(separator);
1243
+ }
1244
+
1245
+ // src/vivliostyle-cli.ts
1246
+ // Copyright (c) 2026 Christian Mahnke
1247
+ // Licensed under the MIT License.
1248
+ const validFormats = ["pdf"];
13
1249
  const validLogLevels = ["silent", "info", "verbose", "debug"];
14
1250
  const validModes = ["build", "preview"];
1251
+ /**
1252
+ * Wrapper log levels mapped onto loglevel. Diagnostics are written to the trace
1253
+ * channel, so `--log-level verbose` stays quiet while `debug` shows them.
1254
+ */
1255
+ const LOG_LEVELS = {
1256
+ silent: log.levels.SILENT,
1257
+ info: log.levels.INFO,
1258
+ verbose: log.levels.DEBUG,
1259
+ debug: log.levels.TRACE
1260
+ };
1261
+ /**
1262
+ * Send every level to the console channel the CLI contract uses: progress to
1263
+ * stdout, diagnostics and problems to stderr. The method is resolved per call so
1264
+ * that patched consoles stay visible.
1265
+ */
1266
+ const CONSOLE_CHANNEL = {
1267
+ trace: "error",
1268
+ debug: "error",
1269
+ info: "log",
1270
+ warn: "warn",
1271
+ error: "error"
1272
+ };
1273
+ log.methodFactory =
1274
+ (methodName) => (...args) => {
1275
+ console[CONSOLE_CHANNEL[methodName] ?? "log"](...args);
1276
+ };
1277
+ // ---------------------------------------------------------------------------
1278
+ // Site path + settle gate helpers
1279
+ // ---------------------------------------------------------------------------
1280
+ /** Directory part of a site path, without a trailing slash (`""` for the root). */
1281
+ function siteDirectory(sitePath) {
1282
+ const dir = posix.dirname(sitePath);
1283
+ return dir === "/" ? "" : dir;
1284
+ }
1285
+ /**
1286
+ * Path the document has on the mapped site, e.g. `/post/tag-pairs/article.html`
1287
+ * for `<localBase>/post/tag-pairs/article.html`. Used as the URL Vivliostyle
1288
+ * loads, so page-relative and root-relative references resolve like they do on
1289
+ * the real site.
1290
+ */
1291
+ function deriveSitePath(inputAbs, assetBases) {
1292
+ for (const ab of assetBases) {
1293
+ const relativePath = relative(resolve(ab.localBase), resolve(inputAbs));
1294
+ if (relativePath === "" || relativePath.startsWith("..") || isAbsolute(relativePath))
1295
+ continue;
1296
+ return `/${relativePath.split(sep).join("/")}`;
1297
+ }
1298
+ return null;
1299
+ }
1300
+ /**
1301
+ * Opens every `<details>` element, now and for any the page adds later.
1302
+ *
1303
+ * Print output has to contain the collapsed content too, and the page's own
1304
+ * print script cannot do it: Vivliostyle re-dispatches `DOMContentLoaded` on
1305
+ * the window rather than on the document, so a `document`-level listener never
1306
+ * runs.
1307
+ */
1308
+ const EXPAND_DETAILS_SNIPPET = `function expandDetails(root){
1309
+ var open=function(el){
1310
+ if(el.tagName!=="DETAILS"||el.open)return;
1311
+ el.open=true;
1312
+ el.setAttribute("data-viv-details-expanded","");
1313
+ };
1314
+ if(root.nodeType!==1)return;
1315
+ [].forEach.call(root.querySelectorAll("details"),open);
1316
+ open(root);
1317
+ }
1318
+ expandDetails(document);
1319
+ try{new MutationObserver(function(records){
1320
+ for(var i=0;i<records.length;i++){
1321
+ var added=records[i].addedNodes;
1322
+ for(var j=0;j<added.length;j++)expandDetails(added[j]);
1323
+ }
1324
+ }).observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
1325
+ `;
1326
+ /** Gate image Vivliostyle waits for before it paginates. */
1327
+ function buildSettleGateImage(origin) {
1328
+ // Out of flow and invisible, but rendered: Vivliostyle only loads resources of
1329
+ // elements that end up in the render tree, so `display:none` would be skipped.
1330
+ return `<img src="${origin}/__viv-settle" alt="" width="1" height="1" style="position:absolute;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none" data-vivliostyle-settle-gate>`;
1331
+ }
1332
+ /**
1333
+ * The script injected into the document: it routes the URLs that page scripts
1334
+ * create to our server and tracks whether the page has finished.
1335
+ *
1336
+ * Everything lives in one scope on purpose — the settle tracker wraps the same
1337
+ * `fetch`/XHR that the routing patches.
1338
+ */
1339
+ function buildRuntimeScript(options) {
1340
+ const { origin, documentBaseUrl, gate } = options;
1341
+ const expandDetails = options.expandDetails === true ? EXPAND_DETAILS_SNIPPET : "";
1342
+ // Vivliostyle paginates incrementally, so collapsed content has to be opened
1343
+ // again while it lays the document out, not just once up front.
1344
+ const expandDetailsTick = options.expandDetails === true ? "expandDetails(document);" : "";
1345
+ return `(function(){
1346
+ var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
1347
+ var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
1348
+ var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
1349
+ // Force preserveDrawingBuffer on every WebGL context the page creates:
1350
+ // print-to-PDF otherwise captures the cleared drawing buffer and WebGL
1351
+ // content ships empty, even though the browser shows it composited.
1352
+ try {
1353
+ var origGetContext = HTMLCanvasElement.prototype.getContext;
1354
+ HTMLCanvasElement.prototype.getContext = function (type, attrs) {
1355
+ if (typeof type === "string" && /^webgl/.test(type)) {
1356
+ attrs = Object.assign({}, attrs || {});
1357
+ attrs.preserveDrawingBuffer = true;
1358
+ return origGetContext.call(this, type, attrs);
1359
+ }
1360
+ return origGetContext.call(this, type, attrs);
1361
+ };
1362
+ } catch (e) {}
1363
+ // Vivliostyle re-dispatches DOMContentLoaded on the window only, so scripts
1364
+ // waiting for it on the document (framework bootstraps, print scripts, asset
1365
+ // bootstraps) never run. Re-dispatch the lifecycle events properly once
1366
+ // loading finished.
1367
+ try {
1368
+ var redeliver = function () {
1369
+ setTimeout(function () {
1370
+ try {
1371
+ document.dispatchEvent(new Event("DOMContentLoaded"));
1372
+ window.dispatchEvent(new Event("DOMContentLoaded"));
1373
+ window.dispatchEvent(new Event("load"));
1374
+ } catch (e) {}
1375
+ }, 0);
1376
+ };
1377
+ if (document.readyState === "complete") redeliver();
1378
+ else window.addEventListener("load", redeliver, { once: true });
1379
+ } catch (e) {}
1380
+ var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
1381
+
1382
+ // Root-relative URLs resolve against the site root, document-relative ones
1383
+ // against the directory the page has on the site (e.g. model/x.glb next to it).
1384
+ function fix(u){
1385
+ if(typeof u!=="string"||u==="")return u;
1386
+ if(u.slice(0,2)==="//"||u.charAt(0)==="#"||u.charAt(0)==="?")return u;
1387
+ if(/^[a-z][a-z0-9+.-]*:/i.test(u))return u;
1388
+ return u.charAt(0)==="/"?ORIGIN+u:BASE+u;
1389
+ }
1390
+
1391
+ function canvases(){
1392
+ try{return[].map.call(document.querySelectorAll("canvas"),function(c){
1393
+ return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);}).join(",");}catch(e){return"";}
1394
+ }
1395
+ // Canvases with real backing pixels and layout size: the minimum for charts,
1396
+ // three.js, maps and OSD tiles to survive print-to-PDF as sharp raster.
1397
+ function paintedCanvases(){
1398
+ try{return[].filter.call(document.querySelectorAll("canvas"),function(c){
1399
+ return c.width>2&&c.height>2&&c.clientWidth>0&&c.clientHeight>0;}).length;}catch(e){return 0;}
1400
+ }
1401
+ // Sizes of the containers pages fill at runtime; zero means the layout has not
1402
+ // happened yet, which is what breaks canvas and chart initialisation.
1403
+ function containers(){
1404
+ try{return[].map.call(document.querySelectorAll(".script,[class*=script]"),function(el){
1405
+ return (el.id||el.className)+"@"+Math.round(el.clientWidth)+"x"+Math.round(el.clientHeight);}).join(",");}catch(e){return"";}
1406
+ }
1407
+
1408
+ function signal(why){
1409
+ if(done)return;done=true;
1410
+ var at=Math.round(performance.now());
1411
+ state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
1412
+ var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
1413
+ "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&longtasks="+longtasks+"&dpr="+window.devicePixelRatio+
1414
+ "&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
1415
+ "&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
1416
+ try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
1417
+ }
1418
+
1419
+ // An embed that never fires load must not hold the layout open forever.
1420
+ function watchFrame(frame){
1421
+ if(frame.__vivWatched)return;frame.__vivWatched=true;frames++;
1422
+ var settled=false;
1423
+ function finish(){if(settled)return;settled=true;frames--;last=performance.now();}
1424
+ frame.addEventListener("load",finish);
1425
+ frame.addEventListener("error",finish);
1426
+ try{ if(frame.contentDocument&&frame.contentDocument.readyState==="complete"){finish();return;} }catch(e){}
1427
+ setTimeout(finish,FRAME_GRACE);
1428
+ }
1429
+ function watchFrames(root){
1430
+ try{
1431
+ [].forEach.call(root.querySelectorAll("iframe"),watchFrame);
1432
+ if(root.tagName==="IFRAME")watchFrame(root);
1433
+ }catch(e){}
1434
+ }
1435
+
1436
+ var of=window.fetch;
1437
+ if(of){window.fetch=function(input,init){
1438
+ try{
1439
+ if(typeof input==="string")input=fix(input);
1440
+ else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
1441
+ }catch(e){}
1442
+ pending++;last=performance.now();
1443
+ var furl=(typeof input==="string"?input:input&&input.url?input.url:"?");
1444
+ return of.call(this,input,init).then(function(v){pending--;last=performance.now();
1445
+ try{console.debug("[viv-fetch]",furl,"->",v.status);}catch(e){}
1446
+ return v;},
1447
+ function(e){pending--;last=performance.now();
1448
+ try{console.debug("[viv-fetch]",furl,"-> FAILED",String(e).slice(0,80));}catch(e2){}
1449
+ throw e;});};}
1450
+ var XHR=window.XMLHttpRequest;
1451
+ if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
1452
+ XHR.prototype.open=function(m,u){this.__vscounted=true;this.__vsurl=fix(u);return open.apply(this,arguments);};
1453
+ XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
1454
+ this.addEventListener("loadend",function(){pending--;last=performance.now();
1455
+ try{console.debug("[viv-xhr]",this.__vsurl,"->",this.status);}catch(e){}});}
1456
+ return send.apply(this,arguments);};}
1457
+ // WebAssembly compilation runs after its fetch resolves, so the fetch wrapper
1458
+ // alone would report idle mid-compile. Hold pending through it.
1459
+ var WA=window.WebAssembly;
1460
+ if(WA){["instantiate","instantiateStreaming","compile","compileStreaming"].forEach(function(n){
1461
+ var orig=WA[n];if(typeof orig!=="function")return;
1462
+ WA[n]=function(){pending++;last=performance.now();
1463
+ var result;
1464
+ try{result=orig.apply(this,arguments);}catch(e){pending--;last=performance.now();throw e;}
1465
+ if(result&&typeof result.then==="function"){
1466
+ return result.then(function(v){pending--;last=performance.now();return v;},
1467
+ function(e){pending--;last=performance.now();throw e;});
1468
+ }
1469
+ pending--;last=performance.now();return result;};});}
1470
+ // Heavy main-thread work (script eval, wasm compile, shader/layout jank)
1471
+ // emits no network or DOM signal; long tasks keep the quiet window open.
1472
+ try{var PO=window.PerformanceObserver;
1473
+ if(typeof PO==="function"){new PO(function(list){
1474
+ var entries=list.getEntries();for(var i=0;i<entries.length;i++){longtasks++;last=performance.now();}
1475
+ }).observe({entryTypes:["longtask"]});}}catch(e){}
1476
+ ["Image","Audio"].forEach(function(n){
1477
+ var Orig=window[n];if(!Orig)return;
1478
+ var Wrapped=function(u){return new Orig(fix(u));};
1479
+ Wrapped.prototype=Orig.prototype;
1480
+ try{window[n]=Wrapped;}catch(e){}
1481
+ });
1482
+ ["HTMLImageElement","HTMLIFrameElement","HTMLScriptElement","HTMLSourceElement","HTMLVideoElement","HTMLAudioElement"].forEach(function(n){
1483
+ var C=window[n];if(!C)return;
1484
+ var d=Object.getOwnPropertyDescriptor(C.prototype,"src");
1485
+ if(!d||!d.set)return;
1486
+ try{Object.defineProperty(C.prototype,"src",{configurable:true,enumerable:d.enumerable,get:d.get,
1487
+ set:function(v){d.set.call(this,fix(v));if(n==="HTMLIFrameElement")watchFrame(this);}});}catch(e){}
1488
+ });
1489
+ try{Object.defineProperty(document,"baseURI",{configurable:true,get:function(){return BASE;}});}catch(e){}
1490
+ try{new MutationObserver(function(){mutations++;watchFrames(document.documentElement);last=performance.now();})
1491
+ .observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
1492
+ try{new ResizeObserver(function(){last=performance.now();}).observe(document.documentElement);}catch(e){}
1493
+ ${expandDetails}watchFrames(document.documentElement);
1494
+ last=performance.now();
1495
+ (function check(){
1496
+ if(done)return;
1497
+ ${expandDetailsTick}
1498
+ var now=performance.now();
1499
+ if(now>=DEADLINE){signal("deadline");return;}
1500
+ // Webfonts loading late would leave canvas text painted with fallbacks.
1501
+ try{if(document.fonts&&document.fonts.status==="loading"){setTimeout(check,50);return;}}catch(e){}
1502
+ // Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
1503
+ // painted instead of making the gate guess from network quietness. Shader
1504
+ // compile and tile decode finish after the last fetch, so readiness wins.
1505
+ if(window.__vivReady===true&&pending===0&&frames===0){signal("ready");return;}
1506
+ if(pending===0&&frames===0&&now-last>=QUIET){signal("quiet");return;}
1507
+ setTimeout(check,50);
1508
+ })();
1509
+ })();`;
1510
+ }
1511
+ /**
1512
+ * Injects the runtime script as the first thing in `<head>` (so it wraps `fetch`
1513
+ * before any page script runs) and the gate image at the end of `<body>`.
1514
+ */
1515
+ function injectRuntimeScriptInDom(document, options) {
1516
+ const head = document.head;
1517
+ const anchor = head.firstChild;
1518
+ const base = document.createElement("base");
1519
+ base.setAttribute("href", options.documentBaseUrl);
1520
+ head.insertBefore(base, anchor);
1521
+ const script = document.createElement("script");
1522
+ script.textContent = buildRuntimeScript(options);
1523
+ head.insertBefore(script, anchor);
1524
+ if (options.gate === null)
1525
+ return;
1526
+ document.body?.insertAdjacentHTML("beforeend", buildSettleGateImage(options.origin));
1527
+ }
15
1528
  // ---------------------------------------------------------------------------
16
1529
  // HTML input detection
17
1530
  // ---------------------------------------------------------------------------
1531
+ function isHtmlInput(inputAbs) {
1532
+ return /\.html?$/i.test(inputAbs);
1533
+ }
1534
+ // ---------------------------------------------------------------------------
1535
+ // Arg splitting
1536
+ // ---------------------------------------------------------------------------
1537
+ function splitArgsAtDoubleDash(argv) {
1538
+ const dd = argv.indexOf("--");
1539
+ if (dd === -1)
1540
+ return { cliArgv: argv, extraArgs: [] };
1541
+ return { cliArgv: argv.slice(0, dd), extraArgs: argv.slice(dd + 1) };
1542
+ }
1543
+ // ---------------------------------------------------------------------------
1544
+ // Static mappings
1545
+ // ---------------------------------------------------------------------------
1546
+ /**
1547
+ * Serve a single local file directly, bypassing Vite's transform pipeline.
1548
+ * Returns true if the file was served, false if it should fall through.
1549
+ */
1550
+ // ---------------------------------------------------------------------------
1551
+ // DOM-level rewriters
1552
+ // ---------------------------------------------------------------------------
1553
+ const URL_ATTR_SELECTORS = [
1554
+ ["link[href]", "href"],
1555
+ ["script[src]", "src"],
1556
+ ["img[src]", "src"],
1557
+ ["source[src]", "src"],
1558
+ ["video[src]", "src"],
1559
+ ["audio[src]", "src"],
1560
+ ["video[poster]", "poster"],
1561
+ ["input[src]", "src"]
1562
+ ];
1563
+ /**
1564
+ * Subresource attributes that would trigger a network request. Hyperlink
1565
+ * attributes (`<a href>`) are deliberately absent: a link is not fetched.
1566
+ */
1567
+ const SUBRESOURCE_ATTR_SELECTORS = [
1568
+ ...URL_ATTR_SELECTORS,
1569
+ ["img[srcset]", "srcset"],
1570
+ ["source[srcset]", "srcset"],
1571
+ ["iframe[src]", "src"],
1572
+ ["object[data]", "data"],
1573
+ ["embed[src]", "src"],
1574
+ // A-Frame keeps its assets in custom elements
1575
+ ["a-asset-item[src]", "src"]
1576
+ ];
1577
+ /** URL schemes that never leave the document. */
1578
+ const INLINE_URL_SCHEME_RE = /^(?:data|blob|about|javascript|mailto|tel):/i;
1579
+ /**
1580
+ * Applies `transform` to every URL of every subresource attribute.
1581
+ *
1582
+ * A `srcset` candidate list is transformed candidate by candidate, keeping the
1583
+ * descriptors (`1x`, `480w`). Returning `null` drops the candidate; an attribute
1584
+ * without any remaining candidate is removed.
1585
+ */
1586
+ function rewriteUrlAttributes(document, transform) {
1587
+ let changed = false;
1588
+ const apply = (el, attr) => {
1589
+ const raw = el.getAttribute(attr);
1590
+ if (raw === null)
1591
+ return;
1592
+ if (attr !== "srcset") {
1593
+ const current = raw.trim();
1594
+ const next = transform(current);
1595
+ if (next === null) {
1596
+ el.removeAttribute(attr);
1597
+ changed = true;
1598
+ return;
1599
+ }
1600
+ if (next === current)
1601
+ return;
1602
+ el.setAttribute(attr, next);
1603
+ changed = true;
1604
+ return;
1605
+ }
1606
+ const candidates = raw
1607
+ .split(",")
1608
+ .map((candidate) => candidate.trim())
1609
+ .filter(Boolean);
1610
+ const kept = [];
1611
+ let touched = false;
1612
+ for (const candidate of candidates) {
1613
+ const [url, ...descriptor] = candidate.split(/\s+/);
1614
+ const next = transform(url);
1615
+ if (next === null) {
1616
+ touched = true;
1617
+ continue;
1618
+ }
1619
+ if (next !== url)
1620
+ touched = true;
1621
+ kept.push([next, ...descriptor].join(" "));
1622
+ }
1623
+ if (!touched)
1624
+ return;
1625
+ changed = true;
1626
+ if (kept.length === 0)
1627
+ el.removeAttribute(attr);
1628
+ else
1629
+ el.setAttribute(attr, kept.join(", "));
1630
+ };
1631
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
1632
+ for (const el of document.querySelectorAll(selector))
1633
+ apply(el, attr);
1634
+ }
1635
+ return changed;
1636
+ }
1637
+ /**
1638
+ * True when the browser would have to fetch the URL over the network.
1639
+ */
1640
+ function isRemoteUrl(value) {
1641
+ const trimmed = value.trim();
1642
+ if (!trimmed)
1643
+ return false;
1644
+ if (trimmed.startsWith("//"))
1645
+ return true;
1646
+ return /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !INLINE_URL_SCHEME_RE.test(trimmed);
1647
+ }
1648
+ /**
1649
+ * Drops subresource references that are not available locally so nothing is
1650
+ * fetched from the web. `srcset` candidates are filtered individually; an
1651
+ * attribute whose candidates are all remote is removed entirely.
1652
+ *
1653
+ * `isAllowed` exempts URLs that are served by the wrapper itself, e.g. the
1654
+ * static server URLs produced by the virtual-path rewrite.
1655
+ *
1656
+ * Returns every dropped URL.
1657
+ */
1658
+ function dropRemoteReferencesInDom(document, isAllowed = () => false) {
1659
+ const dropped = [];
1660
+ const droppedSet = new Set();
1661
+ rewriteUrlAttributes(document, (url) => {
1662
+ if (isAllowed(url) || !isRemoteUrl(url))
1663
+ return url;
1664
+ droppedSet.add(url);
1665
+ return null;
1666
+ });
1667
+ dropped.push(...droppedSet);
1668
+ // A meta refresh navigates the document, which is a fetch just like a
1669
+ // subresource. Redirect stubs are dropped as well.
1670
+ for (const el of document.querySelectorAll("meta[http-equiv]")) {
1671
+ if ((el.getAttribute("http-equiv") ?? "").toLowerCase() !== "refresh")
1672
+ continue;
1673
+ const target = parseMetaRefreshTarget(el.getAttribute("content") ?? "");
1674
+ if (target === null || !isRemoteUrl(target) || isAllowed(target))
1675
+ continue;
1676
+ el.remove();
1677
+ dropped.push(target);
1678
+ }
1679
+ return dropped;
1680
+ }
1681
+ /**
1682
+ * Extracts the target of `<meta http-equiv="refresh" content="0; url=…">`.
1683
+ */
1684
+ function parseMetaRefreshTarget(content) {
1685
+ const match = /^\s*[\d.]*\s*;?\s*url\s*=\s*(.*)$/i.exec(content);
1686
+ if (match === null)
1687
+ return null;
1688
+ const target = match[1].trim().replace(/^["']|["']$/g, "");
1689
+ return target === "" ? null : target;
1690
+ }
1691
+ /**
1692
+ * Root-relative subresource paths that survive the rewrites and therefore end
1693
+ * up resolved against the file system location of the input document. They are
1694
+ * broken unless something else provides them (e.g. the input is served over
1695
+ * HTTP), so they are worth reporting.
1696
+ */
1697
+ function collectUnservedVirtualPaths(document, staticMapKeys, isServable) {
1698
+ const isMapped = (path) => staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
1699
+ const unserved = new Set();
1700
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
1701
+ for (const el of document.querySelectorAll(selector)) {
1702
+ const raw = el.getAttribute(attr);
1703
+ if (raw === null)
1704
+ continue;
1705
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
1706
+ for (const value of values) {
1707
+ if (!value.startsWith("/"))
1708
+ continue;
1709
+ if (isMapped(value))
1710
+ continue;
1711
+ if (isServable !== undefined && isServable(value))
1712
+ continue;
1713
+ unserved.add(value);
1714
+ }
1715
+ }
1716
+ }
1717
+ return [...unserved];
1718
+ }
1719
+ /** Remote subresource URLs a document would have to fetch. */
1720
+ function collectRemoteReferences(document) {
1721
+ const urls = new Set();
1722
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
1723
+ for (const el of document.querySelectorAll(selector)) {
1724
+ const raw = el.getAttribute(attr);
1725
+ if (raw === null)
1726
+ continue;
1727
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
1728
+ for (const value of values) {
1729
+ if (isRemoteUrl(value))
1730
+ urls.add(value);
1731
+ }
1732
+ }
1733
+ }
1734
+ return [...urls];
1735
+ }
18
1736
  /**
19
- * Returns true when the input file should be treated as HTML.
20
- * Vivliostyle also accepts publication manifests (JSON/TOML/JS config files);
21
- * we detect HTML by extension to avoid trying to parse those as markup.
1737
+ * Whether a remote reference is worth probing on the live site.
1738
+ *
1739
+ * A reference that resolves to a local file is served from disk, so only that
1740
+ * file decides whether it stays: the live site may have moved on (a new CSS
1741
+ * hash, a rotated upload) while our copy of the page still has what it needs.
22
1742
  */
23
- function isHtmlInput(inputAbs) {
24
- return /\.html?$/i.test(inputAbs);
1743
+ function referencesToProbe(url, assetBases) {
1744
+ const mapped = mapAbsoluteUrlToLocal(url, assetBases);
1745
+ return mapped.kind === "mapped" ? !existsSync(mapped.localPath) : true;
25
1746
  }
26
- // ---------------------------------------------------------------------------
27
- // Debug logger
28
- // ---------------------------------------------------------------------------
29
- function makeDbg(enabled) {
30
- return (_label, _value) => {
31
- if (!enabled)
32
- return;
33
- if (_value === undefined) {
34
- console.error(`[debug] ${_label}`);
1747
+ /**
1748
+ * Checks which remote references actually exist, so that content that is gone
1749
+ * (a deleted slide deck, a retired CSS file) is dropped instead of leaving a
1750
+ * broken embed that never finishes loading.
1751
+ */
1752
+ async function probeRemoteReferences(urls, timeoutMs = 8000) {
1753
+ const unavailable = new Set();
1754
+ await Promise.all(urls.map(async (url) => {
1755
+ try {
1756
+ const response = await fetch(url, { method: "HEAD", redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
1757
+ // Only a definite "gone" counts: servers that reject HEAD still have the file.
1758
+ if (response.status === 404 || response.status === 410)
1759
+ unavailable.add(url);
1760
+ log.trace("probeRemoteReferences", { url, status: response.status });
35
1761
  }
36
- else {
37
- console.error(`[debug] ${_label}`, JSON.stringify(_value, null, 2));
1762
+ catch (err) {
1763
+ // A failed probe is no proof that the resource is gone: Chromium loads
1764
+ // it with a browser user agent, which many sites accept where a HEAD
1765
+ // request from Node is rejected or blocked outright.
1766
+ log.trace("probeRemoteReferences failed", { url, error: String(err) });
38
1767
  }
39
- };
1768
+ }));
1769
+ return unavailable;
40
1770
  }
41
- // ---------------------------------------------------------------------------
42
- // Arg splitting
43
- // ---------------------------------------------------------------------------
44
- function splitArgsAtDoubleDash(argv) {
45
- const dd = argv.indexOf("--");
46
- if (dd === -1)
47
- return { cliArgv: argv, extraArgs: [] };
48
- return { cliArgv: argv.slice(0, dd), extraArgs: argv.slice(dd + 1) };
1771
+ /** Removes the attributes that point at the given URLs. */
1772
+ function dropUnavailableReferencesInDom(document, unavailable) {
1773
+ if (unavailable.size === 0)
1774
+ return [];
1775
+ const dropped = [];
1776
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
1777
+ for (const el of document.querySelectorAll(selector)) {
1778
+ const raw = el.getAttribute(attr);
1779
+ if (raw === null)
1780
+ continue;
1781
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
1782
+ const hit = values.filter((value) => unavailable.has(value));
1783
+ if (hit.length === 0)
1784
+ continue;
1785
+ dropped.push(...hit);
1786
+ const kept = attr === "srcset"
1787
+ ? raw
1788
+ .split(",")
1789
+ .map((e) => e.trim())
1790
+ .filter((c) => !unavailable.has(c.split(/\s+/)[0] ?? ""))
1791
+ : [];
1792
+ if (kept.length === 0)
1793
+ el.removeAttribute(attr);
1794
+ else
1795
+ el.setAttribute(attr, kept.join(", "));
1796
+ }
1797
+ }
1798
+ for (const url of new Set(dropped)) {
1799
+ log.warn(`[fetch] Dropped unavailable remote reference: ${url}`);
1800
+ }
1801
+ return dropped;
49
1802
  }
50
- function makeMimeHeaders(res, filePath) {
51
- const mime = lookup(filePath);
52
- if (mime)
53
- res.setHeader("Content-Type", mime);
1803
+ /**
1804
+ * Exempts the wrapper's own static server from the offline pass: URLs pointing
1805
+ * at it are served from the local file system, never from the web.
1806
+ */
1807
+ function isStaticServerUrl(serverBaseUrl) {
1808
+ return (url) => serverBaseUrl !== "" && url.startsWith(serverBaseUrl);
54
1809
  }
55
- function isFile(localPath) {
56
- try {
57
- return statSync(localPath).isFile();
1810
+ function reportDroppedRemoteRefs(dropped) {
1811
+ for (const url of new Set(dropped)) {
1812
+ log.info(`[offline] Dropped remote reference: ${url}`);
58
1813
  }
59
- catch {
60
- return false;
1814
+ log.trace("dropRemoteReferencesInDom: dropped", dropped);
1815
+ }
1816
+ function reportUnservedVirtualPaths(unserved) {
1817
+ for (const path of unserved) {
1818
+ log.warn(`[html] Warning: reference is not available and will not resolve: ${path}`);
61
1819
  }
62
1820
  }
63
- function applyStaticMounts(app, staticMap, assetBases, dbg) {
64
- for (const [virtual, localBase] of Object.entries(staticMap)) {
65
- const absLocal = resolve(localBase);
66
- if (isFile(absLocal)) {
67
- app.get(virtual, (_req, res) => {
68
- dbg("[static-server] serving file", { virtual, absLocal });
69
- const mime = lookup(absLocal);
70
- if (mime)
71
- res.type(mime);
72
- res.sendFile(absLocal);
73
- });
74
- console.log(`[static-server] File route: GET ${virtual} → ${absLocal}`);
1821
+ function mapAbsoluteUrlToLocal(url, assetBases) {
1822
+ for (const mapping of assetBases) {
1823
+ if (!url.startsWith(mapping.urlBase))
1824
+ continue;
1825
+ let cleanRelative;
1826
+ try {
1827
+ cleanRelative = new URL(url).pathname.slice(1);
75
1828
  }
76
- else {
77
- const mountPath = virtual.endsWith("/") ? virtual : `${virtual}/`;
78
- app.use(mountPath, serveStatic(absLocal, {
79
- fallthrough: true,
80
- setHeaders: makeMimeHeaders
81
- }));
82
- console.log(`[static-server] Dir mount: ${mountPath} → ${absLocal}`);
1829
+ catch {
1830
+ const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
1831
+ cleanRelative = noQuery.split("#")[0];
83
1832
  }
84
- dbg("[static-server] mount", { virtual, absLocal });
85
- }
86
- for (const ab of assetBases) {
87
- const absLocal = resolve(ab.localBase);
88
- app.use("/", serveStatic(absLocal, { fallthrough: true, setHeaders: makeMimeHeaders }));
89
- dbg("[static-server] assetBase fallback mount", absLocal);
90
- console.log(`[static-server] Fallback mount: / → ${absLocal}`);
91
- }
92
- }
93
- function startStaticServer(staticMap, assetBases, htmlFilePath, dbg, port = 0) {
94
- const app = express();
95
- app.disable("x-powered-by");
96
- if (htmlFilePath !== null) {
97
- const absHtmlPath = resolve(htmlFilePath);
98
- app.get("/index.html", (_req, res) => {
99
- dbg("[static-server] serving HTML entry", absHtmlPath);
100
- res.type("text/html").sendFile(absHtmlPath);
101
- });
102
- console.log(`[static-server] HTML entry: /index.html → ${absHtmlPath}`);
1833
+ if (!cleanRelative) {
1834
+ // The URL points to the asset-base root itself
1835
+ // (e.g. https://cdn.example.com/ with no sub-path).
1836
+ return { kind: "root-only" };
1837
+ }
1838
+ const virtualPath = posix.resolve("/", cleanRelative);
1839
+ const localPath = resolve(mapping.localBase, cleanRelative);
1840
+ return { kind: "mapped", virtualPath, localPath };
103
1841
  }
104
- applyStaticMounts(app, staticMap, assetBases, dbg);
105
- app.use((req, res) => {
106
- dbg("[static-server] 404", req.url);
107
- res.status(404).type("text").send(`404 Not Found: ${req.url}`);
108
- });
109
- return new Promise((resolvePromise, reject) => {
110
- const httpServer = app.listen(port, "127.0.0.1", () => {
111
- const addr = httpServer.address();
112
- const baseUrl = `http://127.0.0.1:${addr.port}`;
113
- console.log(`[static-server] Listening on ${baseUrl}`);
114
- dbg("[static-server] staticMap", staticMap);
115
- dbg("[static-server] assetBase roots", assetBases.map((ab) => ab.localBase));
116
- let closed = false;
117
- const close = () => {
118
- if (closed)
119
- return;
120
- closed = true;
121
- httpServer.close((err) => {
122
- if (err)
123
- console.warn(`[static-server] close error: ${err.message}`);
124
- else
125
- dbg("[static-server] stopped");
126
- });
127
- };
128
- resolvePromise({ baseUrl, close });
129
- });
130
- httpServer.once("error", reject);
131
- });
1842
+ return { kind: "no-match" };
132
1843
  }
133
- // ---------------------------------------------------------------------------
134
- // DOM-level rewriters
135
- // ---------------------------------------------------------------------------
136
- const URL_ATTR_SELECTORS = [
137
- ["link[href]", "href"],
138
- ["script[src]", "src"],
139
- ["img[src]", "src"],
140
- ["source[src]", "src"],
141
- ["video[src]", "src"],
142
- ["audio[src]", "src"],
143
- ["video[poster]", "poster"],
144
- ["input[src]", "src"]
145
- ];
146
- function rewriteAbsoluteUrlsInDom(document, assetBases) {
1844
+ function rewriteAbsoluteUrlsInDom(document, assetBases, keepMissing = false) {
147
1845
  if (assetBases.length === 0)
148
1846
  return false;
149
- let changed = false;
150
- for (const [selector, attr] of URL_ATTR_SELECTORS) {
151
- for (const el of document.querySelectorAll(selector)) {
152
- const val = el.getAttribute(attr) ?? "";
153
- const mapped = mapAbsoluteUrlToLocal(val, assetBases);
154
- if (mapped) {
155
- el.setAttribute(attr, mapped.virtualPath);
156
- changed = true;
157
- }
158
- }
159
- }
160
- return changed;
1847
+ // "root-only" and "no-match" — leave the URL unchanged. With `keepMissing`,
1848
+ // URLs whose local file does not exist keep their absolute form so the browser
1849
+ // can load them from the mapped origin.
1850
+ return rewriteUrlAttributes(document, (url) => {
1851
+ const match = mapAbsoluteUrlToLocal(url, assetBases);
1852
+ if (match.kind !== "mapped")
1853
+ return url;
1854
+ if (keepMissing && !existsSync(match.localPath))
1855
+ return url;
1856
+ return match.virtualPath;
1857
+ });
161
1858
  }
162
- function rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl) {
163
- let changed = false;
1859
+ function rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, isServable) {
164
1860
  const shouldRewrite = (path) => {
165
1861
  if (!path.startsWith("/"))
166
1862
  return false;
167
- return staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
1863
+ if (staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`)))
1864
+ return true;
1865
+ return isServable !== undefined && isServable(path);
168
1866
  };
169
- for (const [selector, attr] of URL_ATTR_SELECTORS) {
170
- for (const el of document.querySelectorAll(selector)) {
171
- const val = el.getAttribute(attr) ?? "";
172
- if (shouldRewrite(val)) {
173
- el.setAttribute(attr, `${serverBaseUrl}${val}`);
174
- changed = true;
175
- }
1867
+ return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
1868
+ }
1869
+ /**
1870
+ * Resolves relative URLs on custom elements (`<a-asset-item>`,
1871
+ * `<model-viewer>`, and any tag name containing a dash) to absolute server
1872
+ * URLs.
1873
+ *
1874
+ * Vivliostyle resolves the subresource attributes it knows (`<img>`,
1875
+ * `<iframe>`, …) correctly, but mangles relative URLs on elements it does not
1876
+ * understand — `../tiles/model.glb` on an `<a-asset-item>` came back as
1877
+ * `http://tiles/model.glb`. Absolute server URLs always resolve, so pages hand
1878
+ * the viewer those instead. Standard elements are left alone (the viewer and
1879
+ * the runtime URL shim already handle them); only dash-tagged elements, whose
1880
+ * attributes the viewer cannot be trusted with, are rewritten.
1881
+ */
1882
+ function rewriteCustomElementUrlsInDom(document, documentDirUrl) {
1883
+ let changed = false;
1884
+ const resolveOne = (url) => {
1885
+ const current = url.trim();
1886
+ if (current === "" || current.startsWith("#") || current.startsWith("?") || current.startsWith("//"))
1887
+ return current;
1888
+ // Absolute URLs (http:, data:, blob:, …) resolve as-is; root-relative ones
1889
+ // are covered by the server-URL rewrite.
1890
+ if (/^[a-z][a-z0-9+.-]*:/i.test(current) || current.startsWith("/"))
1891
+ return current;
1892
+ try {
1893
+ const resolved = new URL(current, documentDirUrl).href;
1894
+ return resolved === current ? current : resolved;
1895
+ }
1896
+ catch {
1897
+ return current;
1898
+ }
1899
+ };
1900
+ const apply = (el, attr) => {
1901
+ const raw = el.getAttribute(attr);
1902
+ if (raw === null)
1903
+ return;
1904
+ if (attr === "src") {
1905
+ const next = resolveOne(raw);
1906
+ if (next === raw.trim() || next === raw)
1907
+ return;
1908
+ el.setAttribute(attr, next);
1909
+ changed = true;
1910
+ return;
176
1911
  }
1912
+ const kept = raw
1913
+ .split(",")
1914
+ .map((candidate) => candidate.trim())
1915
+ .filter(Boolean)
1916
+ .map((candidate) => {
1917
+ const [url, ...descriptor] = candidate.split(/\s+/);
1918
+ return [resolveOne(url), ...descriptor].join(" ");
1919
+ });
1920
+ const next = kept.join(", ");
1921
+ if (next === raw)
1922
+ return;
1923
+ el.setAttribute(attr, next);
1924
+ changed = true;
1925
+ };
1926
+ for (const el of document.querySelectorAll("[src],[srcset]")) {
1927
+ // Tag names are upper-cased in HTML documents; the dash test is case-free.
1928
+ if (!el.tagName.includes("-"))
1929
+ continue;
1930
+ apply(el, "src");
1931
+ apply(el, "srcset");
177
1932
  }
178
1933
  return changed;
179
1934
  }
1935
+ /**
1936
+ * Returns a predicate that reports whether a root-relative path can be served
1937
+ * from one of the configured asset-base local roots.
1938
+ *
1939
+ * Absolute URLs that were rewritten to root-relative virtual paths (see
1940
+ * rewriteAbsoluteUrlsInDom) are not necessarily part of the static map — an
1941
+ * `<img src>` is never collected by extractUrlsFromHtml — but the static server
1942
+ * resolves any request path against an asset-base localBase, so those paths are
1943
+ * servable and must be pointed at the server instead of being resolved against
1944
+ * the file system location of the input document.
1945
+ */
1946
+ function createAssetBasePathProbe(assetBases) {
1947
+ return (virtualPath) => {
1948
+ for (const ab of assetBases) {
1949
+ const localPath = resolve(ab.localBase, virtualPath.replace(/^\//, ""));
1950
+ if (existsSync(localPath)) {
1951
+ log.trace("createAssetBasePathProbe: servable via asset-base", { virtualPath, localPath });
1952
+ return true;
1953
+ }
1954
+ }
1955
+ return false;
1956
+ };
1957
+ }
180
1958
  // ---------------------------------------------------------------------------
181
1959
  // String-level wrappers (kept for external callers / tests)
182
1960
  // ---------------------------------------------------------------------------
@@ -214,16 +1992,27 @@ function extractUrlsFromHtml(htmlPath, includeScripts = true, doc) {
214
1992
  document = new JSDOM(content).window.document;
215
1993
  }
216
1994
  const urls = new Set();
217
- for (const el of document.querySelectorAll("link[href]")) {
218
- const href = el.getAttribute("href")?.trim();
219
- if (href)
220
- urls.add(href);
221
- }
222
- if (includeScripts) {
223
- for (const el of document.querySelectorAll("script[src]")) {
224
- const src = el.getAttribute("src")?.trim();
225
- if (src)
226
- urls.add(src);
1995
+ // Every subresource is collected, not just <link> and <script>: an <img> that
1996
+ // is not part of the static map can only be resolved by the fallback roots of
1997
+ // the static server, and a missing one would fail silently.
1998
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
1999
+ if (selector === "script[src]" && !includeScripts)
2000
+ continue;
2001
+ for (const el of document.querySelectorAll(selector)) {
2002
+ const raw = el.getAttribute(attr);
2003
+ if (raw === null)
2004
+ continue;
2005
+ if (attr !== "srcset") {
2006
+ const url = raw.trim();
2007
+ if (url)
2008
+ urls.add(url);
2009
+ continue;
2010
+ }
2011
+ for (const candidate of raw.split(",")) {
2012
+ const url = candidate.trim().split(/\s+/)[0] ?? "";
2013
+ if (url)
2014
+ urls.add(url);
2015
+ }
227
2016
  }
228
2017
  }
229
2018
  return [...urls];
@@ -231,25 +2020,7 @@ function extractUrlsFromHtml(htmlPath, includeScripts = true, doc) {
231
2020
  // ---------------------------------------------------------------------------
232
2021
  // Preview HTML builder
233
2022
  // ---------------------------------------------------------------------------
234
- /**
235
- * Rewrites absolute external URLs to root-relative virtual paths and writes
236
- * the result as a sibling of the original input file so that
237
- * cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
238
- *
239
- * The output filename uses a non-dotfile prefix so Vite's static server
240
- * (which ignores dotfiles by default) can serve it correctly.
241
- *
242
- * Also derives extra static mounts from each assetBase so that secondary
243
- * assets referenced from CSS (fonts, images) are served by Vivliostyle's
244
- * own Vite server without needing Express.
245
- *
246
- * Returns:
247
- * - htmlPath – sibling file path, or inputAbs if no rewriting was needed
248
- * - extraStatic – virtual→local entries for assetBase roots to merge into
249
- * the static map passed to Vivliostyle
250
- * - cleanup – deletes the sibling file (no-op if inputAbs was returned)
251
- */
252
- function buildPreviewHtml(inputAbs, assetBases, dbg) {
2023
+ function buildPreviewHtml(inputAbs, assetBases, options = {}) {
253
2024
  let content;
254
2025
  try {
255
2026
  content = readFileSync(inputAbs, "utf-8");
@@ -257,8 +2028,6 @@ function buildPreviewHtml(inputAbs, assetBases, dbg) {
257
2028
  catch (err) {
258
2029
  throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
259
2030
  }
260
- // Derive extra static mounts for each assetBase root so secondary assets
261
- // referenced from CSS are also reachable through Vivliostyle's Vite server.
262
2031
  const extraStatic = {};
263
2032
  for (const ab of assetBases) {
264
2033
  let virtualPrefix;
@@ -272,37 +2041,49 @@ function buildPreviewHtml(inputAbs, assetBases, dbg) {
272
2041
  virtualPrefix = `${virtualPrefix}/`;
273
2042
  const mapKey = virtualPrefix === "/" ? "/" : virtualPrefix.slice(0, -1);
274
2043
  if (Object.hasOwn(extraStatic, mapKey)) {
275
- console.warn(`[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`);
2044
+ log.warn(`[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`);
276
2045
  }
277
2046
  extraStatic[mapKey] = resolve(ab.localBase);
278
- dbg("buildPreviewHtml: assetBase extra static mount", {
279
- mapKey,
280
- local: ab.localBase
281
- });
2047
+ log.trace("buildPreviewHtml: assetBase extra static mount", { mapKey, local: ab.localBase });
282
2048
  }
283
2049
  const dom = new JSDOM(content);
284
2050
  const document = dom.window.document;
285
2051
  const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
286
2052
  if (changed)
287
- dbg("buildPreviewHtml: rewrote absolute URLs → virtual paths");
288
- if (!changed) {
289
- dbg("buildPreviewHtml: no URL rewrites needed, using original file");
2053
+ log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
2054
+ // Same custom-element fix as the build path: the viewer mangles relative
2055
+ // URLs on elements it does not understand. Only applied when the caller
2056
+ // knows the document's directory on the server (see startPreview).
2057
+ const customChanged = options.documentBaseUrl === undefined || options.documentBaseUrl === null
2058
+ ? false
2059
+ : rewriteCustomElementUrlsInDom(document, options.documentBaseUrl);
2060
+ if (customChanged)
2061
+ log.trace("buildPreviewHtml: resolved custom-element URLs → server URLs");
2062
+ const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
2063
+ if (dropped.length > 0)
2064
+ reportDroppedRemoteRefs(dropped);
2065
+ if (!changed && !customChanged && dropped.length === 0) {
2066
+ log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
290
2067
  return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
291
2068
  }
292
- const inputDir = dirname(inputAbs);
293
- const inputBase = inputAbs.slice(inputDir.length + 1);
294
- const outputBase = `_vivliostyle_preview_${inputBase}`;
295
- const htmlPath = join(inputDir, outputBase);
2069
+ const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
2070
+ const htmlPath = dumpDir === null ? join(dirname(inputAbs), `_vivliostyle_preview_${basename(inputAbs)}`) : join(dumpDir, basename(inputAbs));
2071
+ if (dumpDir !== null)
2072
+ mkdirSync(dumpDir, { recursive: true });
296
2073
  writeFileSync(htmlPath, dom.serialize(), "utf-8");
297
- dbg("buildPreviewHtml: wrote rewritten HTML alongside original", htmlPath);
298
- console.log(`[preview] Wrote rewritten HTML: ${htmlPath}`);
2074
+ log.trace("buildPreviewHtml: wrote rewritten HTML", htmlPath);
2075
+ log.info(`[preview] Wrote rewritten HTML: ${htmlPath}`);
299
2076
  const cleanup = () => {
2077
+ if (dumpDir !== null) {
2078
+ log.trace("buildPreviewHtml: keeping dumped HTML", htmlPath);
2079
+ return;
2080
+ }
300
2081
  try {
301
2082
  rmSync(htmlPath, { force: true });
302
- dbg("buildPreviewHtml: removed rewritten HTML", htmlPath);
2083
+ log.trace("buildPreviewHtml: removed rewritten HTML", htmlPath);
303
2084
  }
304
2085
  catch (err) {
305
- console.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
2086
+ log.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
306
2087
  }
307
2088
  };
308
2089
  return { htmlPath, extraStatic, cleanup };
@@ -310,13 +2091,7 @@ function buildPreviewHtml(inputAbs, assetBases, dbg) {
310
2091
  // ---------------------------------------------------------------------------
311
2092
  // Build HTML builder
312
2093
  // ---------------------------------------------------------------------------
313
- /**
314
- * Prepares the HTML for BUILD mode.
315
- * Both rewrite passes (absolute → virtual, virtual → absolute server URL)
316
- * are applied in a single DOM parse.
317
- * If nothing changed the original file path is returned with a no-op cleanup.
318
- */
319
- function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl, dbg) {
2094
+ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl, options = {}) {
320
2095
  let content;
321
2096
  try {
322
2097
  content = readFileSync(inputAbs, "utf-8");
@@ -327,28 +2102,70 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
327
2102
  const dom = new JSDOM(content);
328
2103
  const document = dom.window.document;
329
2104
  const staticMapKeys = Object.keys(staticMap);
330
- const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases);
2105
+ const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases, options.fetchMissing === true);
331
2106
  if (absChanged)
332
- dbg("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
333
- const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl);
2107
+ log.trace("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
2108
+ const probe = assetBases.length > 0 ? createAssetBasePathProbe(assetBases) : undefined;
2109
+ const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
334
2110
  if (srvChanged)
335
- dbg("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
336
- if (!absChanged && !srvChanged) {
337
- dbg("prepareInputHtmlForBuild: no changes, using original file");
2111
+ log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
2112
+ const customBase = options.documentBaseUrl ?? `${serverBaseUrl}/`;
2113
+ const customChanged = rewriteCustomElementUrlsInDom(document, customBase);
2114
+ if (customChanged)
2115
+ log.trace("prepareInputHtmlForBuild: resolved custom-element URLs → server URLs", { customBase });
2116
+ const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
2117
+ const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
2118
+ if (dropped.length > 0)
2119
+ reportDroppedRemoteRefs(dropped);
2120
+ const unserved = collectUnservedVirtualPaths(document, staticMapKeys, probe);
2121
+ if (unserved.length > 0)
2122
+ reportUnservedVirtualPaths(unserved);
2123
+ // The runtime script only matters for pages that run scripts; injecting it
2124
+ // into a plain document would rewrite the file for nothing.
2125
+ const hasScripts = document.querySelector("script") !== null;
2126
+ const wantsRuntime = (options.shimOrigin != null && hasScripts) || options.settle != null;
2127
+ if (wantsRuntime) {
2128
+ const origin = options.shimOrigin ?? serverBaseUrl;
2129
+ const documentBaseUrl = options.documentBaseUrl ?? `${origin}/`;
2130
+ // Only the PDF run expands `<details>`; the preview stays interactive.
2131
+ injectRuntimeScriptInDom(document, { origin, documentBaseUrl, gate: options.settle ?? null, expandDetails: true });
2132
+ log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
2133
+ }
2134
+ if (!absChanged &&
2135
+ !srvChanged &&
2136
+ !customChanged &&
2137
+ dropped.length === 0 &&
2138
+ gone.length === 0 &&
2139
+ options.settle == null &&
2140
+ !wantsRuntime) {
2141
+ log.trace("prepareInputHtmlForBuild: no changes, using original file");
338
2142
  return { vivliostyleInput: inputAbs, cleanup: () => undefined };
339
2143
  }
340
- const tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
341
- const tmpHtml = join(tmpDir, "index.html");
2144
+ const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
2145
+ let tmpDir = null;
2146
+ let tmpHtml;
2147
+ if (dumpDir !== null) {
2148
+ mkdirSync(dumpDir, { recursive: true });
2149
+ tmpHtml = join(dumpDir, basename(inputAbs));
2150
+ }
2151
+ else {
2152
+ tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
2153
+ tmpHtml = join(tmpDir, "index.html");
2154
+ }
342
2155
  writeFileSync(tmpHtml, dom.serialize(), "utf-8");
343
- console.log(`[html] Prepared input HTML → ${tmpHtml}`);
344
- dbg("prepareInputHtmlForBuild: written to temp file", tmpHtml);
2156
+ log.info(`[html] ${dumpDir === null ? "Prepared" : "Dumped"} input HTML → ${tmpHtml}`);
2157
+ log.trace("prepareInputHtmlForBuild: written", tmpHtml);
345
2158
  const cleanup = () => {
2159
+ if (tmpDir === null) {
2160
+ log.trace("prepareInputHtmlForBuild: keeping dumped HTML", tmpHtml);
2161
+ return;
2162
+ }
346
2163
  try {
347
2164
  rmSync(tmpDir, { recursive: true, force: true });
348
- dbg("prepareInputHtmlForBuild: removed temp dir", tmpDir);
2165
+ log.trace("prepareInputHtmlForBuild: removed temp dir", tmpDir);
349
2166
  }
350
2167
  catch (err) {
351
- console.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
2168
+ log.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
352
2169
  }
353
2170
  };
354
2171
  return { vivliostyleInput: tmpHtml, cleanup };
@@ -380,62 +2197,43 @@ function parseAssetBaseMapping(value) {
380
2197
  }
381
2198
  return { urlBase: normalizeUrlBase(urlBase), localBase };
382
2199
  }
383
- function mapAbsoluteUrlToLocal(url, assetBases) {
384
- for (const mapping of assetBases) {
385
- if (!url.startsWith(mapping.urlBase))
386
- continue;
387
- let cleanRelative;
388
- try {
389
- cleanRelative = new URL(url).pathname.slice(1);
390
- }
391
- catch {
392
- const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
393
- cleanRelative = noQuery.split("#")[0];
394
- }
395
- if (!cleanRelative)
396
- return null;
397
- const virtualPath = posix.resolve("/", cleanRelative);
398
- const localPath = resolve(mapping.localBase, cleanRelative);
399
- return { virtualPath, localPath };
400
- }
401
- return null;
402
- }
403
- function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
2200
+ function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets) {
404
2201
  const trimmed = url.trim();
405
2202
  if (!trimmed)
406
2203
  return { kind: "skipped", url, reason: "empty URL" };
407
2204
  if (trimmed.startsWith("#"))
408
2205
  return { kind: "skipped", url, reason: "fragment-only URL" };
409
- const absoluteMapped = mapAbsoluteUrlToLocal(trimmed, assetBases);
410
- if (absoluteMapped) {
411
- if (shouldIgnoreVirtualPath(absoluteMapped.virtualPath, ignoredAssets)) {
412
- dbg("urlToStaticMapping: ignored (asset-base match)", {
413
- url,
414
- ...absoluteMapped
415
- });
2206
+ const assetMatch = mapAbsoluteUrlToLocal(trimmed, assetBases);
2207
+ if (assetMatch.kind === "root-only") {
2208
+ return {
2209
+ kind: "skipped",
2210
+ url,
2211
+ reason: "URL matches an asset-base prefix but has no path component (root URL)"
2212
+ };
2213
+ }
2214
+ if (assetMatch.kind === "mapped") {
2215
+ if (shouldIgnoreVirtualPath(assetMatch.virtualPath, ignoredAssets)) {
2216
+ log.trace("urlToStaticMapping: ignored (asset-base match)", { url, ...assetMatch });
416
2217
  return {
417
2218
  kind: "skipped",
418
2219
  url,
419
- reason: `matches --ignore-asset "${absoluteMapped.virtualPath}"`
2220
+ reason: `matches --ignore-asset "${assetMatch.virtualPath}"`
420
2221
  };
421
2222
  }
422
- if (!existsSync(absoluteMapped.localPath)) {
423
- console.warn(`[html] Warning: asset-base mapped path does not exist\n` +
2223
+ if (!existsSync(assetMatch.localPath)) {
2224
+ log.warn(`[html] Warning: asset-base mapped path does not exist\n` +
424
2225
  ` url : ${url}\n` +
425
- ` virtual : ${absoluteMapped.virtualPath}\n` +
426
- ` local : ${absoluteMapped.localPath}`);
2226
+ ` virtual : ${assetMatch.virtualPath}\n` +
2227
+ ` local : ${assetMatch.localPath}`);
427
2228
  }
428
2229
  return {
429
2230
  kind: "mapped",
430
- mapping: `${absoluteMapped.virtualPath}:${absoluteMapped.localPath}`
2231
+ mapping: `${assetMatch.virtualPath}:${assetMatch.localPath}`
431
2232
  };
432
2233
  }
2234
+ // assetMatch.kind === "no-match" — proceed to local / external handling
433
2235
  if (trimmed.startsWith("//")) {
434
- return {
435
- kind: "skipped",
436
- url,
437
- reason: "protocol-relative external URL"
438
- };
2236
+ return { kind: "skipped", url, reason: "protocol-relative external URL" };
439
2237
  }
440
2238
  if (/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(trimmed)) {
441
2239
  const protocol = trimmed.slice(0, trimmed.indexOf(":"));
@@ -456,10 +2254,7 @@ function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
456
2254
  const localPath = resolve(htmlDir, cleanUrl);
457
2255
  const virtualPath = cleanUrl.startsWith("/") ? posix.normalize(cleanUrl) : posix.resolve("/", posix.relative(htmlDir, localPath));
458
2256
  if (shouldIgnoreVirtualPath(virtualPath, ignoredAssets)) {
459
- dbg("urlToStaticMapping: ignored (ignore-asset match)", {
460
- url,
461
- virtualPath
462
- });
2257
+ log.trace("urlToStaticMapping: ignored (ignore-asset match)", { url, virtualPath });
463
2258
  return {
464
2259
  kind: "skipped",
465
2260
  url,
@@ -467,7 +2262,7 @@ function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
467
2262
  };
468
2263
  }
469
2264
  if (!existsSync(localPath)) {
470
- console.warn(`[html] Warning: referenced path does not exist\n` +
2265
+ log.warn(`[html] Warning: referenced path does not exist\n` +
471
2266
  ` url : ${url}\n` +
472
2267
  ` virtual : ${virtualPath}\n` +
473
2268
  ` local : ${localPath}`);
@@ -496,7 +2291,7 @@ function buildStaticMap(rawMappings) {
496
2291
  for (const mapping of rawMappings) {
497
2292
  const { virtual, local } = parseStaticMapping(mapping);
498
2293
  if (Object.hasOwn(map, virtual)) {
499
- console.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
2294
+ log.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
500
2295
  }
501
2296
  map[virtual] = local;
502
2297
  }
@@ -505,40 +2300,53 @@ function buildStaticMap(rawMappings) {
505
2300
  // ---------------------------------------------------------------------------
506
2301
  // Extra args parser
507
2302
  // ---------------------------------------------------------------------------
2303
+ /**
2304
+ * Vivliostyle's config object uses camelCase keys (`viewerParam`, `userStyle`)
2305
+ * and typed values, so `--viewer-param` has to arrive as `viewerParam` and
2306
+ * `--timeout 60000` as the number 60000.
2307
+ */
2308
+ function normalizeExtraKey(key) {
2309
+ return key.replace(/-([a-z0-9])/g, (_match, char) => char.toUpperCase());
2310
+ }
2311
+ function coerceExtraValue(value) {
2312
+ if (value === "true")
2313
+ return true;
2314
+ if (value === "false")
2315
+ return false;
2316
+ // Only plain integers, so that version-like strings ("1.9.2") stay strings.
2317
+ return /^-?\d+$/.test(value) ? Number.parseInt(value, 10) : value;
2318
+ }
508
2319
  function parseExtraArgs(extraArgs) {
509
2320
  const extraConfig = {};
2321
+ const assign = (rawKey, rawValue) => {
2322
+ extraConfig[normalizeExtraKey(rawKey)] = typeof rawValue === "boolean" ? rawValue : coerceExtraValue(rawValue);
2323
+ };
510
2324
  for (let i = 0; i < extraArgs.length; i++) {
511
2325
  const arg = extraArgs[i];
512
2326
  if (!arg.startsWith("--")) {
513
2327
  if (arg.startsWith("-")) {
514
- console.warn(`[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
2328
+ log.warn(`[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
515
2329
  ` Use the long-form --flag equivalent instead.`);
516
2330
  }
517
2331
  continue;
518
2332
  }
519
2333
  if (arg.includes("=")) {
520
2334
  const eqIdx = arg.indexOf("=");
521
- const key = arg.slice(2, eqIdx);
522
- const val = arg.slice(eqIdx + 1);
523
- extraConfig[key] = val === "true" ? true : val === "false" ? false : val;
2335
+ assign(arg.slice(2, eqIdx), arg.slice(eqIdx + 1));
524
2336
  continue;
525
2337
  }
526
2338
  const key = arg.slice(2);
527
2339
  const next = extraArgs[i + 1];
528
- if (next === "true") {
529
- extraConfig[key] = true;
530
- i++;
531
- }
532
- else if (next === "false") {
533
- extraConfig[key] = false;
2340
+ if (next === "true" || next === "false") {
2341
+ assign(key, next === "true");
534
2342
  i++;
535
2343
  }
536
- else if (next && !next.startsWith("-")) {
537
- extraConfig[key] = next;
2344
+ else if (next !== undefined && !next.startsWith("-")) {
2345
+ assign(key, next);
538
2346
  i++;
539
2347
  }
540
2348
  else {
541
- extraConfig[key] = true;
2349
+ extraConfig[normalizeExtraKey(key)] = true;
542
2350
  }
543
2351
  }
544
2352
  return extraConfig;
@@ -586,7 +2394,28 @@ function buildProgram() {
586
2394
  .option("-o, --output <file>", "Output file path", "output.pdf")
587
2395
  .option("--title <title>", "Document title (overrides the one in the source)")
588
2396
  .option("--author <author>", "Document author")
589
- .option("--language <lang>", "Document language tag (e.g. en, de, ja)", "de")
2397
+ .option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
2398
+ .option("--keywords <keywords>", "Document keywords, comma separated")
2399
+ .option("--language <lang>", "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'")
2400
+ .option("--pdfa <level>", [
2401
+ "Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
2402
+ "an OutputIntent with an embedded ICC profile (bundled sRGB unless",
2403
+ "--icc-profile is given) and a file identifier are written.",
2404
+ "Levels: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4.",
2405
+ "This is a label only: the content is neither converted nor checked,",
2406
+ "so conformance of the content is the author's responsibility."
2407
+ ].join("\n "))
2408
+ .option("--pdfx <version>", [
2409
+ "Label the output PDF as PDF/X (ISO 15930): X-4 writes the",
2410
+ "identification metadata as XMP, X-1a:2003 into the information",
2411
+ "dictionary. Both embed the --icc-profile as the OutputIntent.",
2412
+ "Same label-only semantics as --pdfa."
2413
+ ].join("\n "))
2414
+ .option("--icc-profile <path>", [
2415
+ "ICC profile embedded as the PDF output intent, e.g. a print",
2416
+ "provider's profile. Required for --pdfx; --pdfa defaults to the",
2417
+ "bundled sRGB profile."
2418
+ ].join("\n "))
590
2419
  .option("--static <mapping>", [
591
2420
  "Map a virtual path to a local directory or file.",
592
2421
  "Format: /virtual/path:/absolute/local/path",
@@ -610,7 +2439,39 @@ function buildProgram() {
610
2439
  "Example: --ignore-asset /livereload.js",
611
2440
  "Repeatable. Only applies when the input is an HTML file."
612
2441
  ].join("\n "), (val, prev) => prev.concat(val), [])
613
- .option("--cwd <dir>", "Working directory for Vivliostyle (default: directory of --input)")
2442
+ .option("--allow-remote", [
2443
+ "Keep subresource references that would be fetched from the network.",
2444
+ "By default every reference without a local file is removed from the",
2445
+ "input HTML so that nothing is loaded from the web.",
2446
+ "Hyperlinks (<a href>) are never touched. See also --fetch-missing."
2447
+ ].join("\n "))
2448
+ .option("--fetch-missing", [
2449
+ "Load references without a local file from the mapped origin instead of",
2450
+ "dropping them. The local server redirects missing files to the site",
2451
+ "origin, which also covers data that page scripts fetch by relative URL.",
2452
+ "Implies --allow-remote, so remote iframes and scripts are loaded too.",
2453
+ "Nothing is written to the input directory."
2454
+ ].join("\n "))
2455
+ .option("--wait-for-content [ms]", [
2456
+ "Delay pagination until the page's own async work finished: no request in",
2457
+ "flight, no wasm compiling, no long task running and the document height",
2458
+ "stable for --quiet-ms (default 400). Pages with <script> wait",
2459
+ "automatically (deadline 10000ms); 0 disables, larger values capped at",
2460
+ "25000ms."
2461
+ ].join("\n "))
2462
+ .option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
2463
+ .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 "))
2464
+ .option("--pixel-ratio <n>", [
2465
+ "Render at n times the output resolution (Vivliostyle pixelRatio), e.g. 2.",
2466
+ "Layout and raster resolution increase while the page keeps its size,",
2467
+ "which removes pixel artifacts in canvas and WebGL content.",
2468
+ "Pages exposing window.__vivResize(factor) are also redrawn at n×",
2469
+ "backing pixels before printing, so output past 96dpi stays sharp."
2470
+ ].join("\n "))
2471
+ .option("--dump-html <dir>", [
2472
+ "Write the rewritten input HTML into <dir> and keep it, instead of a",
2473
+ "temporary file. Use it to inspect what Vivliostyle actually renders."
2474
+ ].join("\n "))
614
2475
  .option("--format <format>", `Output format: ${validFormats.join(" | ")}`, "pdf")
615
2476
  .option("--log-level <level>", `Vivliostyle log level: ${validLogLevels.join(" | ")}`, "info")
616
2477
  .option("--mode <mode>", `Execution mode: ${validModes.join(" | ")}`, "build")
@@ -621,12 +2482,17 @@ function buildProgram() {
621
2482
  "Notes:",
622
2483
  " • HTML input (.html/.htm) is detected automatically from the file extension.",
623
2484
  " • For HTML input, <link href> and <script src> are parsed and auto-mapped.",
2485
+ " • References without a local file are dropped (offline by default); use --allow-remote to keep them.",
624
2486
  " • Options after -- are forwarded verbatim to Vivliostyle.",
625
2487
  " • --debug sets --log-level to debug automatically.",
626
2488
  " • --preview and --mode preview are equivalent.",
627
- " • In preview mode Vivliostyle serves everything via its own Vite server.",
628
- " • In build mode an Express server is started to serve assets.",
629
- " • --asset-base localBase is also a fallback root for CSS-referenced assets."
2489
+ " • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
2490
+ " • the browser prints that page to PDF, so canvases and iframes stay real content.",
2491
+ " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
2492
+ " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
2493
+ " • PDF metadata (--title/--author/--subject/--keywords/--language) overrides",
2494
+ " • values read from the document or the publication manifest; language falls",
2495
+ " • back to 'de'. --pdfa/--pdfx label the output, they do not convert content."
630
2496
  ].join("\n"));
631
2497
  }
632
2498
  function printHelp() {
@@ -649,27 +2515,153 @@ function parseArgs(argv) {
649
2515
  }
650
2516
  return { options: program.opts(), extraArgs };
651
2517
  }
2518
+ async function runRender(params) {
2519
+ const request = {
2520
+ documentUrl: params.documentUrl,
2521
+ viewerPageUrl: params.viewerPageUrl,
2522
+ output: params.outputAbs,
2523
+ viewerParams: params.viewerParams,
2524
+ timeoutMs: params.timeoutMs,
2525
+ waitForSettle: params.waitForSettle,
2526
+ ...(params.chromeExecutable === undefined ? {} : { chromeExecutable: params.chromeExecutable }),
2527
+ ...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
2528
+ ...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
2529
+ ...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
2530
+ ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
2531
+ ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
2532
+ ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
2533
+ ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
2534
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
2535
+ };
2536
+ log.trace("renderPdf request", request);
2537
+ const result = await renderPdf(request);
2538
+ log.trace("renderPdf result", { pageCount: result.pageCount, bytes: result.bytes, settle: result.settle });
2539
+ log.info(`✓ Document created: ${result.output} (${result.pageCount} pages)`);
2540
+ }
652
2541
  // ---------------------------------------------------------------------------
653
2542
  // Core execute
654
2543
  // ---------------------------------------------------------------------------
2544
+ /**
2545
+ * Log level for the wrapper's own output. `-d` wins over `--log-level`, which
2546
+ * is also forwarded to Vivliostyle unchanged.
2547
+ */
2548
+ function resolveInternalLogLevel(options) {
2549
+ if (options.debug === true)
2550
+ return "debug";
2551
+ const level = options.logLevel;
2552
+ return validLogLevels.includes(level) ? level : "info";
2553
+ }
2554
+ /**
2555
+ * `--wait-for-content [ms]`: hold the document's load event until the page's own
2556
+ * async work finished. Vivliostyle stops waiting for images after 30s, so the
2557
+ * hard limit is capped below that.
2558
+ */
2559
+ const MAX_SETTLE_DEADLINE_MS = 25_000;
2560
+ /** Deadline for the automatic wait on script-driven pages (see below). */
2561
+ const AUTO_SETTLE_DEADLINE_MS = 10_000;
2562
+ function resolveSettleGate(options) {
2563
+ const raw = options.waitForContent;
2564
+ if (raw === undefined || raw === false)
2565
+ return null;
2566
+ // Explicit 0 disables the wait — including the automatic one for pages
2567
+ // with scripts (see resolveEffectiveSettle).
2568
+ if (raw === "0")
2569
+ return null;
2570
+ const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
2571
+ if (!Number.isFinite(requested) || requested <= 0)
2572
+ throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
2573
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
2574
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0)
2575
+ throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
2576
+ return {
2577
+ quietMs: quietRaw,
2578
+ deadlineMs: Math.min(requested, MAX_SETTLE_DEADLINE_MS)
2579
+ };
2580
+ }
2581
+ /**
2582
+ * Settle gate that actually applies: an explicit `--wait-for-content` wins;
2583
+ * otherwise pages that run scripts wait automatically (charts, wasm, WebGL
2584
+ * would otherwise race pagination), static pages don't wait at all.
2585
+ */
2586
+ function resolveEffectiveSettle(options, hasScripts) {
2587
+ const explicit = resolveSettleGate(options);
2588
+ if (explicit !== null || options.waitForContent !== undefined)
2589
+ return { gate: explicit, autoArmed: false };
2590
+ if (!hasScripts)
2591
+ return { gate: null, autoArmed: false };
2592
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
2593
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0)
2594
+ throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
2595
+ return { gate: { quietMs: quietRaw, deadlineMs: AUTO_SETTLE_DEADLINE_MS }, autoArmed: true };
2596
+ }
2597
+ // ---------------------------------------------------------------------------
2598
+ // PDF metadata + standards labeling resolution
2599
+ // ---------------------------------------------------------------------------
2600
+ function describePdfLabel(label) {
2601
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
2602
+ }
2603
+ /**
2604
+ * `--pdfa` / `--pdfx`: mutually exclusive standards labels for the output PDF.
2605
+ */
2606
+ function resolvePdfLabel(options) {
2607
+ if (options.pdfa !== undefined && options.pdfx !== undefined) {
2608
+ throw new Error("--pdfa and --pdfx are mutually exclusive — choose one standard label");
2609
+ }
2610
+ if (options.pdfa !== undefined)
2611
+ return parsePdfaLabel(options.pdfa);
2612
+ if (options.pdfx !== undefined)
2613
+ return parsePdfxLabel(options.pdfx);
2614
+ return undefined;
2615
+ }
2616
+ /**
2617
+ * `--icc-profile <path>`: the profile the OutputIntent embeds. PDF/X always
2618
+ * needs one; a PDF/A build without the flag embeds the bundled sRGB profile.
2619
+ */
2620
+ function resolveIccProfile(options, label) {
2621
+ if (options.iccProfile !== undefined) {
2622
+ const path = resolve(options.iccProfile);
2623
+ if (!existsSync(path))
2624
+ throw new Error(`--icc-profile file does not exist: ${path}`);
2625
+ return { bytes: readFileSync(path), name: basename(path) };
2626
+ }
2627
+ if (label === undefined)
2628
+ return undefined;
2629
+ if (label.kind === "pdfx") {
2630
+ throw new Error(`--pdfx ${label.version} requires --icc-profile <path>: PDF/X output intents carry an ICC profile`);
2631
+ }
2632
+ return loadDefaultIccProfile();
2633
+ }
2634
+ /**
2635
+ * Document metadata for the PDF: the flags override values taken from the
2636
+ * input (HTML meta tags or a publication manifest); the language falls back
2637
+ * to "de" when no source provides one.
2638
+ */
2639
+ function resolvePdfMetadata(options, inputAbs, htmlMode) {
2640
+ const cliFields = pickDefinedStrings(options, ["title", "author", "subject", "keywords", "language"]);
2641
+ let derived;
2642
+ if (htmlMode) {
2643
+ derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
2644
+ }
2645
+ else if (/\.json$/i.test(inputAbs)) {
2646
+ derived = extractMetadataFromManifest(readFileSync(inputAbs, "utf-8"));
2647
+ if (derived === undefined)
2648
+ log.warn(`[metadata] ${inputAbs} is not a JSON publication manifest — no manifest metadata`);
2649
+ }
2650
+ log.trace("metadata (derived)", derived);
2651
+ return resolveMetadata(cliFields, derived);
2652
+ }
655
2653
  async function execute(options, extraArgs = []) {
656
- const debugEnabled = !!(options.debug || options.logLevel === "debug");
657
- const dbg = makeDbg(debugEnabled);
658
- dbg("raw CLI options", options);
659
- dbg("extra args (after --)", extraArgs);
2654
+ log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
2655
+ log.trace("raw CLI options", options);
2656
+ log.trace("extra args (after --)", extraArgs);
660
2657
  if (!options.input)
661
2658
  throw new Error("Missing required option: --input");
662
2659
  const inputAbs = resolve(options.input);
663
- dbg("resolved input", inputAbs);
2660
+ log.trace("resolved input", inputAbs);
664
2661
  if (!existsSync(inputAbs))
665
2662
  throw new Error(`Input file does not exist: ${inputAbs}`);
666
- const cwd = options.cwd ? resolve(options.cwd) : dirname(inputAbs);
667
- if (!existsSync(cwd)) {
668
- throw new Error(`Working directory does not exist: ${cwd}`);
669
- }
670
- dbg("cwd", cwd);
671
2663
  const outputAbs = resolve(options.output);
672
- dbg("resolved output", outputAbs);
2664
+ log.trace("resolved output", outputAbs);
673
2665
  if (!validFormats.includes(options.format)) {
674
2666
  throw new Error(`Invalid format: "${options.format}". Allowed: ${validFormats.join(", ")}`);
675
2667
  }
@@ -678,182 +2670,282 @@ async function execute(options, extraArgs = []) {
678
2670
  throw new Error(`Invalid log level: "${options.logLevel}". Allowed: ${validLogLevels.join(", ")}`);
679
2671
  }
680
2672
  const logLevel = options.debug ? "debug" : options.logLevel;
681
- dbg("logLevel", logLevel);
2673
+ log.trace("logLevel", logLevel);
682
2674
  const mode = (options.preview ? "preview" : options.mode);
683
2675
  if (!validModes.includes(mode)) {
684
2676
  throw new Error(`Invalid mode: "${mode}". Allowed: ${validModes.join(", ")}`);
685
2677
  }
686
- dbg("mode", mode);
2678
+ log.trace("mode", mode);
687
2679
  const htmlMode = isHtmlInput(inputAbs);
688
- dbg("htmlMode (auto-detected)", htmlMode);
2680
+ log.trace("htmlMode (auto-detected)", htmlMode);
689
2681
  if (!htmlMode) {
690
2682
  if (options.assetBase.length > 0) {
691
- console.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
2683
+ log.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
692
2684
  }
693
2685
  if (options.ignoreAsset.length > 0) {
694
- console.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
2686
+ log.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
695
2687
  }
696
2688
  }
697
2689
  const assetBases = options.assetBase.map(parseAssetBaseMapping);
698
- dbg("parsed assetBases", assetBases);
2690
+ log.trace("parsed assetBases", assetBases);
699
2691
  const ignoredAssets = new Set(options.ignoreAsset.map(normalizeIgnoreAssetPath));
700
- dbg("ignoredAssets", [...ignoredAssets]);
2692
+ log.trace("ignoredAssets", [...ignoredAssets]);
701
2693
  // ── HTML-derived mappings ────────────────────────────────────────────────
702
2694
  const derivedMappings = [];
703
2695
  if (htmlMode) {
704
2696
  const htmlDir = dirname(inputAbs);
705
- console.log(`[html] Analysing input as HTML: ${inputAbs}`);
2697
+ log.info(`[html] Analysing input as HTML: ${inputAbs}`);
706
2698
  const includeScripts = mode === "preview" ? true : options.scripts;
707
2699
  const urls = extractUrlsFromHtml(inputAbs, includeScripts);
708
2700
  if (urls.length === 0) {
709
- console.log("[html] No URLs found in input HTML");
2701
+ log.info("[html] No URLs found in input HTML");
710
2702
  }
711
2703
  else {
712
- console.log(`[html] Found URLs (${urls.length}):`);
2704
+ log.info(`[html] Found URLs (${urls.length}):`);
713
2705
  }
714
2706
  for (const url of urls) {
715
- const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg);
2707
+ const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets);
716
2708
  if (result.kind === "skipped") {
717
- console.log(` → Skipped (${result.reason}): ${url}`);
2709
+ log.info(` → Skipped (${result.reason}): ${url}`);
718
2710
  continue;
719
2711
  }
720
- console.log(` → Mapping: ${result.mapping}`);
2712
+ log.info(` → Mapping: ${result.mapping}`);
721
2713
  derivedMappings.push(result.mapping);
722
2714
  }
723
- dbg("derived static mappings from HTML", derivedMappings);
2715
+ log.trace("derived static mappings from HTML", derivedMappings);
724
2716
  }
725
2717
  // ── static map ────────────────────────────────────────────────────────────
726
2718
  const allStaticMappings = [...options.static, ...derivedMappings];
727
- dbg("all raw static mappings", allStaticMappings);
2719
+ log.trace("all raw static mappings", allStaticMappings);
728
2720
  const staticMap = buildStaticMap(allStaticMappings);
729
- dbg("assembled staticMap", staticMap);
730
- const hasStatic = Object.keys(staticMap).length > 0;
2721
+ log.trace("assembled staticMap", staticMap);
2722
+ // Mappings derived from the HTML have already been reported by
2723
+ // urlToStaticMapping; only explicit --static mounts are checked here.
2724
+ const derivedVirtualPaths = new Set(derivedMappings.map((mapping) => parseStaticMapping(mapping).virtual));
731
2725
  for (const [virtualPath, localPath] of Object.entries(staticMap)) {
2726
+ if (derivedVirtualPaths.has(virtualPath))
2727
+ continue;
732
2728
  if (!existsSync(localPath)) {
733
- console.warn(`[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`);
2729
+ log.warn(`[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`);
734
2730
  }
735
2731
  }
736
2732
  const extraConfig = parseExtraArgs(extraArgs);
737
- dbg("extraConfig (parsed from -- args)", extraConfig);
738
- const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
739
- console.log(`Starting Vivliostyle in mode: ${mode}`);
740
- // ── BUILD mode ─────────────────────────────────────────────────────────────
2733
+ log.trace("extraConfig (parsed from -- args)", extraConfig);
2734
+ const metaFields = resolvePdfMetadata(options, inputAbs, htmlMode);
2735
+ const pdfLabel = resolvePdfLabel(options);
2736
+ if (pdfLabel !== undefined)
2737
+ log.info(`[pdf] labeling the output as ${describePdfLabel(pdfLabel)}`);
2738
+ if (options.iccProfile !== undefined && pdfLabel === undefined) {
2739
+ log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
2740
+ }
2741
+ const iccProfile = resolveIccProfile(options, pdfLabel);
2742
+ const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
2743
+ // The wait arms automatically on script-driven pages: without it, charts,
2744
+ // wasm and WebGL race pagination and the PDF ships half-painted content.
2745
+ const hasScripts = htmlMode && new JSDOM(readFileSync(inputAbs, "utf-8")).window.document.querySelector("script") !== null;
2746
+ const { gate: settle, autoArmed } = resolveEffectiveSettle(options, hasScripts);
2747
+ if (autoArmed)
2748
+ log.info(`[wait] auto-armed for script-driven page (deadline ${AUTO_SETTLE_DEADLINE_MS}ms, disable with --wait-for-content 0)`);
2749
+ const htmlOptions = {
2750
+ allowRemote: fetchMissing,
2751
+ fetchMissing,
2752
+ dumpDir: options.dumpHtml ?? null,
2753
+ settle,
2754
+ ...(typeof extraConfig.css === "string" ? { css: extraConfig.css } : {}),
2755
+ ...(typeof extraConfig.userStyle === "string" ? { userStyle: extraConfig.userStyle } : {})
2756
+ };
2757
+ log.trace("htmlRewriteOptions", htmlOptions);
2758
+ if (options.timeout !== undefined) {
2759
+ const timeoutMs = Number.parseInt(options.timeout, 10);
2760
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
2761
+ throw new Error(`Invalid --timeout: "${options.timeout}"`);
2762
+ extraConfig.timeout = timeoutMs;
2763
+ log.info(`[render] timeout=${timeoutMs}ms`);
2764
+ }
2765
+ if (options.pixelRatio !== undefined) {
2766
+ const ratio = Number.parseFloat(options.pixelRatio);
2767
+ if (!Number.isFinite(ratio) || ratio <= 0)
2768
+ throw new Error(`Invalid --pixel-ratio: "${options.pixelRatio}"`);
2769
+ const existing = typeof extraConfig.viewerParam === "string" ? extraConfig.viewerParam : "";
2770
+ extraConfig.viewerParam = existing === "" ? `pixelRatio=${ratio}` : `${existing}&pixelRatio=${ratio}`;
2771
+ log.info(`[render] pixelRatio=${ratio}`);
2772
+ }
2773
+ // Canvas/WebGL backing-store upscale follows --pixel-ratio: layout keeps its
2774
+ // CSS size while JS-painted pixels are redrawn at n× resolution so print
2775
+ // output past 96dpi stays sharp. Pages opt in via window.__vivResize(factor).
2776
+ const canvasScale = options.pixelRatio === undefined
2777
+ ? undefined
2778
+ : (() => {
2779
+ const ratio = Number.parseFloat(options.pixelRatio);
2780
+ return Number.isFinite(ratio) && ratio > 1 ? ratio : undefined;
2781
+ })();
2782
+ log.info(`Starting Vivliostyle in mode: ${mode}`);
2783
+ // ── BUILD mode ───────────────────────────────────────────────────────────────
741
2784
  if (mode === "build") {
742
- let vivliostyleInput = inputAbs;
743
- let htmlCleanup = () => undefined;
744
- if (hasStatic || assetBases.length > 0) {
745
- const server = await startStaticServer(staticMap, assetBases, null, dbg);
746
- try {
747
- if (htmlMode) {
748
- ({ vivliostyleInput, cleanup: htmlCleanup } = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, dbg));
749
- }
750
- dbg("vivliostyleInput (final)", vivliostyleInput);
751
- const config = {
752
- cwd,
753
- input: vivliostyleInput,
754
- output: [{ path: outputAbs, format }],
755
- ...metaFields,
756
- logLevel,
757
- ...(options.debug ? { debug: true } : {}),
758
- ...extraConfig
759
- };
760
- dbg("final BuildConfig", config);
761
- await build(config);
762
- console.log(`✓ Document created: ${outputAbs}`);
2785
+ if (format !== "pdf")
2786
+ throw new Error(`Unsupported format: ${format}. This renderer produces PDF only.`);
2787
+ const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
2788
+ const viewerLibDir = resolveViewerLibDir();
2789
+ log.trace("viewerLibDir", viewerLibDir);
2790
+ log.trace("sitePath", sitePath);
2791
+ const entry = { localPath: null, sitePath };
2792
+ const server = await startStaticServer({
2793
+ staticMap,
2794
+ assetBases,
2795
+ entry,
2796
+ fetchMissing: htmlOptions.fetchMissing === true,
2797
+ settle: htmlOptions.settle ?? null,
2798
+ viewerLibDir,
2799
+ viewerFilePath: join(viewerLibDir, "index.html"),
2800
+ log: (message) => log.info(message),
2801
+ onSettled: ({ reason, waitedMs, detail }) => {
2802
+ // Detail is logged in both branches: the deadline case is exactly
2803
+ // when canvas sizes and readiness matter most (e.g. slow WebGL).
2804
+ const line = `[wait] layout gate ${reason} after ${waitedMs}ms`;
2805
+ const withDetail = detail === undefined ? line : `${line} ${JSON.stringify(detail)}`;
2806
+ if (reason === "settled")
2807
+ log.info(withDetail);
2808
+ else
2809
+ log.warn(`${withDetail} — content may be incomplete`);
763
2810
  }
764
- finally {
765
- htmlCleanup();
766
- server.close();
2811
+ });
2812
+ const htmlResource = { cleanup: () => undefined };
2813
+ try {
2814
+ // Remote references are only worth keeping if they still exist.
2815
+ const remoteReferences = collectRemoteReferences(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document).filter((url) => referencesToProbe(url, assetBases));
2816
+ const unavailableUrls = htmlOptions.fetchMissing === true ? await probeRemoteReferences(remoteReferences) : undefined;
2817
+ if (unavailableUrls !== undefined && unavailableUrls.size > 0) {
2818
+ log.warn(`[fetch] ${unavailableUrls.size} remote reference(s) are unavailable and will be dropped`);
767
2819
  }
2820
+ const prepared = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, {
2821
+ ...htmlOptions,
2822
+ unavailableUrls,
2823
+ shimOrigin: server.baseUrl,
2824
+ // The viewer is served next to the document, so scripts the page runs
2825
+ // resolve their relative URLs against the document's own directory.
2826
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
2827
+ });
2828
+ htmlResource.cleanup = prepared.cleanup;
2829
+ entry.localPath = prepared.vivliostyleInput;
2830
+ const documentUrl = `${server.baseUrl}${sitePath}`;
2831
+ const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
2832
+ log.info(`[html] Serving document at ${documentUrl}`);
2833
+ await runRender({
2834
+ documentUrl,
2835
+ viewerPageUrl,
2836
+ outputAbs,
2837
+ metaFields,
2838
+ viewerParams: buildRenderViewerParams(extraConfig, htmlOptions),
2839
+ timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
2840
+ waitForSettle: htmlOptions.settle != null,
2841
+ chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
2842
+ canvasScale,
2843
+ ...(pdfLabel === undefined ? {} : { pdfLabel }),
2844
+ ...(iccProfile === undefined ? {} : { iccProfile })
2845
+ });
768
2846
  }
769
- else {
770
- dbg("vivliostyleInput (final)", vivliostyleInput);
771
- const config = {
772
- cwd,
773
- input: vivliostyleInput,
774
- output: [{ path: outputAbs, format }],
775
- ...metaFields,
776
- logLevel,
777
- ...(options.debug ? { debug: true } : {}),
778
- ...extraConfig
779
- };
780
- dbg("final BuildConfig", config);
781
- await build(config);
782
- console.log(`✓ Document created: ${outputAbs}`);
2847
+ finally {
2848
+ htmlResource.cleanup();
2849
+ await server.close();
783
2850
  }
784
- // ── PREVIEW mode ───────────────────────────────────────────────────────────
2851
+ return;
785
2852
  }
786
- else {
787
- let previewInput = inputAbs;
788
- let htmlCleanup = () => undefined;
789
- const previewStaticMap = { ...staticMap };
790
- if (htmlMode) {
791
- const { htmlPath, extraStatic, cleanup } = buildPreviewHtml(inputAbs, assetBases, dbg);
792
- previewInput = htmlPath;
793
- htmlCleanup = cleanup;
794
- for (const [virtual, local] of Object.entries(extraStatic)) {
795
- if (!Object.hasOwn(previewStaticMap, virtual)) {
796
- previewStaticMap[virtual] = local;
797
- console.log(`[preview] AssetBase static mount: ${virtual} → ${local}`);
798
- }
799
- else {
800
- dbg("preview: skipping assetBase mount shadowed by explicit --static", { virtual, local });
801
- }
802
- }
803
- if (htmlPath !== inputAbs) {
804
- console.log(`[preview] Using rewritten HTML: ${htmlPath}`);
805
- }
806
- }
807
- dbg("preview input (final)", previewInput);
808
- dbg("previewStaticMap (final)", previewStaticMap);
809
- const hasPreviewStatic = Object.keys(previewStaticMap).length > 0;
810
- const previewCwd = dirname(previewInput);
811
- dbg("previewCwd", previewCwd);
812
- const previewEntry = previewInput.slice(previewCwd.length + 1);
813
- dbg("previewEntry (relative, for configData only)", previewEntry);
814
- const config = {
815
- cwd: previewCwd,
816
- input: previewInput,
817
- logLevel,
818
- enableStaticServe: true,
819
- openViewer: true,
820
- singleDoc: true,
821
- ...(hasPreviewStatic
822
- ? {
823
- configData: [
824
- {
825
- entry: previewEntry,
826
- ...metaFields,
827
- static: previewStaticMap
828
- }
829
- ]
830
- }
831
- : {}),
832
- ...(options.debug ? { debug: true } : {}),
833
- ...extraConfig
834
- };
835
- dbg("final PreviewConfig", config);
836
- const shutdown = () => {
837
- htmlCleanup();
838
- process.exit(0);
839
- };
840
- process.once("SIGINT", shutdown);
841
- process.once("SIGTERM", shutdown);
842
- try {
843
- await preview(config);
2853
+ // ── PREVIEW mode ─────────────────────────────────────────────────────────────
2854
+ {
2855
+ const preview = await startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraConfig);
2856
+ log.info(`[preview] ${preview.url}`);
2857
+ await openInBrowser(preview.url);
2858
+ await new Promise((resolvePromise) => {
2859
+ const stop = () => {
2860
+ process.off("SIGINT", stop);
2861
+ process.off("SIGTERM", stop);
2862
+ resolvePromise();
2863
+ };
2864
+ process.once("SIGINT", stop);
2865
+ process.once("SIGTERM", stop);
2866
+ });
2867
+ await preview.close();
2868
+ }
2869
+ }
2870
+ /**
2871
+ * Serves the rewritten document next to the viewer and returns the URL to open.
2872
+ *
2873
+ * The viewer page lives in the document's own directory, so the preview shows
2874
+ * exactly what the PDF render would lay out.
2875
+ */
2876
+ async function startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraConfig) {
2877
+ const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
2878
+ const viewerLibDir = resolveViewerLibDir();
2879
+ const entry = { localPath: null, sitePath };
2880
+ const server = await startStaticServer({
2881
+ staticMap,
2882
+ assetBases,
2883
+ entry,
2884
+ fetchMissing: htmlOptions.fetchMissing === true,
2885
+ viewerLibDir,
2886
+ viewerFilePath: join(viewerLibDir, "index.html"),
2887
+ log: (message) => log.info(message)
2888
+ });
2889
+ const prepared = buildPreviewHtml(inputAbs, assetBases, {
2890
+ ...htmlOptions,
2891
+ // The viewer is served next to the document, so custom-element URLs
2892
+ // resolve against the document's own directory (see siteDirectory below).
2893
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
2894
+ });
2895
+ entry.localPath = prepared.htmlPath;
2896
+ const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
2897
+ const documentUrl = `${server.baseUrl}${sitePath}`;
2898
+ const url = buildViewerUrl(viewerPageUrl, {
2899
+ src: documentUrl,
2900
+ bookMode: false,
2901
+ renderAllPages: false,
2902
+ ...buildRenderViewerParams(extraConfig, htmlOptions)
2903
+ });
2904
+ return {
2905
+ url,
2906
+ documentUrl,
2907
+ close: async () => {
2908
+ prepared.cleanup();
2909
+ await server.close();
844
2910
  }
845
- catch (err) {
846
- process.off("SIGINT", shutdown);
847
- process.off("SIGTERM", shutdown);
848
- htmlCleanup();
849
- console.error("[preview] Full error:", err);
850
- const message = err instanceof Error ? err.message : String(err);
851
- throw new Error(`preview() failed:\n${message}`);
2911
+ };
2912
+ }
2913
+ /** Opens a URL in the user's browser; preview mode is a plain server. */
2914
+ async function openInBrowser(url) {
2915
+ const { spawn } = await import('node:child_process');
2916
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
2917
+ try {
2918
+ const child = spawn(command, [url], { stdio: "ignore", detached: true });
2919
+ child.unref();
2920
+ }
2921
+ catch (err) {
2922
+ log.warn(`[preview] Could not open a browser: ${String(err)}`);
2923
+ }
2924
+ }
2925
+ /**
2926
+ * Viewer parameters for the render: layout overrides from `--` plus the options
2927
+ * the wrapper owns (page size, output resolution, user stylesheet).
2928
+ */
2929
+ function buildRenderViewerParams(extraConfig, htmlOptions) {
2930
+ const params = {};
2931
+ if (typeof extraConfig.size === "string")
2932
+ params.size = extraConfig.size;
2933
+ if (typeof extraConfig.viewerParam === "string") {
2934
+ for (const pair of extraConfig.viewerParam.split("&")) {
2935
+ if (pair === "")
2936
+ continue;
2937
+ const eq = pair.indexOf("=");
2938
+ if (eq === -1)
2939
+ params[pair] = true;
2940
+ else
2941
+ params[pair.slice(0, eq)] = pair.slice(eq + 1);
852
2942
  }
853
- process.off("SIGINT", shutdown);
854
- process.off("SIGTERM", shutdown);
855
- htmlCleanup();
856
2943
  }
2944
+ if (htmlOptions.css !== undefined)
2945
+ params.style = htmlOptions.css;
2946
+ if (htmlOptions.userStyle !== undefined)
2947
+ params.userStyle = htmlOptions.userStyle;
2948
+ return params;
857
2949
  }
858
2950
  // ---------------------------------------------------------------------------
859
2951
  // Direct execution
@@ -880,9 +2972,9 @@ if (isDirectExecution()) {
880
2972
  process.exit(0);
881
2973
  }
882
2974
  execute(parsed.options, parsed.extraArgs).catch((err) => {
883
- console.error(err instanceof Error ? err.message : String(err));
2975
+ log.error(err instanceof Error ? err.message : String(err));
884
2976
  process.exit(1);
885
2977
  });
886
2978
  }
887
2979
 
888
- export { buildPreviewHtml, execute, extractUrlsFromHtml, isHtmlInput, mapAbsoluteUrlToLocal, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseStaticMapping, prepareInputHtmlForBuild, printHelp, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, splitArgsAtDoubleDash, startStaticServer, urlToStaticMapping };
2980
+ 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 };