@projektemacher/vivliostyle-batch-cli 0.1.2 → 0.2.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,29 +1,23 @@
1
+ // src/vivliostyle-cli.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
1
6
  import { Command } from "commander";
2
- import { build, preview } from "@vivliostyle/cli";
3
- import { resolve, dirname, posix, join } from "node:path";
4
- import { readFileSync, existsSync, mkdtempSync, writeFileSync, rmSync, statSync, realpathSync } from "node:fs";
7
+ import { resolve, dirname, posix, join, basename, relative, isAbsolute, sep } from "node:path";
8
+ import { readFileSync, existsSync, mkdirSync, mkdtempSync, writeFileSync, rmSync, realpathSync } from "node:fs";
5
9
  import { fileURLToPath } from "node:url";
6
10
  import { tmpdir } from "node:os";
7
- import { AddressInfo } from "node:net";
8
- import { lookup as mimeLookup } from "mime-types";
9
- import express from "express";
10
- import serveStatic from "serve-static";
11
11
  import { JSDOM } from "jsdom";
12
+ import log, { type LogLevelDesc } from "loglevel";
13
+ import { VIEWER_PAGE_NAME, startStaticServer, type AssetBaseMapping, type SettleGate, type StaticMap } from "./server.js";
14
+ import { buildViewerUrl, renderPdf, type ViewerParams } from "./render/pdf.js";
15
+ import { resolveViewerLibDir } from "./render/viewer.js";
12
16
 
13
- type BuildConfig = Parameters<typeof build>[0];
14
- type PreviewConfig = Parameters<typeof preview>[0];
15
- type VivliostyleConfigSchema = NonNullable<PreviewConfig["configData"]>;
16
- type StaticMap = VivliostyleConfigSchema extends { static?: infer S } ? NonNullable<S> : Record<string, string>;
17
-
18
- type OutputFormat = "pdf" | "epub" | "webpub";
17
+ type OutputFormat = "pdf";
19
18
  type LogLevel = "silent" | "info" | "verbose" | "debug";
20
19
  type Mode = "build" | "preview";
21
20
 
