@projektemacher/vivliostyle-batch-cli 0.1.1 → 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.
- package/{LICENCE → LICENSE} +1 -1
- package/README.md +73 -30
- package/dist/index.d.ts +211 -42
- package/dist/vivliostyle-batch-cli.js +1557 -399
- package/package.json +31 -20
- package/src/render/chrome.ts +103 -0
- package/src/render/pdf.ts +306 -0
- package/src/render/viewer.ts +46 -0
- package/src/server.ts +300 -0
- package/src/vivliostyle-cli.ts +1164 -439
package/src/vivliostyle-cli.ts
CHANGED
|
@@ -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 {
|
|
3
|
-
import {
|
|
4
|
-
import { readFileSync, existsSync, mkdtempSync, writeFileSync, rmSync, statSync } 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
|
|
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
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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"
|
|
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
|
-
//
|
|
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
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
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
|
|
65
|
-
|
|
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
|
-
//
|
|
324
|
+
// HTML input detection
|
|
70
325
|
// ---------------------------------------------------------------------------
|
|
71
326
|
|
|
72
|
-
function
|
|
73
|
-
return (
|
|
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,159 +342,398 @@ export function splitArgsAtDoubleDash(argv: string[]): {
|
|
|
94
342
|
}
|
|
95
343
|
|
|
96
344
|
// ---------------------------------------------------------------------------
|
|
97
|
-
// Static
|
|
345
|
+
// Static mappings
|
|
98
346
|
// ---------------------------------------------------------------------------
|
|
99
347
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
+
}
|
|
133
528
|
}
|
|
134
|
-
dbg("[static-server] mount", { virtual, absLocal });
|
|
135
529
|
}
|
|
136
530
|
|
|
137
|
-
|
|
138
|
-
const absLocal = resolve(ab.localBase);
|
|
139
|
-
app.use("/", serveStatic(absLocal, { fallthrough: true, setHeaders: makeMimeHeaders }));
|
|
140
|
-
dbg("[static-server] assetBase fallback mount", absLocal);
|
|
141
|
-
console.log(`[static-server] Fallback mount: / → ${absLocal}`);
|
|
142
|
-
}
|
|
531
|
+
return [...unserved];
|
|
143
532
|
}
|
|
144
533
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
dbg("[static-server] serving HTML entry", absHtmlPath);
|
|
159
|
-
res.type("text/html").sendFile(absHtmlPath);
|
|
160
|
-
});
|
|
161
|
-
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
|
+
}
|
|
162
547
|
}
|
|
163
548
|
|
|
164
|
-
|
|
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
|
+
}
|
|
165
563
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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>();
|
|
170
571
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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
|
+
);
|
|
181
587
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
if (closed) return;
|
|
185
|
-
closed = true;
|
|
186
|
-
httpServer.close((err) => {
|
|
187
|
-
if (err) console.warn(`[static-server] close error: ${err.message}`);
|
|
188
|
-
else dbg("[static-server] stopped");
|
|
189
|
-
});
|
|
190
|
-
};
|
|
588
|
+
return unavailable;
|
|
589
|
+
}
|
|
191
590
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
+
}
|
|
196
642
|
}
|
|
197
643
|
|
|
198
644
|
// ---------------------------------------------------------------------------
|
|
199
|
-
//
|
|
645
|
+
// Asset base match result
|
|
200
646
|
// ---------------------------------------------------------------------------
|
|
201
647
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
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" };
|
|
212
660
|
|
|
213
|
-
export function
|
|
214
|
-
|
|
215
|
-
|
|
661
|
+
export function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): AssetBaseMatch {
|
|
662
|
+
for (const mapping of assetBases) {
|
|
663
|
+
if (!url.startsWith(mapping.urlBase)) continue;
|
|
216
664
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
changed = true;
|
|
224
|
-
}
|
|
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];
|
|
225
671
|
}
|
|
226
|
-
}
|
|
227
672
|
|
|
228
|
-
|
|
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" };
|
|
229
684
|
}
|
|
230
685
|
|
|
231
|
-
export function
|
|
232
|
-
|
|
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
|
+
}
|
|
233
699
|
|
|
700
|
+
export function rewriteVirtualPathsToServerInDom(
|
|
701
|
+
document: Document,
|
|
702
|
+
staticMapKeys: string[],
|
|
703
|
+
serverBaseUrl: string,
|
|
704
|
+
isServable?: (virtualPath: string) => boolean
|
|
705
|
+
): boolean {
|
|
234
706
|
const shouldRewrite = (path: string): boolean => {
|
|
235
707
|
if (!path.startsWith("/")) return false;
|
|
236
|
-
|
|
708
|
+
if (staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`))) return true;
|
|
709
|
+
return isServable !== undefined && isServable(path);
|
|
237
710
|
};
|
|
238
711
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
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;
|
|
245
733
|
}
|
|
246
734
|
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
return changed;
|
|
735
|
+
return false;
|
|
736
|
+
};
|
|
250
737
|
}
|
|
251
738
|
|
|
252
739
|
// ---------------------------------------------------------------------------
|
|
@@ -289,15 +776,26 @@ export function extractUrlsFromHtml(htmlPath: string, includeScripts = true, doc
|
|
|
289
776
|
|
|
290
777
|
const urls = new Set<string>();
|
|
291
778
|
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
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;
|
|
784
|
+
|
|
785
|
+
for (const el of document.querySelectorAll(selector)) {
|
|
786
|
+
const raw = el.getAttribute(attr);
|
|
787
|
+
if (raw === null) continue;
|
|
296
788
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
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
|
+
}
|
|
301
799
|
}
|
|
302
800
|
}
|
|
303
801
|
|
|
@@ -308,29 +806,15 @@ export function extractUrlsFromHtml(htmlPath: string, includeScripts = true, doc
|
|
|
308
806
|
// Preview HTML builder
|
|
309
807
|
// ---------------------------------------------------------------------------
|
|
310
808
|
|
|
311
|
-
/**
|
|
312
|
-
* Rewrites absolute external URLs to root-relative virtual paths and writes
|
|
313
|
-
* the result as a sibling of the original input file so that
|
|
314
|
-
* cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
|
|
315
|
-
*
|
|
316
|
-
* The output filename uses a non-dotfile prefix so Vite's static server
|
|
317
|
-
* (which ignores dotfiles by default) can serve it correctly.
|
|
318
|
-
*
|
|
319
|
-
* Also derives extra static mounts from each assetBase so that secondary
|
|
320
|
-
* assets referenced from CSS (fonts, images) are served by Vivliostyle's
|
|
321
|
-
* own Vite server without needing Express.
|
|
322
|
-
*
|
|
323
|
-
* Returns:
|
|
324
|
-
* - htmlPath – sibling file path, or inputAbs if no rewriting was needed
|
|
325
|
-
* - extraStatic – virtual→local entries for assetBase roots to merge into
|
|
326
|
-
* the static map passed to Vivliostyle
|
|
327
|
-
* - cleanup – deletes the sibling file (no-op if inputAbs was returned)
|
|
328
|
-
*/
|
|
329
809
|
export function buildPreviewHtml(
|
|
330
810
|
inputAbs: string,
|
|
331
811
|
assetBases: AssetBaseMapping[],
|
|
332
|
-
|
|
333
|
-
): {
|
|
812
|
+
options: HtmlRewriteOptions = {}
|
|
813
|
+
): {
|
|
814
|
+
htmlPath: string;
|
|
815
|
+
extraStatic: Record<string, string>;
|
|
816
|
+
cleanup: () => void;
|
|
817
|
+
} {
|
|
334
818
|
let content: string;
|
|
335
819
|
try {
|
|
336
820
|
content = readFileSync(inputAbs, "utf-8");
|
|
@@ -338,8 +822,6 @@ export function buildPreviewHtml(
|
|
|
338
822
|
throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
|
|
339
823
|
}
|
|
340
824
|
|
|
341
|
-
// Derive extra static mounts for each assetBase root so secondary assets
|
|
342
|
-
// referenced from CSS are also reachable through Vivliostyle's Vite server.
|
|
343
825
|
const extraStatic: Record<string, string> = {};
|
|
344
826
|
for (const ab of assetBases) {
|
|
345
827
|
let virtualPrefix: string;
|
|
@@ -351,39 +833,46 @@ export function buildPreviewHtml(
|
|
|
351
833
|
if (!virtualPrefix.endsWith("/")) virtualPrefix = `${virtualPrefix}/`;
|
|
352
834
|
const mapKey = virtualPrefix === "/" ? "/" : virtualPrefix.slice(0, -1);
|
|
353
835
|
if (Object.hasOwn(extraStatic, mapKey)) {
|
|
354
|
-
|
|
836
|
+
log.warn(
|
|
355
837
|
`[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`
|
|
356
838
|
);
|
|
357
839
|
}
|
|
358
840
|
extraStatic[mapKey] = resolve(ab.localBase);
|
|
359
|
-
|
|
841
|
+
log.trace("buildPreviewHtml: assetBase extra static mount", { mapKey, local: ab.localBase });
|
|
360
842
|
}
|
|
361
843
|
|
|
362
844
|
const dom = new JSDOM(content);
|
|
363
845
|
const document = dom.window.document;
|
|
364
846
|
const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
|
|
365
|
-
if (changed)
|
|
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);
|
|
366
851
|
|
|
367
|
-
if (!changed) {
|
|
368
|
-
|
|
852
|
+
if (!changed && dropped.length === 0) {
|
|
853
|
+
log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
|
|
369
854
|
return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
|
|
370
855
|
}
|
|
371
856
|
|
|
372
|
-
const
|
|
373
|
-
const
|
|
374
|
-
|
|
375
|
-
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));
|
|
376
860
|
|
|
861
|
+
if (dumpDir !== null) mkdirSync(dumpDir, { recursive: true });
|
|
377
862
|
writeFileSync(htmlPath, dom.serialize(), "utf-8");
|
|
378
|
-
|
|
379
|
-
|
|
863
|
+
log.trace("buildPreviewHtml: wrote rewritten HTML", htmlPath);
|
|
864
|
+
log.info(`[preview] Wrote rewritten HTML: ${htmlPath}`);
|
|
380
865
|
|
|
381
866
|
const cleanup = (): void => {
|
|
867
|
+
if (dumpDir !== null) {
|
|
868
|
+
log.trace("buildPreviewHtml: keeping dumped HTML", htmlPath);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
382
871
|
try {
|
|
383
872
|
rmSync(htmlPath, { force: true });
|
|
384
|
-
|
|
873
|
+
log.trace("buildPreviewHtml: removed rewritten HTML", htmlPath);
|
|
385
874
|
} catch (err) {
|
|
386
|
-
|
|
875
|
+
log.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
|
|
387
876
|
}
|
|
388
877
|
};
|
|
389
878
|
|
|
@@ -394,18 +883,12 @@ export function buildPreviewHtml(
|
|
|
394
883
|
// Build HTML builder
|
|
395
884
|
// ---------------------------------------------------------------------------
|
|
396
885
|
|
|
397
|
-
/**
|
|
398
|
-
* Prepares the HTML for BUILD mode.
|
|
399
|
-
* Both rewrite passes (absolute → virtual, virtual → absolute server URL)
|
|
400
|
-
* are applied in a single DOM parse.
|
|
401
|
-
* If nothing changed the original file path is returned with a no-op cleanup.
|
|
402
|
-
*/
|
|
403
886
|
export function prepareInputHtmlForBuild(
|
|
404
887
|
inputAbs: string,
|
|
405
888
|
assetBases: AssetBaseMapping[],
|
|
406
889
|
staticMap: Record<string, string>,
|
|
407
890
|
serverBaseUrl: string,
|
|
408
|
-
|
|
891
|
+
options: HtmlRewriteOptions = {}
|
|
409
892
|
): { vivliostyleInput: string; cleanup: () => void } {
|
|
410
893
|
let content: string;
|
|
411
894
|
try {
|
|
@@ -418,29 +901,64 @@ export function prepareInputHtmlForBuild(
|
|
|
418
901
|
const document = dom.window.document;
|
|
419
902
|
const staticMapKeys = Object.keys(staticMap);
|
|
420
903
|
|
|
421
|
-
const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases);
|
|
422
|
-
if (absChanged)
|
|
904
|
+
const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases, options.fetchMissing === true);
|
|
905
|
+
if (absChanged) log.trace("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
|
|
423
906
|
|
|
424
|
-
const
|
|
425
|
-
|
|
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");
|
|
426
910
|
|
|
427
|
-
|
|
428
|
-
|
|
911
|
+
const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
|
|
912
|
+
|
|
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
|
+
}
|
|
930
|
+
|
|
931
|
+
if (!absChanged && !srvChanged && dropped.length === 0 && gone.length === 0 && options.settle == null && !wantsRuntime) {
|
|
932
|
+
log.trace("prepareInputHtmlForBuild: no changes, using original file");
|
|
429
933
|
return { vivliostyleInput: inputAbs, cleanup: () => undefined };
|
|
430
934
|
}
|
|
431
935
|
|
|
432
|
-
const
|
|
433
|
-
|
|
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
|
+
|
|
434
948
|
writeFileSync(tmpHtml, dom.serialize(), "utf-8");
|
|
435
|
-
|
|
436
|
-
|
|
949
|
+
log.info(`[html] ${dumpDir === null ? "Prepared" : "Dumped"} input HTML → ${tmpHtml}`);
|
|
950
|
+
log.trace("prepareInputHtmlForBuild: written", tmpHtml);
|
|
437
951
|
|
|
438
952
|
const cleanup = (): void => {
|
|
953
|
+
if (tmpDir === null) {
|
|
954
|
+
log.trace("prepareInputHtmlForBuild: keeping dumped HTML", tmpHtml);
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
439
957
|
try {
|
|
440
958
|
rmSync(tmpDir, { recursive: true, force: true });
|
|
441
|
-
|
|
959
|
+
log.trace("prepareInputHtmlForBuild: removed temp dir", tmpDir);
|
|
442
960
|
} catch (err) {
|
|
443
|
-
|
|
961
|
+
log.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
|
|
444
962
|
}
|
|
445
963
|
};
|
|
446
964
|
|
|
@@ -478,27 +996,6 @@ export function parseAssetBaseMapping(value: string): AssetBaseMapping {
|
|
|
478
996
|
return { urlBase: normalizeUrlBase(urlBase), localBase };
|
|
479
997
|
}
|
|
480
998
|
|
|
481
|
-
export function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): { virtualPath: string; localPath: string } | null {
|
|
482
|
-
for (const mapping of assetBases) {
|
|
483
|
-
if (!url.startsWith(mapping.urlBase)) continue;
|
|
484
|
-
|
|
485
|
-
let cleanRelative: string;
|
|
486
|
-
try {
|
|
487
|
-
cleanRelative = new URL(url).pathname.slice(1);
|
|
488
|
-
} catch {
|
|
489
|
-
const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
|
|
490
|
-
cleanRelative = noQuery.split("#")[0];
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
if (!cleanRelative) return null;
|
|
494
|
-
|
|
495
|
-
const virtualPath = posix.resolve("/", cleanRelative);
|
|
496
|
-
const localPath = resolve(mapping.localBase, cleanRelative);
|
|
497
|
-
return { virtualPath, localPath };
|
|
498
|
-
}
|
|
499
|
-
return null;
|
|
500
|
-
}
|
|
501
|
-
|
|
502
999
|
// ---------------------------------------------------------------------------
|
|
503
1000
|
// MappingResult + urlToStaticMapping
|
|
504
1001
|
// ---------------------------------------------------------------------------
|
|
@@ -509,37 +1006,47 @@ export function urlToStaticMapping(
|
|
|
509
1006
|
url: string,
|
|
510
1007
|
htmlDir: string,
|
|
511
1008
|
assetBases: AssetBaseMapping[],
|
|
512
|
-
ignoredAssets: Set<string
|
|
513
|
-
dbg: Dbg
|
|
1009
|
+
ignoredAssets: Set<string>
|
|
514
1010
|
): MappingResult {
|
|
515
1011
|
const trimmed = url.trim();
|
|
516
1012
|
if (!trimmed) return { kind: "skipped", url, reason: "empty URL" };
|
|
517
1013
|
if (trimmed.startsWith("#")) return { kind: "skipped", url, reason: "fragment-only URL" };
|
|
518
1014
|
|
|
519
|
-
const
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
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 });
|
|
523
1028
|
return {
|
|
524
1029
|
kind: "skipped",
|
|
525
1030
|
url,
|
|
526
|
-
reason: `matches --ignore-asset "${
|
|
1031
|
+
reason: `matches --ignore-asset "${assetMatch.virtualPath}"`
|
|
527
1032
|
};
|
|
528
1033
|
}
|
|
529
|
-
if (!existsSync(
|
|
530
|
-
|
|
1034
|
+
if (!existsSync(assetMatch.localPath)) {
|
|
1035
|
+
log.warn(
|
|
531
1036
|
`[html] Warning: asset-base mapped path does not exist\n` +
|
|
532
1037
|
` url : ${url}\n` +
|
|
533
|
-
` virtual : ${
|
|
534
|
-
` local : ${
|
|
1038
|
+
` virtual : ${assetMatch.virtualPath}\n` +
|
|
1039
|
+
` local : ${assetMatch.localPath}`
|
|
535
1040
|
);
|
|
536
1041
|
}
|
|
537
1042
|
return {
|
|
538
1043
|
kind: "mapped",
|
|
539
|
-
mapping: `${
|
|
1044
|
+
mapping: `${assetMatch.virtualPath}:${assetMatch.localPath}`
|
|
540
1045
|
};
|
|
541
1046
|
}
|
|
542
1047
|
|
|
1048
|
+
// assetMatch.kind === "no-match" — proceed to local / external handling
|
|
1049
|
+
|
|
543
1050
|
if (trimmed.startsWith("//")) {
|
|
544
1051
|
return { kind: "skipped", url, reason: "protocol-relative external URL" };
|
|
545
1052
|
}
|
|
@@ -555,14 +1062,18 @@ export function urlToStaticMapping(
|
|
|
555
1062
|
|
|
556
1063
|
const [cleanUrl] = trimmed.split(/[?#]/);
|
|
557
1064
|
if (!cleanUrl) {
|
|
558
|
-
return {
|
|
1065
|
+
return {
|
|
1066
|
+
kind: "skipped",
|
|
1067
|
+
url,
|
|
1068
|
+
reason: "URL is empty after stripping query/fragment"
|
|
1069
|
+
};
|
|
559
1070
|
}
|
|
560
1071
|
|
|
561
1072
|
const localPath = resolve(htmlDir, cleanUrl);
|
|
562
1073
|
const virtualPath = cleanUrl.startsWith("/") ? posix.normalize(cleanUrl) : posix.resolve("/", posix.relative(htmlDir, localPath));
|
|
563
1074
|
|
|
564
1075
|
if (shouldIgnoreVirtualPath(virtualPath, ignoredAssets)) {
|
|
565
|
-
|
|
1076
|
+
log.trace("urlToStaticMapping: ignored (ignore-asset match)", { url, virtualPath });
|
|
566
1077
|
return {
|
|
567
1078
|
kind: "skipped",
|
|
568
1079
|
url,
|
|
@@ -571,7 +1082,7 @@ export function urlToStaticMapping(
|
|
|
571
1082
|
}
|
|
572
1083
|
|
|
573
1084
|
if (!existsSync(localPath)) {
|
|
574
|
-
|
|
1085
|
+
log.warn(
|
|
575
1086
|
`[html] Warning: referenced path does not exist\n` +
|
|
576
1087
|
` url : ${url}\n` +
|
|
577
1088
|
` virtual : ${virtualPath}\n` +
|
|
@@ -605,7 +1116,7 @@ function buildStaticMap(rawMappings: string[]): Record<string, string> {
|
|
|
605
1116
|
for (const mapping of rawMappings) {
|
|
606
1117
|
const { virtual, local } = parseStaticMapping(mapping);
|
|
607
1118
|
if (Object.hasOwn(map, virtual)) {
|
|
608
|
-
|
|
1119
|
+
log.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
|
|
609
1120
|
}
|
|
610
1121
|
map[virtual] = local;
|
|
611
1122
|
}
|
|
@@ -616,15 +1127,35 @@ function buildStaticMap(rawMappings: string[]): Record<string, string> {
|
|
|
616
1127
|
// Extra args parser
|
|
617
1128
|
// ---------------------------------------------------------------------------
|
|
618
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
|
+
|
|
619
1146
|
export function parseExtraArgs(extraArgs: string[]): Record<string, unknown> {
|
|
620
1147
|
const extraConfig: Record<string, unknown> = {};
|
|
621
1148
|
|
|
1149
|
+
const assign = (rawKey: string, rawValue: string | boolean): void => {
|
|
1150
|
+
extraConfig[normalizeExtraKey(rawKey)] = typeof rawValue === "boolean" ? rawValue : coerceExtraValue(rawValue);
|
|
1151
|
+
};
|
|
1152
|
+
|
|
622
1153
|
for (let i = 0; i < extraArgs.length; i++) {
|
|
623
1154
|
const arg = extraArgs[i];
|
|
624
1155
|
|
|
625
1156
|
if (!arg.startsWith("--")) {
|
|
626
1157
|
if (arg.startsWith("-")) {
|
|
627
|
-
|
|
1158
|
+
log.warn(
|
|
628
1159
|
`[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
|
|
629
1160
|
` Use the long-form --flag equivalent instead.`
|
|
630
1161
|
);
|
|
@@ -634,26 +1165,21 @@ export function parseExtraArgs(extraArgs: string[]): Record<string, unknown> {
|
|
|
634
1165
|
|
|
635
1166
|
if (arg.includes("=")) {
|
|
636
1167
|
const eqIdx = arg.indexOf("=");
|
|
637
|
-
|
|
638
|
-
const val = arg.slice(eqIdx + 1);
|
|
639
|
-
extraConfig[key] = val === "true" ? true : val === "false" ? false : val;
|
|
1168
|
+
assign(arg.slice(2, eqIdx), arg.slice(eqIdx + 1));
|
|
640
1169
|
continue;
|
|
641
1170
|
}
|
|
642
1171
|
|
|
643
1172
|
const key = arg.slice(2);
|
|
644
1173
|
const next = extraArgs[i + 1];
|
|
645
1174
|
|
|
646
|
-
if (next === "true") {
|
|
647
|
-
|
|
648
|
-
i++;
|
|
649
|
-
} else if (next === "false") {
|
|
650
|
-
extraConfig[key] = false;
|
|
1175
|
+
if (next === "true" || next === "false") {
|
|
1176
|
+
assign(key, next === "true");
|
|
651
1177
|
i++;
|
|
652
|
-
} else if (next && !next.startsWith("-")) {
|
|
653
|
-
|
|
1178
|
+
} else if (next !== undefined && !next.startsWith("-")) {
|
|
1179
|
+
assign(key, next);
|
|
654
1180
|
i++;
|
|
655
1181
|
} else {
|
|
656
|
-
extraConfig[key] = true;
|
|
1182
|
+
extraConfig[normalizeExtraKey(key)] = true;
|
|
657
1183
|
}
|
|
658
1184
|
}
|
|
659
1185
|
|
|
@@ -749,7 +1275,57 @@ function buildProgram(): Command {
|
|
|
749
1275
|
(val: string, prev: string[]) => prev.concat(val),
|
|
750
1276
|
[]
|
|
751
1277
|
)
|
|
752
|
-
.option(
|
|
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
|
+
)
|
|
753
1329
|
.option("--format <format>", `Output format: ${validFormats.join(" | ")}`, "pdf")
|
|
754
1330
|
.option("--log-level <level>", `Vivliostyle log level: ${validLogLevels.join(" | ")}`, "info")
|
|
755
1331
|
.option("--mode <mode>", `Execution mode: ${validModes.join(" | ")}`, "build")
|
|
@@ -762,18 +1338,20 @@ function buildProgram(): Command {
|
|
|
762
1338
|
"Notes:",
|
|
763
1339
|
" • HTML input (.html/.htm) is detected automatically from the file extension.",
|
|
764
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.",
|
|
765
1342
|
" • Options after -- are forwarded verbatim to Vivliostyle.",
|
|
766
1343
|
" • --debug sets --log-level to debug automatically.",
|
|
767
1344
|
" • --preview and --mode preview are equivalent.",
|
|
768
|
-
" •
|
|
769
|
-
" •
|
|
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.",
|
|
770
1348
|
" • --asset-base localBase is also a fallback root for CSS-referenced assets."
|
|
771
1349
|
].join("\n")
|
|
772
1350
|
);
|
|
773
1351
|
}
|
|
774
1352
|
|
|
775
1353
|
export function printHelp(): void {
|
|
776
|
-
buildProgram().help();
|
|
1354
|
+
buildProgram().help({ error: false });
|
|
777
1355
|
}
|
|
778
1356
|
|
|
779
1357
|
export function parseArgs(argv: string[]): {
|
|
@@ -797,31 +1375,93 @@ export function parseArgs(argv: string[]): {
|
|
|
797
1375
|
return { options: program.opts<CliOptions>(), extraArgs };
|
|
798
1376
|
}
|
|
799
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
|
+
|
|
800
1415
|
// ---------------------------------------------------------------------------
|
|
801
1416
|
// Core execute
|
|
802
1417
|
// ---------------------------------------------------------------------------
|
|
803
1418
|
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
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;
|
|
807
1439
|
|
|
808
|
-
|
|
809
|
-
|
|
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
|
+
}
|
|
1451
|
+
|
|
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);
|
|
810
1456
|
|
|
811
1457
|
if (!options.input) throw new Error("Missing required option: --input");
|
|
812
1458
|
|
|
813
1459
|
const inputAbs = resolve(options.input);
|
|
814
|
-
|
|
1460
|
+
log.trace("resolved input", inputAbs);
|
|
815
1461
|
if (!existsSync(inputAbs)) throw new Error(`Input file does not exist: ${inputAbs}`);
|
|
816
1462
|
|
|
817
|
-
const cwd = options.cwd ? resolve(options.cwd) : dirname(inputAbs);
|
|
818
|
-
if (!existsSync(cwd)) {
|
|
819
|
-
throw new Error(`Working directory does not exist: ${cwd}`);
|
|
820
|
-
}
|
|
821
|
-
dbg("cwd", cwd);
|
|
822
|
-
|
|
823
1463
|
const outputAbs = resolve(options.output);
|
|
824
|
-
|
|
1464
|
+
log.trace("resolved output", outputAbs);
|
|
825
1465
|
|
|
826
1466
|
if (!validFormats.includes(options.format as OutputFormat)) {
|
|
827
1467
|
throw new Error(`Invalid format: "${options.format}". Allowed: ${validFormats.join(", ")}`);
|
|
@@ -832,236 +1472,321 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
|
|
|
832
1472
|
throw new Error(`Invalid log level: "${options.logLevel}". Allowed: ${validLogLevels.join(", ")}`);
|
|
833
1473
|
}
|
|
834
1474
|
const logLevel: LogLevel = options.debug ? "debug" : (options.logLevel as LogLevel);
|
|
835
|
-
|
|
1475
|
+
log.trace("logLevel", logLevel);
|
|
836
1476
|
|
|
837
1477
|
const mode = (options.preview ? "preview" : options.mode) as Mode;
|
|
838
1478
|
if (!validModes.includes(mode)) {
|
|
839
1479
|
throw new Error(`Invalid mode: "${mode}". Allowed: ${validModes.join(", ")}`);
|
|
840
1480
|
}
|
|
841
|
-
|
|
1481
|
+
log.trace("mode", mode);
|
|
842
1482
|
|
|
843
1483
|
const htmlMode = isHtmlInput(inputAbs);
|
|
844
|
-
|
|
1484
|
+
log.trace("htmlMode (auto-detected)", htmlMode);
|
|
845
1485
|
|
|
846
1486
|
if (!htmlMode) {
|
|
847
1487
|
if (options.assetBase.length > 0) {
|
|
848
|
-
|
|
1488
|
+
log.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
|
|
849
1489
|
}
|
|
850
1490
|
if (options.ignoreAsset.length > 0) {
|
|
851
|
-
|
|
1491
|
+
log.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
|
|
852
1492
|
}
|
|
853
1493
|
}
|
|
854
1494
|
|
|
855
1495
|
const assetBases = options.assetBase.map(parseAssetBaseMapping);
|
|
856
|
-
|
|
1496
|
+
log.trace("parsed assetBases", assetBases);
|
|
857
1497
|
|
|
858
1498
|
const ignoredAssets = new Set(options.ignoreAsset.map(normalizeIgnoreAssetPath));
|
|
859
|
-
|
|
1499
|
+
log.trace("ignoredAssets", [...ignoredAssets]);
|
|
860
1500
|
|
|
861
1501
|
// ── HTML-derived mappings ────────────────────────────────────────────────
|
|
862
1502
|
const derivedMappings: string[] = [];
|
|
863
1503
|
|
|
864
1504
|
if (htmlMode) {
|
|
865
1505
|
const htmlDir = dirname(inputAbs);
|
|
866
|
-
|
|
1506
|
+
log.info(`[html] Analysing input as HTML: ${inputAbs}`);
|
|
867
1507
|
|
|
868
1508
|
const includeScripts = mode === "preview" ? true : options.scripts;
|
|
869
1509
|
const urls = extractUrlsFromHtml(inputAbs, includeScripts);
|
|
870
1510
|
|
|
871
1511
|
if (urls.length === 0) {
|
|
872
|
-
|
|
1512
|
+
log.info("[html] No URLs found in input HTML");
|
|
873
1513
|
} else {
|
|
874
|
-
|
|
1514
|
+
log.info(`[html] Found URLs (${urls.length}):`);
|
|
875
1515
|
}
|
|
876
1516
|
|
|
877
1517
|
for (const url of urls) {
|
|
878
|
-
const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets
|
|
1518
|
+
const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets);
|
|
879
1519
|
if (result.kind === "skipped") {
|
|
880
|
-
|
|
1520
|
+
log.info(` → Skipped (${result.reason}): ${url}`);
|
|
881
1521
|
continue;
|
|
882
1522
|
}
|
|
883
|
-
|
|
1523
|
+
log.info(` → Mapping: ${result.mapping}`);
|
|
884
1524
|
derivedMappings.push(result.mapping);
|
|
885
1525
|
}
|
|
886
1526
|
|
|
887
|
-
|
|
1527
|
+
log.trace("derived static mappings from HTML", derivedMappings);
|
|
888
1528
|
}
|
|
889
1529
|
|
|
890
1530
|
// ── static map ────────────────────────────────────────────────────────────
|
|
891
1531
|
const allStaticMappings = [...options.static, ...derivedMappings];
|
|
892
|
-
|
|
1532
|
+
log.trace("all raw static mappings", allStaticMappings);
|
|
893
1533
|
|
|
894
1534
|
const staticMap = buildStaticMap(allStaticMappings);
|
|
895
|
-
|
|
1535
|
+
log.trace("assembled staticMap", staticMap);
|
|
896
1536
|
|
|
897
|
-
|
|
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));
|
|
898
1540
|
|
|
899
1541
|
for (const [virtualPath, localPath] of Object.entries(staticMap)) {
|
|
1542
|
+
if (derivedVirtualPaths.has(virtualPath)) continue;
|
|
900
1543
|
if (!existsSync(localPath)) {
|
|
901
|
-
|
|
1544
|
+
log.warn(
|
|
902
1545
|
`[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`
|
|
903
1546
|
);
|
|
904
1547
|
}
|
|
905
1548
|
}
|
|
906
1549
|
|
|
907
1550
|
const extraConfig = parseExtraArgs(extraArgs);
|
|
908
|
-
|
|
1551
|
+
log.trace("extraConfig (parsed from -- args)", extraConfig);
|
|
909
1552
|
|
|
910
1553
|
const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
|
|
911
1554
|
|
|
912
|
-
|
|
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);
|
|
1566
|
+
|
|
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
|
+
}
|
|
913
1573
|
|
|
914
|
-
|
|
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 ───────────────────────────────────────────────────────────────
|
|
915
1595
|
if (mode === "build") {
|
|
916
|
-
|
|
917
|
-
|
|
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
|
+
});
|
|
918
1622
|
|
|
919
|
-
|
|
920
|
-
const server = await startStaticServer(staticMap, assetBases, null, dbg);
|
|
1623
|
+
const htmlResource = { cleanup: (): void => undefined };
|
|
921
1624
|
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
cwd,
|
|
931
|
-
input: vivliostyleInput,
|
|
932
|
-
output: [{ path: outputAbs, format }],
|
|
933
|
-
...metaFields,
|
|
934
|
-
logLevel,
|
|
935
|
-
...(options.debug ? { debug: true } : {}),
|
|
936
|
-
...extraConfig
|
|
937
|
-
};
|
|
938
|
-
dbg("final BuildConfig", config);
|
|
939
|
-
await build(config);
|
|
940
|
-
console.log(`✓ Document created: ${outputAbs}`);
|
|
941
|
-
} finally {
|
|
942
|
-
htmlCleanup();
|
|
943
|
-
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`);
|
|
944
1633
|
}
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
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();
|
|
960
1664
|
}
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
961
1667
|
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
const
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
} else {
|
|
978
|
-
dbg("preview: skipping assetBase mount shadowed by explicit --static", {
|
|
979
|
-
virtual,
|
|
980
|
-
local
|
|
981
|
-
});
|
|
982
|
-
}
|
|
983
|
-
}
|
|
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
|
+
});
|
|
984
1683
|
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
}
|
|
1684
|
+
await preview.close();
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
989
1687
|
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
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
|
+
};
|
|
1695
|
+
|
|
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
|
+
});
|
|
1022
1722
|
|
|
1023
|
-
|
|
1723
|
+
const prepared = buildPreviewHtml(inputAbs, assetBases, htmlOptions);
|
|
1724
|
+
entry.localPath = prepared.htmlPath;
|
|
1024
1725
|
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
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
|
+
});
|
|
1031
1734
|
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
console.error("[preview] Full error:", err);
|
|
1039
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1040
|
-
throw new Error(`preview() failed:\n${message}`);
|
|
1735
|
+
return {
|
|
1736
|
+
url,
|
|
1737
|
+
documentUrl,
|
|
1738
|
+
close: async () => {
|
|
1739
|
+
prepared.cleanup();
|
|
1740
|
+
await server.close();
|
|
1041
1741
|
}
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1042
1744
|
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
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)}`);
|
|
1046
1754
|
}
|
|
1047
1755
|
}
|
|
1048
1756
|
|
|
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
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
if (htmlOptions.css !== undefined) params.style = htmlOptions.css;
|
|
1774
|
+
if (htmlOptions.userStyle !== undefined) params.userStyle = htmlOptions.userStyle;
|
|
1775
|
+
|
|
1776
|
+
return params;
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1049
1779
|
// ---------------------------------------------------------------------------
|
|
1050
1780
|
// Direct execution
|
|
1051
1781
|
// ---------------------------------------------------------------------------
|
|
1052
1782
|
|
|
1053
|
-
let _resolvedEntry: string | null = null;
|
|
1054
|
-
try {
|
|
1055
|
-
_resolvedEntry = resolve(fileURLToPath(import.meta.url));
|
|
1056
|
-
} catch {
|
|
1057
|
-
// ESM import.meta.url not available — not a direct invocation
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
1783
|
function isDirectExecution(): boolean {
|
|
1061
1784
|
const entry = process.argv[1];
|
|
1062
|
-
if (!entry
|
|
1785
|
+
if (!entry) return false;
|
|
1063
1786
|
try {
|
|
1064
|
-
|
|
1787
|
+
const realEntry = realpathSync(entry);
|
|
1788
|
+
const realSelf = realpathSync(fileURLToPath(import.meta.url));
|
|
1789
|
+
return realEntry === realSelf;
|
|
1065
1790
|
} catch {
|
|
1066
1791
|
return false;
|
|
1067
1792
|
}
|
|
@@ -1075,11 +1800,11 @@ if (isDirectExecution()) {
|
|
|
1075
1800
|
const parsed = parseArgs(process.argv);
|
|
1076
1801
|
|
|
1077
1802
|
if (!parsed) {
|
|
1078
|
-
|
|
1079
|
-
} else {
|
|
1080
|
-
execute(parsed.options, parsed.extraArgs).catch((err) => {
|
|
1081
|
-
console.error(err instanceof Error ? err.message : err);
|
|
1082
|
-
process.exit(1);
|
|
1083
|
-
});
|
|
1803
|
+
process.exit(0);
|
|
1084
1804
|
}
|
|
1805
|
+
|
|
1806
|
+
execute(parsed.options, parsed.extraArgs).catch((err: unknown) => {
|
|
1807
|
+
log.error(err instanceof Error ? err.message : String(err));
|
|
1808
|
+
process.exit(1);
|
|
1809
|
+
});
|
|
1085
1810
|
}
|