22
- type AssetBaseMapping = {
23
- urlBase: string;
24
- localBase: string;
25
- };
26
-
27
21
  type CliOptions = {
28
22
  input: string;
29
23
  output: string;
@@ -32,7 +26,6 @@ type CliOptions = {
32
26
  language?: string;
33
27
  static: string[];
34
28
  scripts: boolean;
35
- cwd?: string;
36
29
  format: string;
37
30
  logLevel: string;
38
31
  debug?: boolean;
@@ -40,44 +33,299 @@ type CliOptions = {
40
33
  ignoreAsset: string[];
41
34
  mode: string;
42
35
  preview?: boolean;
36
+ allowRemote?: boolean;
37
+ fetchMissing?: boolean;
38
+ dumpHtml?: string;
39
+ waitForContent?: string | boolean;
40
+ pixelRatio?: string;
41
+ timeout?: string;
42
+ quietMs?: string;
43
43
  };
44
44
 
45
- // ---------------------------------------------------------------------------
46
- // Shared debug callback type
47
- // ---------------------------------------------------------------------------
48
-
49
- type Dbg = (_label: string, _value?: unknown) => void;
45
+ /**
46
+ * Options shared by the build-mode and preview-mode HTML rewriters.
47
+ */
48
+ export type HtmlRewriteOptions = {
49
+ /** Keep references that would be fetched from the network. Off by default. */
50
+ allowRemote?: boolean;
51
+ /** Write the rewritten HTML here (and keep it) instead of a temp file. */
52
+ dumpDir?: string | null;
53
+ /** Let the browser load references without a local file from the web. */
54
+ fetchMissing?: boolean;
55
+ /** Delay pagination until the page's own async work finished. */
56
+ settle?: SettleGate | null;
57
+ /** Origin that page-script requests are routed to. */
58
+ shimOrigin?: string | null;
59
+ /** Base that page-relative URLs resolve against (the page's directory). */
60
+ documentBaseUrl?: string | null;
61
+ /** Remote references that turned out not to exist. */
62
+ unavailableUrls?: Set<string>;
63
+ /** Extra CSS handed to the viewer (`@page` rules, print tweaks). */
64
+ css?: string;
65
+ /** Additional user stylesheet for the viewer. */
66
+ userStyle?: string;
67
+ };
50
68
 
51
- const validFormats: readonly OutputFormat[] = ["pdf", "epub", "webpub"];
69
+ const validFormats: readonly OutputFormat[] = ["pdf"];
52
70
  const validLogLevels: readonly LogLevel[] = ["silent", "info", "verbose", "debug"];
53
71
  const validModes: readonly Mode[] = ["build", "preview"];
54
72
 
73
+ /**
74
+ * Wrapper log levels mapped onto loglevel. Diagnostics are written to the trace
75
+ * channel, so `--log-level verbose` stays quiet while `debug` shows them.
76
+ */
77
+ const LOG_LEVELS: Record<LogLevel, LogLevelDesc> = {
78
+ silent: log.levels.SILENT,
79
+ info: log.levels.INFO,
80
+ verbose: log.levels.DEBUG,
81
+ debug: log.levels.TRACE
82
+ };
83
+
84
+ /**
85
+ * Send every level to the console channel the CLI contract uses: progress to
86
+ * stdout, diagnostics and problems to stderr. The method is resolved per call so
87
+ * that patched consoles stay visible.
88
+ */
89
+ const CONSOLE_CHANNEL: Record<string, "log" | "warn" | "error"> = {
90
+ trace: "error",
91
+ debug: "error",
92
+ info: "log",
93
+ warn: "warn",
94
+ error: "error"
95
+ };
96
+
97
+ log.methodFactory =
98
+ (methodName: string) =>
99
+ (...args: unknown[]): void => {
100
+ (console[CONSOLE_CHANNEL[methodName] ?? "log"] as (...values: unknown[]) => void)(...args);
101
+ };
102
+
55
103
  // ---------------------------------------------------------------------------
56
- // HTML input detection
104
+ // Site path + settle gate helpers
57
105
  // ---------------------------------------------------------------------------
58
106
 
107
+ /** Directory part of a site path, without a trailing slash (`""` for the root). */
108
+ export function siteDirectory(sitePath: string): string {
109
+ const dir = posix.dirname(sitePath);
110
+ return dir === "/" ? "" : dir;
111
+ }
112
+
59
113
  /**
60
- * Returns true when the input file should be treated as HTML.
61
- * Vivliostyle also accepts publication manifests (JSON/TOML/JS config files);
62
- * we detect HTML by extension to avoid trying to parse those as markup.
114
+ * Path the document has on the mapped site, e.g. `/post/tag-pairs/article.html`
115
+ * for `<localBase>/post/tag-pairs/article.html`. Used as the URL Vivliostyle
116
+ * loads, so page-relative and root-relative references resolve like they do on
117
+ * the real site.
63
118
  */
64
- export function isHtmlInput(inputAbs: string): boolean {
65
- return /\.html?$/i.test(inputAbs);
119
+ export function deriveSitePath(inputAbs: string, assetBases: AssetBaseMapping[]): string | null {
120
+ for (const ab of assetBases) {
121
+ const relativePath = relative(resolve(ab.localBase), resolve(inputAbs));
122
+ if (relativePath === "" || relativePath.startsWith("..") || isAbsolute(relativePath)) continue;
123
+ return `/${relativePath.split(sep).join("/")}`;
124
+ }
125
+ return null;
126
+ }
127
+
128
+ /**
129
+ * Tracker injected into the document. It wraps fetch/XHR, watches the document
130
+ * for late content and reports back once nothing is pending and the height has
131
+ * been stable for `quietMs` — or when the deadline is reached.
132
+ */
133
+ export type RuntimeScriptOptions = {
134
+ origin: string;
135
+ documentBaseUrl: string;
136
+ gate: SettleGate | null;
137
+ /**
138
+ * Open every `<details>` element. Vivliostyle loads the page's scripts itself
139
+ * and only re-dispatches `DOMContentLoaded` on the window, so scripts that
140
+ * wait for it on the document — the usual way to expand collapsible content —
141
+ * never run and their content would be missing from the PDF.
142
+ */
143
+ expandDetails?: boolean;
144
+ };
145
+
146
+ /**
147
+ * Opens every `<details>` element, now and for any the page adds later.
148
+ *
149
+ * Print output has to contain the collapsed content too, and the page's own
150
+ * print script cannot do it: Vivliostyle re-dispatches `DOMContentLoaded` on
151
+ * the window rather than on the document, so a `document`-level listener never
152
+ * runs.
153
+ */
154
+ export const EXPAND_DETAILS_SNIPPET = `function expandDetails(root){
155
+ var open=function(el){
156
+ if(el.tagName!=="DETAILS"||el.open)return;
157
+ el.open=true;
158
+ el.setAttribute("data-viv-details-expanded","");
159
+ };
160
+ if(root.nodeType!==1)return;
161
+ [].forEach.call(root.querySelectorAll("details"),open);
162
+ open(root);
163
+ }
164
+ expandDetails(document);
165
+ try{new MutationObserver(function(records){
166
+ for(var i=0;i<records.length;i++){
167
+ var added=records[i].addedNodes;
168
+ for(var j=0;j<added.length;j++)expandDetails(added[j]);
169
+ }
170
+ }).observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
171
+ `;
172
+
173
+ /** Gate image Vivliostyle waits for before it paginates. */
174
+ export function buildSettleGateImage(origin: string): string {
175
+ // Out of flow and invisible, but rendered: Vivliostyle only loads resources of
176
+ // elements that end up in the render tree, so `display:none` would be skipped.
177
+ 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>`;
178
+ }
179
+
180
+ /**
181
+ * The script injected into the document: it routes the URLs that page scripts
182
+ * create to our server and tracks whether the page has finished.
183
+ *
184
+ * Everything lives in one scope on purpose — the settle tracker wraps the same
185
+ * `fetch`/XHR that the routing patches.
186
+ */
187
+ export function buildRuntimeScript(options: RuntimeScriptOptions): string {
188
+ const { origin, documentBaseUrl, gate } = options;
189
+ const expandDetails = options.expandDetails === true ? EXPAND_DETAILS_SNIPPET : "";
190
+ // Vivliostyle paginates incrementally, so collapsed content has to be opened
191
+ // again while it lays the document out, not just once up front.
192
+ const expandDetailsTick = options.expandDetails === true ? "expandDetails(document);" : "";
193
+
194
+ return `(function(){
195
+ var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
196
+ var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
197
+ var pending=0,frames=0,last=0,mutations=0,done=false;
198
+ var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
199
+
200
+ // Root-relative URLs resolve against the site root, document-relative ones
201
+ // against the directory the page has on the site (e.g. model/x.glb next to it).
202
+ function fix(u){
203
+ if(typeof u!=="string"||u==="")return u;
204
+ if(u.slice(0,2)==="//"||u.charAt(0)==="#"||u.charAt(0)==="?")return u;
205
+ if(/^[a-z][a-z0-9+.-]*:/i.test(u))return u;
206
+ return u.charAt(0)==="/"?ORIGIN+u:BASE+u;
207
+ }
208
+
209
+ function canvases(){
210
+ try{return[].map.call(document.querySelectorAll("canvas"),function(c){
211
+ return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);}).join(",");}catch(e){return"";}
212
+ }
213
+ // Canvases with real backing pixels and layout size: the minimum for charts,
214
+ // three.js, maps and OSD tiles to survive print-to-PDF as sharp raster.
215
+ function paintedCanvases(){
216
+ try{return[].filter.call(document.querySelectorAll("canvas"),function(c){
217
+ return c.width>2&&c.height>2&&c.clientWidth>0&&c.clientHeight>0;}).length;}catch(e){return 0;}
218
+ }
219
+ // Sizes of the containers pages fill at runtime; zero means the layout has not
220
+ // happened yet, which is what breaks canvas and chart initialisation.
221
+ function containers(){
222
+ try{return[].map.call(document.querySelectorAll(".script,[class*=script]"),function(el){
223
+ return (el.id||el.className)+"@"+Math.round(el.clientWidth)+"x"+Math.round(el.clientHeight);}).join(",");}catch(e){return"";}
224
+ }
225
+
226
+ function signal(why){
227
+ if(done)return;done=true;
228
+ var at=Math.round(performance.now());
229
+ state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
230
+ var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
231
+ "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&dpr="+window.devicePixelRatio+
232
+ "&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
233
+ "&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
234
+ try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
235
+ }
236
+
237
+ // An embed that never fires load must not hold the layout open forever.
238
+ function watchFrame(frame){
239
+ if(frame.__vivWatched)return;frame.__vivWatched=true;frames++;
240
+ var settled=false;
241
+ function finish(){if(settled)return;settled=true;frames--;last=performance.now();}
242
+ frame.addEventListener("load",finish);
243
+ frame.addEventListener("error",finish);
244
+ try{ if(frame.contentDocument&&frame.contentDocument.readyState==="complete"){finish();return;} }catch(e){}
245
+ setTimeout(finish,FRAME_GRACE);
246
+ }
247
+ function watchFrames(root){
248
+ try{
249
+ [].forEach.call(root.querySelectorAll("iframe"),watchFrame);
250
+ if(root.tagName==="IFRAME")watchFrame(root);
251
+ }catch(e){}
252
+ }
253
+
254
+ var of=window.fetch;
255
+ if(of){window.fetch=function(input,init){
256
+ try{
257
+ if(typeof input==="string")input=fix(input);
258
+ else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
259
+ }catch(e){}
260
+ pending++;last=performance.now();
261
+ return of.call(this,input,init).then(function(v){pending--;last=performance.now();return v;},
262
+ function(e){pending--;last=performance.now();throw e;});};}
263
+ var XHR=window.XMLHttpRequest;
264
+ if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
265
+ XHR.prototype.open=function(m,u){this.__vscounted=true;return open.apply(this,arguments);};
266
+ XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
267
+ this.addEventListener("loadend",function(){pending--;last=performance.now();});}
268
+ return send.apply(this,arguments);};}
269
+ ["Image","Audio"].forEach(function(n){
270
+ var Orig=window[n];if(!Orig)return;
271
+ var Wrapped=function(u){return new Orig(fix(u));};
272
+ Wrapped.prototype=Orig.prototype;
273
+ try{window[n]=Wrapped;}catch(e){}
274
+ });
275
+ ["HTMLImageElement","HTMLIFrameElement","HTMLScriptElement","HTMLSourceElement","HTMLVideoElement","HTMLAudioElement"].forEach(function(n){
276
+ var C=window[n];if(!C)return;
277
+ var d=Object.getOwnPropertyDescriptor(C.prototype,"src");
278
+ if(!d||!d.set)return;
279
+ try{Object.defineProperty(C.prototype,"src",{configurable:true,enumerable:d.enumerable,get:d.get,
280
+ set:function(v){d.set.call(this,fix(v));if(n==="HTMLIFrameElement")watchFrame(this);}});}catch(e){}
281
+ });
282
+ try{Object.defineProperty(document,"baseURI",{configurable:true,get:function(){return BASE;}});}catch(e){}
283
+ try{new MutationObserver(function(){mutations++;watchFrames(document.documentElement);last=performance.now();})
284
+ .observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
285
+ try{new ResizeObserver(function(){last=performance.now();}).observe(document.documentElement);}catch(e){}
286
+ ${expandDetails}watchFrames(document.documentElement);
287
+ last=performance.now();
288
+ (function check(){
289
+ if(done)return;
290
+ ${expandDetailsTick}
291
+ var now=performance.now();
292
+ if(now>=DEADLINE){signal("deadline");return;}
293
+ // Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
294
+ // painted instead of making the gate guess from network quietness. Shader
295
+ // compile and tile decode finish after the last fetch, so readiness wins.
296
+ if(window.__vivReady===true&&pending===0&&frames===0){signal("ready");return;}
297
+ if(pending===0&&frames===0&&now-last>=QUIET){signal("quiet");return;}
298
+ setTimeout(check,50);
299
+ })();
300
+ })();`;
301
+ }
302
+
303
+ /**
304
+ * Injects the runtime script as the first thing in `<head>` (so it wraps `fetch`
305
+ * before any page script runs) and the gate image at the end of `<body>`.
306
+ */
307
+ export function injectRuntimeScriptInDom(document: Document, options: RuntimeScriptOptions): void {
308
+ const head = document.head;
309
+ const anchor = head.firstChild;
310
+
311
+ const base = document.createElement("base");
312
+ base.setAttribute("href", options.documentBaseUrl);
313
+ head.insertBefore(base, anchor);
314
+
315
+ const script = document.createElement("script");
316
+ script.textContent = buildRuntimeScript(options);
317
+ head.insertBefore(script, anchor);
318
+
319
+ if (options.gate === null) return;
320
+ document.body?.insertAdjacentHTML("beforeend", buildSettleGateImage(options.origin));
66
321
  }
67
322
 
68
323
  // ---------------------------------------------------------------------------
69
- // Debug logger
324
+ // HTML input detection
70
325
  // ---------------------------------------------------------------------------
71
326
 
72
- function makeDbg(enabled: boolean): Dbg {
73
- return (_label: string, _value?: unknown): void => {
74
- if (!enabled) return;
75
- if (_value === undefined) {
76
- console.error(`[debug] ${_label}`);
77
- } else {
78
- console.error(`[debug] ${_label}`, JSON.stringify(_value, null, 2));
79
- }
80
- };
327
+ export function isHtmlInput(inputAbs: string): boolean {
328
+ return /\.html?$/i.test(inputAbs);
81
329
  }
82
330
 
83
331
  // ---------------------------------------------------------------------------
@@ -94,165 +342,398 @@ export function splitArgsAtDoubleDash(argv: string[]): {
94
342
  }
95
343
 
96
344
  // ---------------------------------------------------------------------------
97
- // Static HTTP server (build mode only)
345
+ // Static mappings
98
346
  // ---------------------------------------------------------------------------
99
347
 
100
- type StaticServer = {
101
- baseUrl: string;
102
- close: () => void;
103
- };
348
+ /**
349
+ * Serve a single local file directly, bypassing Vite's transform pipeline.
350
+ * Returns true if the file was served, false if it should fall through.
351
+ */
352
+
353
+ // ---------------------------------------------------------------------------
354
+ // DOM-level rewriters
355
+ // ---------------------------------------------------------------------------
104
356
 
105
- function makeMimeHeaders(res: express.Response, filePath: string): void {
106
- const mime = mimeLookup(filePath);
107
- if (mime) res.setHeader("Content-Type", mime);
357
+ const URL_ATTR_SELECTORS: Array<[string, string]> = [
358
+ ["link[href]", "href"],
359
+ ["script[src]", "src"],
360
+ ["img[src]", "src"],
361
+ ["source[src]", "src"],
362
+ ["video[src]", "src"],
363
+ ["audio[src]", "src"],
364
+ ["video[poster]", "poster"],
365
+ ["input[src]", "src"]
366
+ ];
367
+
368
+ /**
369
+ * Subresource attributes that would trigger a network request. Hyperlink
370
+ * attributes (`<a href>`) are deliberately absent: a link is not fetched.
371
+ */
372
+ const SUBRESOURCE_ATTR_SELECTORS: Array<[string, string]> = [
373
+ ...URL_ATTR_SELECTORS,
374
+ ["img[srcset]", "srcset"],
375
+ ["source[srcset]", "srcset"],
376
+ ["iframe[src]", "src"],
377
+ ["object[data]", "data"],
378
+ ["embed[src]", "src"],
379
+ // A-Frame keeps its assets in custom elements
380
+ ["a-asset-item[src]", "src"]
381
+ ];
382
+
383
+ /** URL schemes that never leave the document. */
384
+ const INLINE_URL_SCHEME_RE = /^(?:data|blob|about|javascript|mailto|tel):/i;
385
+
386
+ /**
387
+ * Applies `transform` to every URL of every subresource attribute.
388
+ *
389
+ * A `srcset` candidate list is transformed candidate by candidate, keeping the
390
+ * descriptors (`1x`, `480w`). Returning `null` drops the candidate; an attribute
391
+ * without any remaining candidate is removed.
392
+ */
393
+ export function rewriteUrlAttributes(document: Document, transform: (url: string) => string | null): boolean {
394
+ let changed = false;
395
+
396
+ const apply = (el: Element, attr: string): void => {
397
+ const raw = el.getAttribute(attr);
398
+ if (raw === null) return;
399
+
400
+ if (attr !== "srcset") {
401
+ const current = raw.trim();
402
+ const next = transform(current);
403
+ if (next === null) {
404
+ el.removeAttribute(attr);
405
+ changed = true;
406
+ return;
407
+ }
408
+ if (next === current) return;
409
+ el.setAttribute(attr, next);
410
+ changed = true;
411
+ return;
412
+ }
413
+
414
+ const candidates = raw
415
+ .split(",")
416
+ .map((candidate) => candidate.trim())
417
+ .filter(Boolean);
418
+
419
+ const kept: string[] = [];
420
+ let touched = false;
421
+
422
+ for (const candidate of candidates) {
423
+ const [url, ...descriptor] = candidate.split(/\s+/);
424
+ const next = transform(url);
425
+ if (next === null) {
426
+ touched = true;
427
+ continue;
428
+ }
429
+ if (next !== url) touched = true;
430
+ kept.push([next, ...descriptor].join(" "));
431
+ }
432
+
433
+ if (!touched) return;
434
+ changed = true;
435
+ if (kept.length === 0) el.removeAttribute(attr);
436
+ else el.setAttribute(attr, kept.join(", "));
437
+ };
438
+
439
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
440
+ for (const el of document.querySelectorAll(selector)) apply(el, attr);
441
+ }
442
+
443
+ return changed;
108
444
  }
109
445
 
110
- function isFile(localPath: string): boolean {
111
- try {
112
- return statSync(localPath).isFile();
113
- } catch {
114
- return false;
446
+ /**
447
+ * True when the browser would have to fetch the URL over the network.
448
+ */
449
+ export function isRemoteUrl(value: string): boolean {
450
+ const trimmed = value.trim();
451
+ if (!trimmed) return false;
452
+ if (trimmed.startsWith("//")) return true;
453
+ return /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !INLINE_URL_SCHEME_RE.test(trimmed);
454
+ }
455
+
456
+ /**
457
+ * Drops subresource references that are not available locally so nothing is
458
+ * fetched from the web. `srcset` candidates are filtered individually; an
459
+ * attribute whose candidates are all remote is removed entirely.
460
+ *
461
+ * `isAllowed` exempts URLs that are served by the wrapper itself, e.g. the
462
+ * static server URLs produced by the virtual-path rewrite.
463
+ *
464
+ * Returns every dropped URL.
465
+ */
466
+ export function dropRemoteReferencesInDom(document: Document, isAllowed: (url: string) => boolean = () => false): string[] {
467
+ const dropped: string[] = [];
468
+
469
+ const droppedSet = new Set<string>();
470
+ rewriteUrlAttributes(document, (url) => {
471
+ if (isAllowed(url) || !isRemoteUrl(url)) return url;
472
+ droppedSet.add(url);
473
+ return null;
474
+ });
475
+ dropped.push(...droppedSet);
476
+
477
+ // A meta refresh navigates the document, which is a fetch just like a
478
+ // subresource. Redirect stubs are dropped as well.
479
+ for (const el of document.querySelectorAll("meta[http-equiv]")) {
480
+ if ((el.getAttribute("http-equiv") ?? "").toLowerCase() !== "refresh") continue;
481
+ const target = parseMetaRefreshTarget(el.getAttribute("content") ?? "");
482
+ if (target === null || !isRemoteUrl(target) || isAllowed(target)) continue;
483
+ el.remove();
484
+ dropped.push(target);
115
485
  }
486
+
487
+ return dropped;
116
488
  }
117
489
 
118
- function applyStaticMounts(app: express.Express, staticMap: Record<string, string>, assetBases: AssetBaseMapping[], dbg: Dbg): void {
119
- for (const [virtual, localBase] of Object.entries(staticMap)) {
120
- const absLocal = resolve(localBase);
121
- if (isFile(absLocal)) {
122
- app.get(virtual, (_req, res) => {
123
- dbg("[static-server] serving file", { virtual, absLocal });
124
- const mime = mimeLookup(absLocal);
125
- if (mime) res.type(mime);
126
- res.sendFile(absLocal);
127
- });
128
- console.log(`[static-server] File route: GET ${virtual} → ${absLocal}`);
129
- } else {
130
- const mountPath = virtual.endsWith("/") ? virtual : `${virtual}/`;
131
- app.use(
132
- mountPath,
133
- serveStatic(absLocal, {
134
- fallthrough: true,
135
- setHeaders: makeMimeHeaders
136
- })
137
- );
138
- console.log(`[static-server] Dir mount: ${mountPath} → ${absLocal}`);
490
+ /**
491
+ * Extracts the target of `<meta http-equiv="refresh" content="0; url=…">`.
492
+ */
493
+ export function parseMetaRefreshTarget(content: string): string | null {
494
+ const match = /^\s*[\d.]*\s*;?\s*url\s*=\s*(.*)$/i.exec(content);
495
+ if (match === null) return null;
496
+ const target = match[1].trim().replace(/^["']|["']$/g, "");
497
+ return target === "" ? null : target;
498
+ }
499
+
500
+ /**
501
+ * Root-relative subresource paths that survive the rewrites and therefore end
502
+ * up resolved against the file system location of the input document. They are
503
+ * broken unless something else provides them (e.g. the input is served over
504
+ * HTTP), so they are worth reporting.
505
+ */
506
+ export function collectUnservedVirtualPaths(
507
+ document: Document,
508
+ staticMapKeys: string[],
509
+ isServable?: (virtualPath: string) => boolean
510
+ ): string[] {
511
+ const isMapped = (path: string): boolean =>
512
+ staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
513
+
514
+ const unserved = new Set<string>();
515
+
516
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
517
+ for (const el of document.querySelectorAll(selector)) {
518
+ const raw = el.getAttribute(attr);
519
+ if (raw === null) continue;
520
+
521
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
522
+ for (const value of values) {
523
+ if (!value.startsWith("/")) continue;
524
+ if (isMapped(value)) continue;
525
+ if (isServable !== undefined && isServable(value)) continue;
526
+ unserved.add(value);
527
+ }
139
528
  }
140
- dbg("[static-server] mount", { virtual, absLocal });
141
529
  }
142
530
 
143
- for (const ab of assetBases) {
144
- const absLocal = resolve(ab.localBase);
145
- app.use("/", serveStatic(absLocal, { fallthrough: true, setHeaders: makeMimeHeaders }));
146
- dbg("[static-server] assetBase fallback mount", absLocal);
147
- console.log(`[static-server] Fallback mount: / → ${absLocal}`);
148
- }
531
+ return [...unserved];
149
532
  }
150
533
 
151
- export function startStaticServer(
152
- staticMap: Record<string, string>,
153
- assetBases: AssetBaseMapping[],
154
- htmlFilePath: string | null,
155
- dbg: Dbg,
156
- port = 0
157
- ): Promise<StaticServer> {
158
- const app = express();
159
- app.disable("x-powered-by");
160
-
161
- if (htmlFilePath !== null) {
162
- const absHtmlPath = resolve(htmlFilePath);
163
- app.get("/index.html", (_req, res) => {
164
- dbg("[static-server] serving HTML entry", absHtmlPath);
165
- res.type("text/html").sendFile(absHtmlPath);
166
- });
167
- console.log(`[static-server] HTML entry: /index.html → ${absHtmlPath}`);
534
+ /** Remote subresource URLs a document would have to fetch. */
535
+ export function collectRemoteReferences(document: Document): string[] {
536
+ const urls = new Set<string>();
537
+
538
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
539
+ for (const el of document.querySelectorAll(selector)) {
540
+ const raw = el.getAttribute(attr);
541
+ if (raw === null) continue;
542
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
543
+ for (const value of values) {
544
+ if (isRemoteUrl(value)) urls.add(value);
545
+ }
546
+ }
168
547
  }
169
548
 
170
- applyStaticMounts(app, staticMap, assetBases, dbg);
549
+ return [...urls];
550
+ }
551
+
552
+ /**
553
+ * Whether a remote reference is worth probing on the live site.
554
+ *
555
+ * A reference that resolves to a local file is served from disk, so only that
556
+ * file decides whether it stays: the live site may have moved on (a new CSS
557
+ * hash, a rotated upload) while our copy of the page still has what it needs.
558
+ */
559
+ export function referencesToProbe(url: string, assetBases: AssetBaseMapping[]): boolean {
560
+ const mapped = mapAbsoluteUrlToLocal(url, assetBases);
561
+ return mapped.kind === "mapped" ? !existsSync(mapped.localPath) : true;
562
+ }
171
563
 
172
- app.use((req: express.Request, res: express.Response) => {
173
- dbg("[static-server] 404", req.url);
174
- res.status(404).type("text").send(`404 Not Found: ${req.url}`);
175
- });
564
+ /**
565
+ * Checks which remote references actually exist, so that content that is gone
566
+ * (a deleted slide deck, a retired CSS file) is dropped instead of leaving a
567
+ * broken embed that never finishes loading.
568
+ */
569
+ export async function probeRemoteReferences(urls: string[], timeoutMs = 8000): Promise<Set<string>> {
570
+ const unavailable = new Set<string>();
176
571
 
177
- return new Promise((resolvePromise, reject) => {
178
- const httpServer = app.listen(port, "127.0.0.1", () => {
179
- const addr = httpServer.address() as AddressInfo;
180
- const baseUrl = `http://127.0.0.1:${addr.port}`;
181
- console.log(`[static-server] Listening on ${baseUrl}`);
182
- dbg("[static-server] staticMap", staticMap);
183
- dbg(
184
- "[static-server] assetBase roots",
185
- assetBases.map((ab) => ab.localBase)
186
- );
572
+ await Promise.all(
573
+ urls.map(async (url) => {
574
+ try {
575
+ const response = await fetch(url, { method: "HEAD", redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
576
+ // Only a definite "gone" counts: servers that reject HEAD still have the file.
577
+ if (response.status === 404 || response.status === 410) unavailable.add(url);
578
+ log.trace("probeRemoteReferences", { url, status: response.status });
579
+ } catch (err) {
580
+ // A failed probe is no proof that the resource is gone: Chromium loads
581
+ // it with a browser user agent, which many sites accept where a HEAD
582
+ // request from Node is rejected or blocked outright.
583
+ log.trace("probeRemoteReferences failed", { url, error: String(err) });
584
+ }
585
+ })
586
+ );
187
587
 
188
- let closed = false;
189
- const close = (): void => {
190
- if (closed) return;
191
- closed = true;
192
- httpServer.close((err) => {
193
- if (err) console.warn(`[static-server] close error: ${err.message}`);
194
- else dbg("[static-server] stopped");
195
- });
196
- };
588
+ return unavailable;
589
+ }
197
590
 
198
- resolvePromise({ baseUrl, close });
199
- });
200
- httpServer.once("error", reject);
201
- });
591
+ /** Removes the attributes that point at the given URLs. */
592
+ export function dropUnavailableReferencesInDom(document: Document, unavailable: Set<string>): string[] {
593
+ if (unavailable.size === 0) return [];
594
+ const dropped: string[] = [];
595
+
596
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
597
+ for (const el of document.querySelectorAll(selector)) {
598
+ const raw = el.getAttribute(attr);
599
+ if (raw === null) continue;
600
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
601
+ const hit = values.filter((value) => unavailable.has(value));
602
+ if (hit.length === 0) continue;
603
+
604
+ dropped.push(...hit);
605
+ const kept =
606
+ attr === "srcset"
607
+ ? raw
608
+ .split(",")
609
+ .map((e) => e.trim())
610
+ .filter((c) => !unavailable.has(c.split(/\s+/)[0] ?? ""))
611
+ : [];
612
+ if (kept.length === 0) el.removeAttribute(attr);
613
+ else el.setAttribute(attr, kept.join(", "));
614
+ }
615
+ }
616
+
617
+ for (const url of new Set(dropped)) {
618
+ log.warn(`[fetch] Dropped unavailable remote reference: ${url}`);
619
+ }
620
+ return dropped;
621
+ }
622
+
623
+ /**
624
+ * Exempts the wrapper's own static server from the offline pass: URLs pointing
625
+ * at it are served from the local file system, never from the web.
626
+ */
627
+ export function isStaticServerUrl(serverBaseUrl: string): (url: string) => boolean {
628
+ return (url: string): boolean => serverBaseUrl !== "" && url.startsWith(serverBaseUrl);
629
+ }
630
+
631
+ function reportDroppedRemoteRefs(dropped: string[]): void {
632
+ for (const url of new Set(dropped)) {
633
+ log.info(`[offline] Dropped remote reference: ${url}`);
634
+ }
635
+ log.trace("dropRemoteReferencesInDom: dropped", dropped);
636
+ }
637
+
638
+ function reportUnservedVirtualPaths(unserved: string[]): void {
639
+ for (const path of unserved) {
640
+ log.warn(`[html] Warning: reference is not available and will not resolve: ${path}`);
641
+ }
202
642
  }
203
643
 
204
644
  // ---------------------------------------------------------------------------
205
- // DOM-level rewriters
645
+ // Asset base match result
206
646
  // ---------------------------------------------------------------------------
207
647
 
208
- const URL_ATTR_SELECTORS: Array<[string, string]> = [
209
- ["link[href]", "href"],
210
- ["script[src]", "src"],
211
- ["img[src]", "src"],
212
- ["source[src]", "src"],
213
- ["video[src]", "src"],
214
- ["audio[src]", "src"],
215
- ["video[poster]", "poster"],
216
- ["input[src]", "src"]
217
- ];
648
+ /**
649
+ * Discriminated union returned by mapAbsoluteUrlToLocal.
650
+ *
651
+ * - "mapped" — the URL matched an asset-base prefix and has a sub-path that
652
+ * can be mapped to a local file.
653
+ * - "root-only" — the URL matched a prefix but carried no sub-path (i.e. the
654
+ * URL is exactly the base root). The caller should skip it
655
+ * with a precise message rather than treating it as an
656
+ * unrecognised external URL.
657
+ * - "no-match" — no asset-base prefix matched; caller handles as usual.
658
+ */
659
+ type AssetBaseMatch = { kind: "mapped"; virtualPath: string; localPath: string } | { kind: "root-only" } | { kind: "no-match" };
218
660
 
219
- export function rewriteAbsoluteUrlsInDom(document: Document, assetBases: AssetBaseMapping[]): boolean {
220
- if (assetBases.length === 0) return false;
221
- let changed = false;
661
+ export function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): AssetBaseMatch {
662
+ for (const mapping of assetBases) {
663
+ if (!url.startsWith(mapping.urlBase)) continue;
222
664
 
223
- for (const [selector, attr] of URL_ATTR_SELECTORS) {
224
- for (const el of document.querySelectorAll(selector)) {
225
- const val = el.getAttribute(attr) ?? "";
226
- const mapped = mapAbsoluteUrlToLocal(val, assetBases);
227
- if (mapped) {
228
- el.setAttribute(attr, mapped.virtualPath);
229
- changed = true;
230
- }
665
+ let cleanRelative: string;
666
+ try {
667
+ cleanRelative = new URL(url).pathname.slice(1);
668
+ } catch {
669
+ const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
670
+ cleanRelative = noQuery.split("#")[0];
231
671
  }
232
- }
233
672
 
234
- return changed;
673
+ if (!cleanRelative) {
674
+ // The URL points to the asset-base root itself
675
+ // (e.g. https://cdn.example.com/ with no sub-path).
676
+ return { kind: "root-only" };
677
+ }
678
+
679
+ const virtualPath = posix.resolve("/", cleanRelative);
680
+ const localPath = resolve(mapping.localBase, cleanRelative);
681
+ return { kind: "mapped", virtualPath, localPath };
682
+ }
683
+ return { kind: "no-match" };
235
684
  }
236
685
 
237
- export function rewriteVirtualPathsToServerInDom(document: Document, staticMapKeys: string[], serverBaseUrl: string): boolean {
238
- let changed = false;
686
+ export function rewriteAbsoluteUrlsInDom(document: Document, assetBases: AssetBaseMapping[], keepMissing = false): boolean {
687
+ if (assetBases.length === 0) return false;
688
+
689
+ // "root-only" and "no-match" — leave the URL unchanged. With `keepMissing`,
690
+ // URLs whose local file does not exist keep their absolute form so the browser
691
+ // can load them from the mapped origin.
692
+ return rewriteUrlAttributes(document, (url) => {
693
+ const match = mapAbsoluteUrlToLocal(url, assetBases);
694
+ if (match.kind !== "mapped") return url;
695
+ if (keepMissing && !existsSync(match.localPath)) return url;
696
+ return match.virtualPath;
697
+ });
698
+ }
239
699
 
700
+ export function rewriteVirtualPathsToServerInDom(
701
+ document: Document,
702
+ staticMapKeys: string[],
703
+ serverBaseUrl: string,
704
+ isServable?: (virtualPath: string) => boolean
705
+ ): boolean {
240
706
  const shouldRewrite = (path: string): boolean => {
241
707
  if (!path.startsWith("/")) return false;
242
- return staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
708
+ if (staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`))) return true;
709
+ return isServable !== undefined && isServable(path);
243
710
  };
244
711
 
245
- for (const [selector, attr] of URL_ATTR_SELECTORS) {
246
- for (const el of document.querySelectorAll(selector)) {
247
- const val = el.getAttribute(attr) ?? "";
248
- if (shouldRewrite(val)) {
249
- el.setAttribute(attr, `${serverBaseUrl}${val}`);
250
- changed = true;
712
+ return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
713
+ }
714
+
715
+ /**
716
+ * Returns a predicate that reports whether a root-relative path can be served
717
+ * from one of the configured asset-base local roots.
718
+ *
719
+ * Absolute URLs that were rewritten to root-relative virtual paths (see
720
+ * rewriteAbsoluteUrlsInDom) are not necessarily part of the static map — an
721
+ * `<img src>` is never collected by extractUrlsFromHtml — but the static server
722
+ * resolves any request path against an asset-base localBase, so those paths are
723
+ * servable and must be pointed at the server instead of being resolved against
724
+ * the file system location of the input document.
725
+ */
726
+ export function createAssetBasePathProbe(assetBases: AssetBaseMapping[]): (virtualPath: string) => boolean {
727
+ return (virtualPath: string): boolean => {
728
+ for (const ab of assetBases) {
729
+ const localPath = resolve(ab.localBase, virtualPath.replace(/^\//, ""));
730
+ if (existsSync(localPath)) {
731
+ log.trace("createAssetBasePathProbe: servable via asset-base", { virtualPath, localPath });
732
+ return true;
251
733
  }
252
734
  }
253
- }
254
-
255
- return changed;
735
+ return false;
736
+ };
256
737
  }
257
738
 
258
739
  // ---------------------------------------------------------------------------
@@ -295,15 +776,26 @@ export function extractUrlsFromHtml(htmlPath: string, includeScripts = true, doc
295
776
 
296
777
  const urls = new Set<string>();
297
778
 
298
- for (const el of document.querySelectorAll("link[href]")) {
299
- const href = el.getAttribute("href")?.trim();
300
- if (href) urls.add(href);
301
- }
779
+ // Every subresource is collected, not just <link> and <script>: an <img> that
780
+ // is not part of the static map can only be resolved by the fallback roots of
781
+ // the static server, and a missing one would fail silently.
782
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
783
+ if (selector === "script[src]" && !includeScripts) continue;
302
784
 
303
- if (includeScripts) {
304
- for (const el of document.querySelectorAll("script[src]")) {
305
- const src = el.getAttribute("src")?.trim();
306
- if (src) urls.add(src);
785
+ for (const el of document.querySelectorAll(selector)) {
786
+ const raw = el.getAttribute(attr);
787
+ if (raw === null) continue;
788
+
789
+ if (attr !== "srcset") {
790
+ const url = raw.trim();
791
+ if (url) urls.add(url);
792
+ continue;
793
+ }
794
+
795
+ for (const candidate of raw.split(",")) {
796
+ const url = candidate.trim().split(/\s+/)[0] ?? "";
797
+ if (url) urls.add(url);
798
+ }
307
799
  }
308
800
  }
309
801
 
@@ -314,29 +806,15 @@ export function extractUrlsFromHtml(htmlPath: string, includeScripts = true, doc
314
806
  // Preview HTML builder
315
807
  // ---------------------------------------------------------------------------
316
808
 
317
- /**
318
- * Rewrites absolute external URLs to root-relative virtual paths and writes
319
- * the result as a sibling of the original input file so that
320
- * cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
321
- *
322
- * The output filename uses a non-dotfile prefix so Vite's static server
323
- * (which ignores dotfiles by default) can serve it correctly.
324
- *
325
- * Also derives extra static mounts from each assetBase so that secondary
326
- * assets referenced from CSS (fonts, images) are served by Vivliostyle's
327
- * own Vite server without needing Express.
328
- *
329
- * Returns:
330
- * - htmlPath – sibling file path, or inputAbs if no rewriting was needed
331
- * - extraStatic – virtual→local entries for assetBase roots to merge into
332
- * the static map passed to Vivliostyle
333
- * - cleanup – deletes the sibling file (no-op if inputAbs was returned)
334
- */
335
809
  export function buildPreviewHtml(
336
810
  inputAbs: string,
337
811
  assetBases: AssetBaseMapping[],
338
- dbg: Dbg
339
- ): { htmlPath: string; extraStatic: Record<string, string>; cleanup: () => void } {
812
+ options: HtmlRewriteOptions = {}
813
+ ): {
814
+ htmlPath: string;
815
+ extraStatic: Record<string, string>;
816
+ cleanup: () => void;
817
+ } {
340
818
  let content: string;
341
819
  try {
342
820
  content = readFileSync(inputAbs, "utf-8");
@@ -344,8 +822,6 @@ export function buildPreviewHtml(
344
822
  throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
345
823
  }
346
824
 
347
- // Derive extra static mounts for each assetBase root so secondary assets
348
- // referenced from CSS are also reachable through Vivliostyle's Vite server.
349
825
  const extraStatic: Record<string, string> = {};
350
826
  for (const ab of assetBases) {
351
827
  let virtualPrefix: string;
@@ -357,42 +833,46 @@ export function buildPreviewHtml(
357
833
  if (!virtualPrefix.endsWith("/")) virtualPrefix = `${virtualPrefix}/`;
358
834
  const mapKey = virtualPrefix === "/" ? "/" : virtualPrefix.slice(0, -1);
359
835
  if (Object.hasOwn(extraStatic, mapKey)) {
360
- console.warn(
836
+ log.warn(
361
837
  `[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`
362
838
  );
363
839
  }
364
840
  extraStatic[mapKey] = resolve(ab.localBase);
365
- dbg("buildPreviewHtml: assetBase extra static mount", {
366
- mapKey,
367
- local: ab.localBase
368
- });
841
+ log.trace("buildPreviewHtml: assetBase extra static mount", { mapKey, local: ab.localBase });
369
842
  }
370
843
 
371
844
  const dom = new JSDOM(content);
372
845
  const document = dom.window.document;
373
846
  const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
374
- if (changed) dbg("buildPreviewHtml: rewrote absolute URLs → virtual paths");
847
+ if (changed) log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
848
+
849
+ const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
850
+ if (dropped.length > 0) reportDroppedRemoteRefs(dropped);
375
851
 
376
- if (!changed) {
377
- dbg("buildPreviewHtml: no URL rewrites needed, using original file");
852
+ if (!changed && dropped.length === 0) {
853
+ log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
378
854
  return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
379
855
  }
380
856
 
381
- const inputDir = dirname(inputAbs);
382
- const inputBase = inputAbs.slice(inputDir.length + 1);
383
- const outputBase = `_vivliostyle_preview_${inputBase}`;
384
- const htmlPath = join(inputDir, outputBase);
857
+ const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
858
+ const htmlPath =
859
+ dumpDir === null ? join(dirname(inputAbs), `_vivliostyle_preview_${basename(inputAbs)}`) : join(dumpDir, basename(inputAbs));
385
860
 
861
+ if (dumpDir !== null) mkdirSync(dumpDir, { recursive: true });
386
862
  writeFileSync(htmlPath, dom.serialize(), "utf-8");
387
- dbg("buildPreviewHtml: wrote rewritten HTML alongside original", htmlPath);
388
- console.log(`[preview] Wrote rewritten HTML: ${htmlPath}`);
863
+ log.trace("buildPreviewHtml: wrote rewritten HTML", htmlPath);
864
+ log.info(`[preview] Wrote rewritten HTML: ${htmlPath}`);
389
865
 
390
866
  const cleanup = (): void => {
867
+ if (dumpDir !== null) {
868
+ log.trace("buildPreviewHtml: keeping dumped HTML", htmlPath);
869
+ return;
870
+ }
391
871
  try {
392
872
  rmSync(htmlPath, { force: true });
393
- dbg("buildPreviewHtml: removed rewritten HTML", htmlPath);
873
+ log.trace("buildPreviewHtml: removed rewritten HTML", htmlPath);
394
874
  } catch (err) {
395
- console.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
875
+ log.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
396
876
  }
397
877
  };
398
878
 
@@ -403,18 +883,12 @@ export function buildPreviewHtml(
403
883
  // Build HTML builder
404
884
  // ---------------------------------------------------------------------------
405
885
 
406
- /**
407
- * Prepares the HTML for BUILD mode.
408
- * Both rewrite passes (absolute → virtual, virtual → absolute server URL)
409
- * are applied in a single DOM parse.
410
- * If nothing changed the original file path is returned with a no-op cleanup.
411
- */
412
886
  export function prepareInputHtmlForBuild(
413
887
  inputAbs: string,
414
888
  assetBases: AssetBaseMapping[],
415
889
  staticMap: Record<string, string>,
416
890
  serverBaseUrl: string,
417
- dbg: Dbg
891
+ options: HtmlRewriteOptions = {}
418
892
  ): { vivliostyleInput: string; cleanup: () => void } {
419
893
  let content: string;
420
894
  try {
@@ -427,29 +901,64 @@ export function prepareInputHtmlForBuild(
427
901
  const document = dom.window.document;
428
902
  const staticMapKeys = Object.keys(staticMap);
429
903
 
430
- const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases);
431
- if (absChanged) dbg("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
904
+ const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases, options.fetchMissing === true);
905
+ if (absChanged) log.trace("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
906
+
907
+ const probe = assetBases.length > 0 ? createAssetBasePathProbe(assetBases) : undefined;
908
+ const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
909
+ if (srvChanged) log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
910
+
911
+ const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
432
912
 
433
- const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl);
434
- if (srvChanged) dbg("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
913
+ const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
914
+ if (dropped.length > 0) reportDroppedRemoteRefs(dropped);
915
+
916
+ const unserved = collectUnservedVirtualPaths(document, staticMapKeys, probe);
917
+ if (unserved.length > 0) reportUnservedVirtualPaths(unserved);
918
+
919
+ // The runtime script only matters for pages that run scripts; injecting it
920
+ // into a plain document would rewrite the file for nothing.
921
+ const hasScripts = document.querySelector("script") !== null;
922
+ const wantsRuntime = (options.shimOrigin != null && hasScripts) || options.settle != null;
923
+ if (wantsRuntime) {
924
+ const origin = options.shimOrigin ?? serverBaseUrl;
925
+ const documentBaseUrl = options.documentBaseUrl ?? `${origin}/`;
926
+ // Only the PDF run expands `<details>`; the preview stays interactive.
927
+ injectRuntimeScriptInDom(document, { origin, documentBaseUrl, gate: options.settle ?? null, expandDetails: true });
928
+ log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
929
+ }
435
930
 
436
- if (!absChanged && !srvChanged) {
437
- dbg("prepareInputHtmlForBuild: no changes, using original file");
931
+ if (!absChanged && !srvChanged && dropped.length === 0 && gone.length === 0 && options.settle == null && !wantsRuntime) {
932
+ log.trace("prepareInputHtmlForBuild: no changes, using original file");
438
933
  return { vivliostyleInput: inputAbs, cleanup: () => undefined };
439
934
  }
440
935
 
441
- const tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
442
- const tmpHtml = join(tmpDir, "index.html");
936
+ const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
937
+ let tmpDir: string | null = null;
938
+ let tmpHtml: string;
939
+
940
+ if (dumpDir !== null) {
941
+ mkdirSync(dumpDir, { recursive: true });
942
+ tmpHtml = join(dumpDir, basename(inputAbs));
943
+ } else {
944
+ tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
945
+ tmpHtml = join(tmpDir, "index.html");
946
+ }
947
+
443
948
  writeFileSync(tmpHtml, dom.serialize(), "utf-8");
444
- console.log(`[html] Prepared input HTML → ${tmpHtml}`);
445
- dbg("prepareInputHtmlForBuild: written to temp file", tmpHtml);
949
+ log.info(`[html] ${dumpDir === null ? "Prepared" : "Dumped"} input HTML → ${tmpHtml}`);
950
+ log.trace("prepareInputHtmlForBuild: written", tmpHtml);
446
951
 
447
952
  const cleanup = (): void => {
953
+ if (tmpDir === null) {
954
+ log.trace("prepareInputHtmlForBuild: keeping dumped HTML", tmpHtml);
955
+ return;
956
+ }
448
957
  try {
449
958
  rmSync(tmpDir, { recursive: true, force: true });
450
- dbg("prepareInputHtmlForBuild: removed temp dir", tmpDir);
959
+ log.trace("prepareInputHtmlForBuild: removed temp dir", tmpDir);
451
960
  } catch (err) {
452
- console.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
961
+ log.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
453
962
  }
454
963
  };
455
964
 
@@ -487,27 +996,6 @@ export function parseAssetBaseMapping(value: string): AssetBaseMapping {
487
996
  return { urlBase: normalizeUrlBase(urlBase), localBase };
488
997
  }
489
998
 
490
- export function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): { virtualPath: string; localPath: string } | null {
491
- for (const mapping of assetBases) {
492
- if (!url.startsWith(mapping.urlBase)) continue;
493
-
494
- let cleanRelative: string;
495
- try {
496
- cleanRelative = new URL(url).pathname.slice(1);
497
- } catch {
498
- const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
499
- cleanRelative = noQuery.split("#")[0];
500
- }
501
-
502
- if (!cleanRelative) return null;
503
-
504
- const virtualPath = posix.resolve("/", cleanRelative);
505
- const localPath = resolve(mapping.localBase, cleanRelative);
506
- return { virtualPath, localPath };
507
- }
508
- return null;
509
- }
510
-
511
999
  // ---------------------------------------------------------------------------
512
1000
  // MappingResult + urlToStaticMapping
513
1001
  // ---------------------------------------------------------------------------
@@ -518,46 +1006,49 @@ export function urlToStaticMapping(
518
1006
  url: string,
519
1007
  htmlDir: string,
520
1008
  assetBases: AssetBaseMapping[],
521
- ignoredAssets: Set<string>,
522
- dbg: Dbg
1009
+ ignoredAssets: Set<string>
523
1010
  ): MappingResult {
524
1011
  const trimmed = url.trim();
525
1012
  if (!trimmed) return { kind: "skipped", url, reason: "empty URL" };
526
1013
  if (trimmed.startsWith("#")) return { kind: "skipped", url, reason: "fragment-only URL" };
527
1014
 
528
- const absoluteMapped = mapAbsoluteUrlToLocal(trimmed, assetBases);
529
- if (absoluteMapped) {
530
- if (shouldIgnoreVirtualPath(absoluteMapped.virtualPath, ignoredAssets)) {
531
- dbg("urlToStaticMapping: ignored (asset-base match)", {
532
- url,
533
- ...absoluteMapped
534
- });
1015
+ const assetMatch = mapAbsoluteUrlToLocal(trimmed, assetBases);
1016
+
1017
+ if (assetMatch.kind === "root-only") {
1018
+ return {
1019
+ kind: "skipped",
1020
+ url,
1021
+ reason: "URL matches an asset-base prefix but has no path component (root URL)"
1022
+ };
1023
+ }
1024
+
1025
+ if (assetMatch.kind === "mapped") {
1026
+ if (shouldIgnoreVirtualPath(assetMatch.virtualPath, ignoredAssets)) {
1027
+ log.trace("urlToStaticMapping: ignored (asset-base match)", { url, ...assetMatch });
535
1028
  return {
536
1029
  kind: "skipped",
537
1030
  url,
538
- reason: `matches --ignore-asset "${absoluteMapped.virtualPath}"`
1031
+ reason: `matches --ignore-asset "${assetMatch.virtualPath}"`
539
1032
  };
540
1033
  }
541
- if (!existsSync(absoluteMapped.localPath)) {
542
- console.warn(
1034
+ if (!existsSync(assetMatch.localPath)) {
1035
+ log.warn(
543
1036
  `[html] Warning: asset-base mapped path does not exist\n` +
544
1037
  ` url : ${url}\n` +
545
- ` virtual : ${absoluteMapped.virtualPath}\n` +
546
- ` local : ${absoluteMapped.localPath}`
1038
+ ` virtual : ${assetMatch.virtualPath}\n` +
1039
+ ` local : ${assetMatch.localPath}`
547
1040
  );
548
1041
  }
549
1042
  return {
550
1043
  kind: "mapped",
551
- mapping: `${absoluteMapped.virtualPath}:${absoluteMapped.localPath}`
1044
+ mapping: `${assetMatch.virtualPath}:${assetMatch.localPath}`
552
1045
  };
553
1046
  }
554
1047
 
1048
+ // assetMatch.kind === "no-match" — proceed to local / external handling
1049
+
555
1050
  if (trimmed.startsWith("//")) {
556
- return {
557
- kind: "skipped",
558
- url,
559
- reason: "protocol-relative external URL"
560
- };
1051
+ return { kind: "skipped", url, reason: "protocol-relative external URL" };
561
1052
  }
562
1053
 
563
1054
  if (/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(trimmed)) {
@@ -582,10 +1073,7 @@ export function urlToStaticMapping(
582
1073
  const virtualPath = cleanUrl.startsWith("/") ? posix.normalize(cleanUrl) : posix.resolve("/", posix.relative(htmlDir, localPath));
583
1074
 
584
1075
  if (shouldIgnoreVirtualPath(virtualPath, ignoredAssets)) {
585
- dbg("urlToStaticMapping: ignored (ignore-asset match)", {
586
- url,
587
- virtualPath
588
- });
1076
+ log.trace("urlToStaticMapping: ignored (ignore-asset match)", { url, virtualPath });
589
1077
  return {
590
1078
  kind: "skipped",
591
1079
  url,
@@ -594,7 +1082,7 @@ export function urlToStaticMapping(
594
1082
  }
595
1083
 
596
1084
  if (!existsSync(localPath)) {
597
- console.warn(
1085
+ log.warn(
598
1086
  `[html] Warning: referenced path does not exist\n` +
599
1087
  ` url : ${url}\n` +
600
1088
  ` virtual : ${virtualPath}\n` +
@@ -605,10 +1093,7 @@ export function urlToStaticMapping(
605
1093
  return { kind: "mapped", mapping: `${virtualPath}:${localPath}` };
606
1094
  }
607
1095
 
608
- export function parseStaticMapping(mapping: string): {
609
- virtual: string;
610
- local: string;
611
- } {
1096
+ export function parseStaticMapping(mapping: string): { virtual: string; local: string } {
612
1097
  if (!mapping.startsWith("/")) {
613
1098
  throw new Error(`Invalid --static mapping: "${mapping}"\nExpected format: /virtual/path:/local/path`);
614
1099
  }
@@ -631,7 +1116,7 @@ function buildStaticMap(rawMappings: string[]): Record<string, string> {
631
1116
  for (const mapping of rawMappings) {
632
1117
  const { virtual, local } = parseStaticMapping(mapping);
633
1118
  if (Object.hasOwn(map, virtual)) {
634
- console.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
1119
+ log.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
635
1120
  }
636
1121
  map[virtual] = local;
637
1122
  }
@@ -642,15 +1127,35 @@ function buildStaticMap(rawMappings: string[]): Record<string, string> {
642
1127
  // Extra args parser
643
1128
  // ---------------------------------------------------------------------------
644
1129
 
1130
+ /**
1131
+ * Vivliostyle's config object uses camelCase keys (`viewerParam`, `userStyle`)
1132
+ * and typed values, so `--viewer-param` has to arrive as `viewerParam` and
1133
+ * `--timeout 60000` as the number 60000.
1134
+ */
1135
+ export function normalizeExtraKey(key: string): string {
1136
+ return key.replace(/-([a-z0-9])/g, (_match, char: string) => char.toUpperCase());
1137
+ }
1138
+
1139
+ export function coerceExtraValue(value: string): string | number | boolean {
1140
+ if (value === "true") return true;
1141
+ if (value === "false") return false;
1142
+ // Only plain integers, so that version-like strings ("1.9.2") stay strings.
1143
+ return /^-?\d+$/.test(value) ? Number.parseInt(value, 10) : value;
1144
+ }
1145
+
645
1146
  export function parseExtraArgs(extraArgs: string[]): Record<string, unknown> {
646
1147
  const extraConfig: Record<string, unknown> = {};
647
1148
 
1149
+ const assign = (rawKey: string, rawValue: string | boolean): void => {
1150
+ extraConfig[normalizeExtraKey(rawKey)] = typeof rawValue === "boolean" ? rawValue : coerceExtraValue(rawValue);
1151
+ };
1152
+
648
1153
  for (let i = 0; i < extraArgs.length; i++) {
649
1154
  const arg = extraArgs[i];
650
1155
 
651
1156
  if (!arg.startsWith("--")) {
652
1157
  if (arg.startsWith("-")) {
653
- console.warn(
1158
+ log.warn(
654
1159
  `[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
655
1160
  ` Use the long-form --flag equivalent instead.`
656
1161
  );
@@ -660,26 +1165,21 @@ export function parseExtraArgs(extraArgs: string[]): Record<string, unknown> {
660
1165
 
661
1166
  if (arg.includes("=")) {
662
1167
  const eqIdx = arg.indexOf("=");
663
- const key = arg.slice(2, eqIdx);
664
- const val = arg.slice(eqIdx + 1);
665
- extraConfig[key] = val === "true" ? true : val === "false" ? false : val;
1168
+ assign(arg.slice(2, eqIdx), arg.slice(eqIdx + 1));
666
1169
  continue;
667
1170
  }
668
1171
 
669
1172
  const key = arg.slice(2);
670
1173
  const next = extraArgs[i + 1];
671
1174
 
672
- if (next === "true") {
673
- extraConfig[key] = true;
674
- i++;
675
- } else if (next === "false") {
676
- extraConfig[key] = false;
1175
+ if (next === "true" || next === "false") {
1176
+ assign(key, next === "true");
677
1177
  i++;
678
- } else if (next && !next.startsWith("-")) {
679
- extraConfig[key] = next;
1178
+ } else if (next !== undefined && !next.startsWith("-")) {
1179
+ assign(key, next);
680
1180
  i++;
681
1181
  } else {
682
- extraConfig[key] = true;
1182
+ extraConfig[normalizeExtraKey(key)] = true;
683
1183
  }
684
1184
  }
685
1185
 
@@ -775,7 +1275,57 @@ function buildProgram(): Command {
775
1275
  (val: string, prev: string[]) => prev.concat(val),
776
1276
  []
777
1277
  )
778
- .option("--cwd <dir>", "Working directory for Vivliostyle (default: directory of --input)")
1278
+ .option(
1279
+ "--allow-remote",
1280
+ [
1281
+ "Keep subresource references that would be fetched from the network.",
1282
+ "By default every reference without a local file is removed from the",
1283
+ "input HTML so that nothing is loaded from the web.",
1284
+ "Hyperlinks (<a href>) are never touched. See also --fetch-missing."
1285
+ ].join("\n ")
1286
+ )
1287
+ .option(
1288
+ "--fetch-missing",
1289
+ [
1290
+ "Load references without a local file from the mapped origin instead of",
1291
+ "dropping them. The local server redirects missing files to the site",
1292
+ "origin, which also covers data that page scripts fetch by relative URL.",
1293
+ "Implies --allow-remote, so remote iframes and scripts are loaded too.",
1294
+ "Nothing is written to the input directory."
1295
+ ].join("\n ")
1296
+ )
1297
+ .option(
1298
+ "--wait-for-content [ms]",
1299
+ [
1300
+ "Delay pagination until the page's own async work finished: no request in",
1301
+ "flight and the document height stable for --quiet-ms (default 400).",
1302
+ "Without [ms] the hard limit of 25000ms applies; larger values are capped."
1303
+ ].join("\n ")
1304
+ )
1305
+ .option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
1306
+ .option(
1307
+ "--timeout <ms>",
1308
+ ["Give up on a page after <ms> (Vivliostyle default: 300000).", "Lower it for pages with embeds that never finish loading."].join(
1309
+ "\n "
1310
+ )
1311
+ )
1312
+ .option(
1313
+ "--pixel-ratio <n>",
1314
+ [
1315
+ "Render at n times the output resolution (Vivliostyle pixelRatio), e.g. 2.",
1316
+ "Layout and raster resolution increase while the page keeps its size,",
1317
+ "which removes pixel artifacts in canvas and WebGL content.",
1318
+ "Pages exposing window.__vivResize(factor) are also redrawn at n×",
1319
+ "backing pixels before printing, so output past 96dpi stays sharp."
1320
+ ].join("\n ")
1321
+ )
1322
+ .option(
1323
+ "--dump-html <dir>",
1324
+ [
1325
+ "Write the rewritten input HTML into <dir> and keep it, instead of a",
1326
+ "temporary file. Use it to inspect what Vivliostyle actually renders."
1327
+ ].join("\n ")
1328
+ )
779
1329
  .option("--format <format>", `Output format: ${validFormats.join(" | ")}`, "pdf")
780
1330
  .option("--log-level <level>", `Vivliostyle log level: ${validLogLevels.join(" | ")}`, "info")
781
1331
  .option("--mode <mode>", `Execution mode: ${validModes.join(" | ")}`, "build")
@@ -788,11 +1338,13 @@ function buildProgram(): Command {
788
1338
  "Notes:",
789
1339
  " • HTML input (.html/.htm) is detected automatically from the file extension.",
790
1340
  " • For HTML input, <link href> and <script src> are parsed and auto-mapped.",
1341
+ " • References without a local file are dropped (offline by default); use --allow-remote to keep them.",
791
1342
  " • Options after -- are forwarded verbatim to Vivliostyle.",
792
1343
  " • --debug sets --log-level to debug automatically.",
793
1344
  " • --preview and --mode preview are equivalent.",
794
- " • In preview mode Vivliostyle serves everything via its own Vite server.",
795
- " • In build mode an Express server is started to serve assets.",
1345
+ " • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
1346
+ " • the browser prints that page to PDF, so canvases and iframes stay real content.",
1347
+ " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
796
1348
  " • --asset-base localBase is also a fallback root for CSS-referenced assets."
797
1349
  ].join("\n")
798
1350
  );
@@ -823,31 +1375,93 @@ export function parseArgs(argv: string[]): {
823
1375
  return { options: program.opts<CliOptions>(), extraArgs };
824
1376
  }
825
1377
 
1378
+ // ---------------------------------------------------------------------------
1379
+ // Build runner helper
1380
+ // ---------------------------------------------------------------------------
1381
+
1382
+ type RenderParams = {
1383
+ documentUrl: string;
1384
+ viewerPageUrl: string;
1385
+ outputAbs: string;
1386
+ metaFields: Partial<Record<"title" | "author" | "language", string>>;
1387
+ viewerParams: ViewerParams;
1388
+ timeoutMs?: number;
1389
+ waitForSettle: boolean;
1390
+ chromeExecutable?: string;
1391
+ canvasScale?: number;
1392
+ };
1393
+
1394
+ async function runRender(params: RenderParams): Promise<void> {
1395
+ const request = {
1396
+ documentUrl: params.documentUrl,
1397
+ viewerPageUrl: params.viewerPageUrl,
1398
+ output: params.outputAbs,
1399
+ viewerParams: params.viewerParams,
1400
+ timeoutMs: params.timeoutMs,
1401
+ waitForSettle: params.waitForSettle,
1402
+ ...(params.chromeExecutable === undefined ? {} : { chromeExecutable: params.chromeExecutable }),
1403
+ ...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
1404
+ ...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
1405
+ ...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
1406
+ ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language })
1407
+ };
1408
+
1409
+ log.trace("renderPdf request", request);
1410
+ const result = await renderPdf(request);
1411
+ log.trace("renderPdf result", { pageCount: result.pageCount, bytes: result.bytes, settle: result.settle });
1412
+ log.info(`✓ Document created: ${result.output} (${result.pageCount} pages)`);
1413
+ }
1414
+
826
1415
  // ---------------------------------------------------------------------------
827
1416
  // Core execute
828
1417
  // ---------------------------------------------------------------------------
829
1418
 
830
- export async function execute(options: CliOptions, extraArgs: string[] = []): Promise<void> {
831
- const debugEnabled = !!(options.debug || options.logLevel === "debug");
832
- const dbg = makeDbg(debugEnabled);
1419
+ /**
1420
+ * Log level for the wrapper's own output. `-d` wins over `--log-level`, which
1421
+ * is also forwarded to Vivliostyle unchanged.
1422
+ */
1423
+ function resolveInternalLogLevel(options: CliOptions): LogLevel {
1424
+ if (options.debug === true) return "debug";
1425
+ const level = options.logLevel as LogLevel;
1426
+ return validLogLevels.includes(level) ? level : "info";
1427
+ }
1428
+
1429
+ /**
1430
+ * `--wait-for-content [ms]`: hold the document's load event until the page's own
1431
+ * async work finished. Vivliostyle stops waiting for images after 30s, so the
1432
+ * hard limit is capped below that.
1433
+ */
1434
+ const MAX_SETTLE_DEADLINE_MS = 25_000;
1435
+
1436
+ export function resolveSettleGate(options: CliOptions): SettleGate | null {
1437
+ const raw = options.waitForContent;
1438
+ if (raw === undefined || raw === false) return null;
1439
+
1440
+ const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
1441
+ if (!Number.isFinite(requested) || requested <= 0) throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
1442
+
1443
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
1444
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0) throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
1445
+
1446
+ return {
1447
+ quietMs: quietRaw,
1448
+ deadlineMs: Math.min(requested, MAX_SETTLE_DEADLINE_MS)
1449
+ };
1450
+ }
833
1451
 
834
- dbg("raw CLI options", options);
835
- dbg("extra args (after --)", extraArgs);
1452
+ export async function execute(options: CliOptions, extraArgs: string[] = []): Promise<void> {
1453
+ log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
1454
+ log.trace("raw CLI options", options);
1455
+ log.trace("extra args (after --)", extraArgs);
836
1456
 
837
1457
  if (!options.input) throw new Error("Missing required option: --input");
838
1458
 
839
1459
  const inputAbs = resolve(options.input);
840
- dbg("resolved input", inputAbs);
1460
+ log.trace("resolved input", inputAbs);
841
1461
  if (!existsSync(inputAbs)) throw new Error(`Input file does not exist: ${inputAbs}`);
842
1462
 
843
- const cwd = options.cwd ? resolve(options.cwd) : dirname(inputAbs);
844
- if (!existsSync(cwd)) {
845
- throw new Error(`Working directory does not exist: ${cwd}`);
846
- }
847
- dbg("cwd", cwd);
848
-
849
1463
  const outputAbs = resolve(options.output);
850
- dbg("resolved output", outputAbs);
1464
+ log.trace("resolved output", outputAbs);
851
1465
 
852
1466
  if (!validFormats.includes(options.format as OutputFormat)) {
853
1467
  throw new Error(`Invalid format: "${options.format}". Allowed: ${validFormats.join(", ")}`);
@@ -858,215 +1472,308 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
858
1472
  throw new Error(`Invalid log level: "${options.logLevel}". Allowed: ${validLogLevels.join(", ")}`);
859
1473
  }
860
1474
  const logLevel: LogLevel = options.debug ? "debug" : (options.logLevel as LogLevel);
861
- dbg("logLevel", logLevel);
1475
+ log.trace("logLevel", logLevel);
862
1476
 
863
1477
  const mode = (options.preview ? "preview" : options.mode) as Mode;
864
1478
  if (!validModes.includes(mode)) {
865
1479
  throw new Error(`Invalid mode: "${mode}". Allowed: ${validModes.join(", ")}`);
866
1480
  }
867
- dbg("mode", mode);
1481
+ log.trace("mode", mode);
868
1482
 
869
1483
  const htmlMode = isHtmlInput(inputAbs);
870
- dbg("htmlMode (auto-detected)", htmlMode);
1484
+ log.trace("htmlMode (auto-detected)", htmlMode);
871
1485
 
872
1486
  if (!htmlMode) {
873
1487
  if (options.assetBase.length > 0) {
874
- console.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
1488
+ log.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
875
1489
  }
876
1490
  if (options.ignoreAsset.length > 0) {
877
- console.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
1491
+ log.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
878
1492
  }
879
1493
  }
880
1494
 
881
1495
  const assetBases = options.assetBase.map(parseAssetBaseMapping);
882
- dbg("parsed assetBases", assetBases);
1496
+ log.trace("parsed assetBases", assetBases);
883
1497
 
884
1498
  const ignoredAssets = new Set(options.ignoreAsset.map(normalizeIgnoreAssetPath));
885
- dbg("ignoredAssets", [...ignoredAssets]);
1499
+ log.trace("ignoredAssets", [...ignoredAssets]);
886
1500
 
887
1501
  // ── HTML-derived mappings ────────────────────────────────────────────────
888
1502
  const derivedMappings: string[] = [];
889
1503
 
890
1504
  if (htmlMode) {
891
1505
  const htmlDir = dirname(inputAbs);
892
- console.log(`[html] Analysing input as HTML: ${inputAbs}`);
1506
+ log.info(`[html] Analysing input as HTML: ${inputAbs}`);
893
1507
 
894
1508
  const includeScripts = mode === "preview" ? true : options.scripts;
895
1509
  const urls = extractUrlsFromHtml(inputAbs, includeScripts);
896
1510
 
897
1511
  if (urls.length === 0) {
898
- console.log("[html] No URLs found in input HTML");
1512
+ log.info("[html] No URLs found in input HTML");
899
1513
  } else {
900
- console.log(`[html] Found URLs (${urls.length}):`);
1514
+ log.info(`[html] Found URLs (${urls.length}):`);
901
1515
  }
902
1516
 
903
1517
  for (const url of urls) {
904
- const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg);
1518
+ const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets);
905
1519
  if (result.kind === "skipped") {
906
- console.log(` → Skipped (${result.reason}): ${url}`);
1520
+ log.info(` → Skipped (${result.reason}): ${url}`);
907
1521
  continue;
908
1522
  }
909
- console.log(` → Mapping: ${result.mapping}`);
1523
+ log.info(` → Mapping: ${result.mapping}`);
910
1524
  derivedMappings.push(result.mapping);
911
1525
  }
912
1526
 
913
- dbg("derived static mappings from HTML", derivedMappings);
1527
+ log.trace("derived static mappings from HTML", derivedMappings);
914
1528
  }
915
1529
 
916
1530
  // ── static map ────────────────────────────────────────────────────────────
917
1531
  const allStaticMappings = [...options.static, ...derivedMappings];
918
- dbg("all raw static mappings", allStaticMappings);
1532
+ log.trace("all raw static mappings", allStaticMappings);
919
1533
 
920
1534
  const staticMap = buildStaticMap(allStaticMappings);
921
- dbg("assembled staticMap", staticMap);
1535
+ log.trace("assembled staticMap", staticMap);
922
1536
 
923
- const hasStatic = Object.keys(staticMap).length > 0;
1537
+ // Mappings derived from the HTML have already been reported by
1538
+ // urlToStaticMapping; only explicit --static mounts are checked here.
1539
+ const derivedVirtualPaths = new Set(derivedMappings.map((mapping) => parseStaticMapping(mapping).virtual));
924
1540
 
925
1541
  for (const [virtualPath, localPath] of Object.entries(staticMap)) {
1542
+ if (derivedVirtualPaths.has(virtualPath)) continue;
926
1543
  if (!existsSync(localPath)) {
927
- console.warn(
1544
+ log.warn(
928
1545
  `[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`
929
1546
  );
930
1547
  }
931
1548
  }
932
1549
 
933
1550
  const extraConfig = parseExtraArgs(extraArgs);
934
- dbg("extraConfig (parsed from -- args)", extraConfig);
1551
+ log.trace("extraConfig (parsed from -- args)", extraConfig);
935
1552
 
936
1553
  const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
937
1554
 
938
- console.log(`Starting Vivliostyle in mode: ${mode}`);
1555
+ const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
1556
+ const settle = resolveSettleGate(options);
1557
+ const htmlOptions: HtmlRewriteOptions = {
1558
+ allowRemote: fetchMissing,
1559
+ fetchMissing,
1560
+ dumpDir: options.dumpHtml ?? null,
1561
+ settle,
1562
+ ...(typeof extraConfig.css === "string" ? { css: extraConfig.css } : {}),
1563
+ ...(typeof extraConfig.userStyle === "string" ? { userStyle: extraConfig.userStyle } : {})
1564
+ };
1565
+ log.trace("htmlRewriteOptions", htmlOptions);
939
1566
 
940
- // ── BUILD mode ─────────────────────────────────────────────────────────────
1567
+ if (options.timeout !== undefined) {
1568
+ const timeoutMs = Number.parseInt(options.timeout, 10);
1569
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error(`Invalid --timeout: "${options.timeout}"`);
1570
+ extraConfig.timeout = timeoutMs;
1571
+ log.info(`[render] timeout=${timeoutMs}ms`);
1572
+ }
1573
+
1574
+ if (options.pixelRatio !== undefined) {
1575
+ const ratio = Number.parseFloat(options.pixelRatio);
1576
+ if (!Number.isFinite(ratio) || ratio <= 0) throw new Error(`Invalid --pixel-ratio: "${options.pixelRatio}"`);
1577
+ const existing = typeof extraConfig.viewerParam === "string" ? extraConfig.viewerParam : "";
1578
+ extraConfig.viewerParam = existing === "" ? `pixelRatio=${ratio}` : `${existing}&pixelRatio=${ratio}`;
1579
+ log.info(`[render] pixelRatio=${ratio}`);
1580
+ }
1581
+ // Canvas/WebGL backing-store upscale follows --pixel-ratio: layout keeps its
1582
+ // CSS size while JS-painted pixels are redrawn at n× resolution so print
1583
+ // output past 96dpi stays sharp. Pages opt in via window.__vivResize(factor).
1584
+ const canvasScale =
1585
+ options.pixelRatio === undefined
1586
+ ? undefined
1587
+ : (() => {
1588
+ const ratio = Number.parseFloat(options.pixelRatio);
1589
+ return Number.isFinite(ratio) && ratio > 1 ? ratio : undefined;
1590
+ })();
1591
+
1592
+ log.info(`Starting Vivliostyle in mode: ${mode}`);
1593
+
1594
+ // ── BUILD mode ───────────────────────────────────────────────────────────────
941
1595
  if (mode === "build") {
942
- let vivliostyleInput = inputAbs;
943
- let htmlCleanup = (): void => undefined;
1596
+ if (format !== "pdf") throw new Error(`Unsupported format: ${format}. This renderer produces PDF only.`);
1597
+
1598
+ const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
1599
+ const viewerLibDir = resolveViewerLibDir();
1600
+ log.trace("viewerLibDir", viewerLibDir);
1601
+ log.trace("sitePath", sitePath);
1602
+
1603
+ const entry: { localPath: string | null; sitePath: string } = { localPath: null, sitePath };
1604
+ const server = await startStaticServer({
1605
+ staticMap,
1606
+ assetBases,
1607
+ entry,
1608
+ fetchMissing: htmlOptions.fetchMissing === true,
1609
+ settle: htmlOptions.settle ?? null,
1610
+ viewerLibDir,
1611
+ viewerFilePath: join(viewerLibDir, "index.html"),
1612
+ log: (message) => log.info(message),
1613
+ onSettled: ({ reason, waitedMs, detail }) => {
1614
+ // Detail is logged in both branches: the deadline case is exactly
1615
+ // when canvas sizes and readiness matter most (e.g. slow WebGL).
1616
+ const line = `[wait] layout gate ${reason} after ${waitedMs}ms`;
1617
+ const withDetail = detail === undefined ? line : `${line} ${JSON.stringify(detail)}`;
1618
+ if (reason === "settled") log.info(withDetail);
1619
+ else log.warn(`${withDetail} — content may be incomplete`);
1620
+ }
1621
+ });
944
1622
 
945
- if (hasStatic || assetBases.length > 0) {
946
- const server = await startStaticServer(staticMap, assetBases, null, dbg);
1623
+ const htmlResource = { cleanup: (): void => undefined };
947
1624
 
948
- try {
949
- if (htmlMode) {
950
- ({ vivliostyleInput, cleanup: htmlCleanup } = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, dbg));
951
- }
952
-
953
- dbg("vivliostyleInput (final)", vivliostyleInput);
954
-
955
- const config: BuildConfig = {
956
- cwd,
957
- input: vivliostyleInput,
958
- output: [{ path: outputAbs, format }],
959
- ...metaFields,
960
- logLevel,
961
- ...(options.debug ? { debug: true } : {}),
962
- ...extraConfig
963
- };
964
- dbg("final BuildConfig", config);
965
- await build(config);
966
- console.log(`✓ Document created: ${outputAbs}`);
967
- } finally {
968
- htmlCleanup();
969
- server.close();
1625
+ try {
1626
+ // Remote references are only worth keeping if they still exist.
1627
+ const remoteReferences = collectRemoteReferences(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document).filter((url) =>
1628
+ referencesToProbe(url, assetBases)
1629
+ );
1630
+ const unavailableUrls = htmlOptions.fetchMissing === true ? await probeRemoteReferences(remoteReferences) : undefined;
1631
+ if (unavailableUrls !== undefined && unavailableUrls.size > 0) {
1632
+ log.warn(`[fetch] ${unavailableUrls.size} remote reference(s) are unavailable and will be dropped`);
970
1633
  }
971
- } else {
972
- dbg("vivliostyleInput (final)", vivliostyleInput);
973
-
974
- const config: BuildConfig = {
975
- cwd,
976
- input: vivliostyleInput,
977
- output: [{ path: outputAbs, format }],
978
- ...metaFields,
979
- logLevel,
980
- ...(options.debug ? { debug: true } : {}),
981
- ...extraConfig
982
- };
983
- dbg("final BuildConfig", config);
984
- await build(config);
985
- console.log(`✓ Document created: ${outputAbs}`);
1634
+
1635
+ const prepared = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, {
1636
+ ...htmlOptions,
1637
+ unavailableUrls,
1638
+ shimOrigin: server.baseUrl,
1639
+ // The viewer is served next to the document, so scripts the page runs
1640
+ // resolve their relative URLs against the document's own directory.
1641
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
1642
+ });
1643
+ htmlResource.cleanup = prepared.cleanup;
1644
+ entry.localPath = prepared.vivliostyleInput;
1645
+
1646
+ const documentUrl = `${server.baseUrl}${sitePath}`;
1647
+ const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
1648
+ log.info(`[html] Serving document at ${documentUrl}`);
1649
+
1650
+ await runRender({
1651
+ documentUrl,
1652
+ viewerPageUrl,
1653
+ outputAbs,
1654
+ metaFields,
1655
+ viewerParams: buildRenderViewerParams(extraConfig, htmlOptions),
1656
+ timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
1657
+ waitForSettle: htmlOptions.settle != null,
1658
+ chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
1659
+ canvasScale
1660
+ });
1661
+ } finally {
1662
+ htmlResource.cleanup();
1663
+ await server.close();
986
1664
  }
1665
+ return;
1666
+ }
987
1667
 
988
- // ── PREVIEW mode ───────────────────────────────────────────────────────────
989
- } else {
990
- let previewInput = inputAbs;
991
- let htmlCleanup = (): void => undefined;
992
- const previewStaticMap: Record<string, string> = { ...staticMap };
993
-
994
- if (htmlMode) {
995
- const { htmlPath, extraStatic, cleanup } = buildPreviewHtml(inputAbs, assetBases, dbg);
996
- previewInput = htmlPath;
997
- htmlCleanup = cleanup;
998
-
999
- for (const [virtual, local] of Object.entries(extraStatic)) {
1000
- if (!Object.hasOwn(previewStaticMap, virtual)) {
1001
- previewStaticMap[virtual] = local;
1002
- console.log(`[preview] AssetBase static mount: ${virtual} → ${local}`);
1003
- } else {
1004
- dbg("preview: skipping assetBase mount shadowed by explicit --static", { virtual, local });
1005
- }
1006
- }
1668
+ // ── PREVIEW mode ─────────────────────────────────────────────────────────────
1669
+ {
1670
+ const preview = await startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraConfig);
1671
+ log.info(`[preview] ${preview.url}`);
1672
+ await openInBrowser(preview.url);
1673
+
1674
+ await new Promise<void>((resolvePromise) => {
1675
+ const stop = (): void => {
1676
+ process.off("SIGINT", stop);
1677
+ process.off("SIGTERM", stop);
1678
+ resolvePromise();
1679
+ };
1680
+ process.once("SIGINT", stop);
1681
+ process.once("SIGTERM", stop);
1682
+ });
1007
1683
 
1008
- if (htmlPath !== inputAbs) {
1009
- console.log(`[preview] Using rewritten HTML: ${htmlPath}`);
1010
- }
1011
- }
1684
+ await preview.close();
1685
+ }
1686
+ }
1012
1687
 
1013
- dbg("preview input (final)", previewInput);
1014
- dbg("previewStaticMap (final)", previewStaticMap);
1015
-
1016
- const hasPreviewStatic = Object.keys(previewStaticMap).length > 0;
1017
-
1018
- const previewCwd = dirname(previewInput);
1019
- dbg("previewCwd", previewCwd);
1020
-
1021
- const previewEntry = previewInput.slice(previewCwd.length + 1);
1022
- dbg("previewEntry (relative, for configData only)", previewEntry);
1023
-
1024
- const config: PreviewConfig = {
1025
- cwd: previewCwd,
1026
- input: previewInput,
1027
- logLevel,
1028
- enableStaticServe: true,
1029
- openViewer: true,
1030
- singleDoc: true,
1031
- ...(hasPreviewStatic
1032
- ? {
1033
- configData: [
1034
- {
1035
- entry: previewEntry,
1036
- ...metaFields,
1037
- static: previewStaticMap as StaticMap
1038
- }
1039
- ]
1040
- }
1041
- : {}),
1042
- ...(options.debug ? { debug: true } : {}),
1043
- ...extraConfig
1044
- };
1688
+ export type PreviewTarget = {
1689
+ /** URL of the viewer, showing the document. */
1690
+ url: string;
1691
+ /** URL the viewer loads the document from. */
1692
+ documentUrl: string;
1693
+ close: () => Promise<void>;
1694
+ };
1045
1695
 
1046
- dbg("final PreviewConfig", config);
1696
+ /**
1697
+ * Serves the rewritten document next to the viewer and returns the URL to open.
1698
+ *
1699
+ * The viewer page lives in the document's own directory, so the preview shows
1700
+ * exactly what the PDF render would lay out.
1701
+ */
1702
+ export async function startPreview(
1703
+ inputAbs: string,
1704
+ assetBases: AssetBaseMapping[],
1705
+ staticMap: StaticMap,
1706
+ htmlOptions: HtmlRewriteOptions,
1707
+ extraConfig: Record<string, unknown>
1708
+ ): Promise<PreviewTarget> {
1709
+ const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
1710
+ const viewerLibDir = resolveViewerLibDir();
1711
+ const entry: { localPath: string | null; sitePath: string } = { localPath: null, sitePath };
1712
+
1713
+ const server = await startStaticServer({
1714
+ staticMap,
1715
+ assetBases,
1716
+ entry,
1717
+ fetchMissing: htmlOptions.fetchMissing === true,
1718
+ viewerLibDir,
1719
+ viewerFilePath: join(viewerLibDir, "index.html"),
1720
+ log: (message) => log.info(message)
1721
+ });
1047
1722
 
1048
- const shutdown = (): void => {
1049
- htmlCleanup();
1050
- process.exit(0);
1051
- };
1052
- process.once("SIGINT", shutdown);
1053
- process.once("SIGTERM", shutdown);
1723
+ const prepared = buildPreviewHtml(inputAbs, assetBases, htmlOptions);
1724
+ entry.localPath = prepared.htmlPath;
1054
1725
 
1055
- try {
1056
- await preview(config);
1057
- } catch (err) {
1058
- process.off("SIGINT", shutdown);
1059
- process.off("SIGTERM", shutdown);
1060
- htmlCleanup();
1061
- console.error("[preview] Full error:", err);
1062
- const message = err instanceof Error ? err.message : String(err);
1063
- throw new Error(`preview() failed:\n${message}`);
1726
+ const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
1727
+ const documentUrl = `${server.baseUrl}${sitePath}`;
1728
+ const url = buildViewerUrl(viewerPageUrl, {
1729
+ src: documentUrl,
1730
+ bookMode: false,
1731
+ renderAllPages: false,
1732
+ ...buildRenderViewerParams(extraConfig, htmlOptions)
1733
+ });
1734
+
1735
+ return {
1736
+ url,
1737
+ documentUrl,
1738
+ close: async () => {
1739
+ prepared.cleanup();
1740
+ await server.close();
1064
1741
  }
1742
+ };
1743
+ }
1744
+
1745
+ /** Opens a URL in the user's browser; preview mode is a plain server. */
1746
+ async function openInBrowser(url: string): Promise<void> {
1747
+ const { spawn } = await import("node:child_process");
1748
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
1749
+ try {
1750
+ const child = spawn(command, [url], { stdio: "ignore", detached: true });
1751
+ child.unref();
1752
+ } catch (err) {
1753
+ log.warn(`[preview] Could not open a browser: ${String(err)}`);
1754
+ }
1755
+ }
1065
1756
 
1066
- process.off("SIGINT", shutdown);
1067
- process.off("SIGTERM", shutdown);
1068
- htmlCleanup();
1757
+ /**
1758
+ * Viewer parameters for the render: layout overrides from `--` plus the options
1759
+ * the wrapper owns (page size, output resolution, user stylesheet).
1760
+ */
1761
+ function buildRenderViewerParams(extraConfig: Record<string, unknown>, htmlOptions: HtmlRewriteOptions): ViewerParams {
1762
+ const params: ViewerParams = {};
1763
+
1764
+ if (typeof extraConfig.size === "string") params.size = extraConfig.size;
1765
+ if (typeof extraConfig.viewerParam === "string") {
1766
+ for (const pair of extraConfig.viewerParam.split("&")) {
1767
+ if (pair === "") continue;
1768
+ const eq = pair.indexOf("=");
1769
+ if (eq === -1) params[pair] = true;
1770
+ else params[pair.slice(0, eq)] = pair.slice(eq + 1);
1771
+ }
1069
1772
  }
1773
+ if (htmlOptions.css !== undefined) params.style = htmlOptions.css;
1774
+ if (htmlOptions.userStyle !== undefined) params.userStyle = htmlOptions.userStyle;
1775
+
1776
+ return params;
1070
1777
  }
1071
1778
 
1072
1779
  // ---------------------------------------------------------------------------
@@ -1097,7 +1804,7 @@ if (isDirectExecution()) {
1097
1804
  }
1098
1805
 
1099
1806
  execute(parsed.options, parsed.extraArgs).catch((err: unknown) => {
1100
- console.error(err instanceof Error ? err.message : String(err));
1807
+ log.error(err instanceof Error ? err.message : String(err));
1101
1808
  process.exit(1);
1102
1809
  });
1103
1810
  }