@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
|
@@ -1,133 +1,820 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { existsSync, readFileSync, mkdtempSync, writeFileSync, rmSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve, join, dirname, posix, relative, isAbsolute, sep, basename } from 'node:path';
|
|
3
|
+
import { readFileSync, statSync, existsSync, readdirSync, mkdirSync, writeFileSync, realpathSync, mkdtempSync, rmSync } from 'node:fs';
|
|
5
4
|
import { fileURLToPath } from 'node:url';
|
|
6
|
-
import { tmpdir } from 'node:os';
|
|
7
|
-
import { lookup } from 'mime-types';
|
|
8
|
-
import express from 'express';
|
|
9
|
-
import serveStatic from 'serve-static';
|
|
5
|
+
import { platform, homedir, tmpdir } from 'node:os';
|
|
10
6
|
import { JSDOM } from 'jsdom';
|
|
7
|
+
import log from 'loglevel';
|
|
8
|
+
import { createServer } from 'node:http';
|
|
9
|
+
import { lookup } from 'mime-types';
|
|
10
|
+
import puppeteer from 'puppeteer-core';
|
|
11
|
+
import { PDFDocument } from 'pdf-lib';
|
|
12
|
+
import { createRequire } from 'node:module';
|
|
11
13
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// ---------------------------------------------------------------------------
|
|
16
|
-
// HTML input detection
|
|
17
|
-
// ---------------------------------------------------------------------------
|
|
14
|
+
// src/server.ts
|
|
15
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
16
|
+
// Licensed under the MIT License.
|
|
18
17
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
18
|
+
* The static server the renderer serves the document and its assets from.
|
|
19
|
+
*
|
|
20
|
+
* It replaces the Vite based server this package used before: everything is
|
|
21
|
+
* served by us, which is what makes the document's origin (and therefore the
|
|
22
|
+
* base URI of scripts the page runs) ours as well.
|
|
22
23
|
*/
|
|
23
|
-
|
|
24
|
-
|
|
24
|
+
/** Paths the wrapper owns inside the site it serves. */
|
|
25
|
+
const VIEWER_PAGE_NAME = "__viv-viewer.html";
|
|
26
|
+
const VIEWER_LIB_PATH = "/__viv-viewer";
|
|
27
|
+
const SETTLE_GATE_PATH = "/__viv-settle";
|
|
28
|
+
const SETTLE_READY_PATH = "/__viv-settle-ready";
|
|
29
|
+
const TRANSPARENT_GIF = Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64");
|
|
30
|
+
/** CSP that lets the Vivliostyle viewer embed the served documents. */
|
|
31
|
+
function frameAncestors() {
|
|
32
|
+
return ["'self'", "http://localhost:*", "https://localhost:*", "http://127.0.0.1:*", "https://127.0.0.1:*"].join(" ");
|
|
25
33
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
34
|
+
/** Only redirect requests that ask for a file, never bare directory URLs. */
|
|
35
|
+
function looksLikeFileRequest(urlPath) {
|
|
36
|
+
const last = urlPath.slice(urlPath.lastIndexOf("/") + 1);
|
|
37
|
+
return last !== "" && last !== "/" && last.includes(".");
|
|
38
|
+
}
|
|
39
|
+
function decodeRequestPath(req) {
|
|
40
|
+
const raw = (req.url ?? "/").split("?")[0];
|
|
41
|
+
try {
|
|
42
|
+
return decodeURIComponent(raw);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return raw;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Resolves a request path against the explicit static map, then against the
|
|
50
|
+
* asset-base roots.
|
|
51
|
+
*/
|
|
52
|
+
function resolveRequestPath(urlPath, staticMap, assetBases) {
|
|
53
|
+
// An exact entry whose file is gone (e.g. a derived mapping for an already
|
|
54
|
+
// virtual path) must not shadow a prefix mount that actually serves the file.
|
|
55
|
+
if (Object.hasOwn(staticMap, urlPath)) {
|
|
56
|
+
const localPath = resolve(staticMap[urlPath]);
|
|
57
|
+
if (existsSync(localPath))
|
|
58
|
+
return { localPath, remoteUrl: null };
|
|
59
|
+
}
|
|
60
|
+
for (const [virtual, localBase] of Object.entries(staticMap)) {
|
|
61
|
+
const prefix = virtual.endsWith("/") ? virtual : `${virtual}/`;
|
|
62
|
+
if (!urlPath.startsWith(prefix))
|
|
63
|
+
continue;
|
|
64
|
+
const localPath = resolve(localBase, urlPath.slice(prefix.length));
|
|
65
|
+
if (existsSync(localPath))
|
|
66
|
+
return { localPath, remoteUrl: null };
|
|
67
|
+
}
|
|
68
|
+
for (const ab of assetBases) {
|
|
69
|
+
const localPath = resolve(ab.localBase, urlPath.replace(/^\//, ""));
|
|
70
|
+
if (existsSync(localPath))
|
|
71
|
+
return { localPath, remoteUrl: null };
|
|
72
|
+
}
|
|
73
|
+
for (const ab of assetBases) {
|
|
74
|
+
if (!looksLikeFileRequest(urlPath))
|
|
75
|
+
continue;
|
|
76
|
+
return { localPath: null, remoteUrl: `${ab.urlBase.replace(/\/$/, "")}${urlPath}` };
|
|
77
|
+
}
|
|
78
|
+
return { localPath: null, remoteUrl: null };
|
|
79
|
+
}
|
|
80
|
+
function sendFile(res, localPath) {
|
|
81
|
+
let size;
|
|
82
|
+
try {
|
|
83
|
+
const stat = statSync(localPath);
|
|
84
|
+
if (!stat.isFile())
|
|
85
|
+
return false;
|
|
86
|
+
size = stat.size;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
const mime = lookup(localPath);
|
|
92
|
+
if (mime)
|
|
93
|
+
res.setHeader("Content-Type", mime);
|
|
94
|
+
res.setHeader("Content-Length", String(size));
|
|
95
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
96
|
+
res.setHeader("Content-Security-Policy", `frame-ancestors ${frameAncestors()}`);
|
|
97
|
+
res.statusCode = 200;
|
|
98
|
+
res.end(readFileSync(localPath));
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Serves the viewer page with its asset references made absolute, so that it
|
|
103
|
+
* can live in the document's directory without dragging its own assets along.
|
|
104
|
+
*/
|
|
105
|
+
function buildViewerPage(viewerHtml, viewerLibPath = VIEWER_LIB_PATH) {
|
|
106
|
+
return viewerHtml
|
|
107
|
+
.replace(/(src|href)="(?!https?:|data:|\/)([^"]+)"/g, (_match, attr, path) => `${attr}="${viewerLibPath}/${path}"`)
|
|
108
|
+
.replace(/<base[^>]*>/g, "");
|
|
109
|
+
}
|
|
110
|
+
async function startStaticServer(options = {}, port = 0) {
|
|
111
|
+
const staticMap = options.staticMap ?? {};
|
|
112
|
+
const assetBases = options.assetBases ?? [];
|
|
113
|
+
const fetchMissing = options.fetchMissing === true;
|
|
114
|
+
const settle = options.settle ?? null;
|
|
115
|
+
const log = options.log ?? (() => undefined);
|
|
116
|
+
let released = false;
|
|
117
|
+
let holdStartedAt = 0;
|
|
118
|
+
let deadlineTimer = null;
|
|
119
|
+
let pending = [];
|
|
120
|
+
const release = (reason, detail) => {
|
|
121
|
+
if (released)
|
|
32
122
|
return;
|
|
33
|
-
|
|
34
|
-
|
|
123
|
+
released = true;
|
|
124
|
+
if (deadlineTimer !== null)
|
|
125
|
+
clearTimeout(deadlineTimer);
|
|
126
|
+
const waitedMs = holdStartedAt === 0 ? 0 : Date.now() - holdStartedAt;
|
|
127
|
+
options.onSettled?.({ reason, waitedMs, detail });
|
|
128
|
+
const waiting = pending;
|
|
129
|
+
pending = [];
|
|
130
|
+
for (const res of waiting) {
|
|
131
|
+
if (res.headersSent || res.writableEnded)
|
|
132
|
+
continue;
|
|
133
|
+
res.statusCode = 200;
|
|
134
|
+
res.setHeader("Content-Type", "image/gif");
|
|
135
|
+
res.setHeader("Content-Length", String(TRANSPARENT_GIF.length));
|
|
136
|
+
res.end(TRANSPARENT_GIF);
|
|
35
137
|
}
|
|
36
|
-
|
|
37
|
-
|
|
138
|
+
};
|
|
139
|
+
const handleSettle = (urlPath, query, res) => {
|
|
140
|
+
if (settle === null)
|
|
141
|
+
return false;
|
|
142
|
+
if (urlPath === SETTLE_READY_PATH) {
|
|
143
|
+
const detail = {};
|
|
144
|
+
for (const key of ["reason", "ms", "pending", "frames", "canvases", "containers", "mutations", "dpr", "painted", "ready"]) {
|
|
145
|
+
const value = query.get(key);
|
|
146
|
+
if (value === null)
|
|
147
|
+
continue;
|
|
148
|
+
detail[key] = /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
|
|
149
|
+
}
|
|
150
|
+
res.statusCode = 204;
|
|
151
|
+
res.end();
|
|
152
|
+
release("settled", detail);
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
if (urlPath !== SETTLE_GATE_PATH)
|
|
156
|
+
return false;
|
|
157
|
+
if (released) {
|
|
158
|
+
release("deadline");
|
|
159
|
+
return true;
|
|
38
160
|
}
|
|
161
|
+
if (holdStartedAt === 0) {
|
|
162
|
+
holdStartedAt = Date.now();
|
|
163
|
+
deadlineTimer = setTimeout(() => release("deadline"), settle.deadlineMs);
|
|
164
|
+
deadlineTimer.unref?.();
|
|
165
|
+
}
|
|
166
|
+
pending.push(res);
|
|
167
|
+
res.on("close", () => {
|
|
168
|
+
pending = pending.filter((candidate) => candidate !== res);
|
|
169
|
+
});
|
|
170
|
+
return true;
|
|
171
|
+
};
|
|
172
|
+
const handler = (req, res) => {
|
|
173
|
+
const urlPath = decodeRequestPath(req);
|
|
174
|
+
const query = new URLSearchParams((req.url ?? "").split("?")[1] ?? "");
|
|
175
|
+
if (handleSettle(urlPath, query, res))
|
|
176
|
+
return;
|
|
177
|
+
// The viewer page lives next to the document so that scripts the page runs
|
|
178
|
+
// resolve relative URLs against the document's directory.
|
|
179
|
+
if (urlPath.endsWith(`/${VIEWER_PAGE_NAME}`)) {
|
|
180
|
+
const html = options.viewerFilePath === null || options.viewerFilePath === undefined ? "" : readFileSync(options.viewerFilePath, "utf-8");
|
|
181
|
+
if (html !== "") {
|
|
182
|
+
res.statusCode = 200;
|
|
183
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
184
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
185
|
+
res.end(buildViewerPage(html));
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (options.viewerLibDir != null && urlPath.startsWith(`${VIEWER_LIB_PATH}/`)) {
|
|
190
|
+
const relative = urlPath.slice(VIEWER_LIB_PATH.length + 1);
|
|
191
|
+
if (sendFile(res, resolve(options.viewerLibDir, relative)))
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const entry = options.entry;
|
|
195
|
+
if (entry !== null && entry !== undefined && entry.localPath !== null && urlPath === entry.sitePath) {
|
|
196
|
+
if (sendFile(res, resolve(entry.localPath)))
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const { localPath, remoteUrl } = resolveRequestPath(urlPath, staticMap, assetBases);
|
|
200
|
+
if (localPath !== null && sendFile(res, localPath))
|
|
201
|
+
return;
|
|
202
|
+
if (remoteUrl !== null && fetchMissing) {
|
|
203
|
+
log(`[fetch] ${urlPath} → ${remoteUrl}`);
|
|
204
|
+
res.statusCode = 302;
|
|
205
|
+
res.setHeader("Location", remoteUrl);
|
|
206
|
+
res.end();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
res.statusCode = 404;
|
|
210
|
+
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
211
|
+
res.end("Not found");
|
|
212
|
+
};
|
|
213
|
+
const server = createServer(handler);
|
|
214
|
+
await new Promise((resolvePromise, reject) => {
|
|
215
|
+
server.once("error", reject);
|
|
216
|
+
server.listen(port, "127.0.0.1", () => {
|
|
217
|
+
server.off("error", reject);
|
|
218
|
+
resolvePromise();
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
const address = server.address();
|
|
222
|
+
const boundPort = typeof address === "object" && address !== null ? address.port : port;
|
|
223
|
+
return {
|
|
224
|
+
baseUrl: `http://127.0.0.1:${boundPort}`,
|
|
225
|
+
close: () => new Promise((resolvePromise) => {
|
|
226
|
+
release("deadline");
|
|
227
|
+
server.closeAllConnections?.();
|
|
228
|
+
server.close(() => resolvePromise());
|
|
229
|
+
})
|
|
39
230
|
};
|
|
40
231
|
}
|
|
41
|
-
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
232
|
+
|
|
233
|
+
// src/render/chrome.ts
|
|
234
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
235
|
+
// Licensed under the MIT License.
|
|
236
|
+
/**
|
|
237
|
+
* Locates a Chrome/Chromium binary for the renderer.
|
|
238
|
+
*
|
|
239
|
+
* `--executable-browser` wins, then a binary installed by @puppeteer/browsers
|
|
240
|
+
* (the same cache Vivliostyle CLI used), then the usual system locations.
|
|
241
|
+
*/
|
|
242
|
+
const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
|
|
243
|
+
const MAC_CHROMIUM = "/Applications/Chromium.app/Contents/MacOS/Chromium";
|
|
244
|
+
const LINUX_PATHS = [
|
|
245
|
+
"/usr/bin/google-chrome",
|
|
246
|
+
"/usr/bin/google-chrome-stable",
|
|
247
|
+
"/usr/bin/chromium",
|
|
248
|
+
"/usr/bin/chromium-browser",
|
|
249
|
+
"/snap/bin/chromium"
|
|
250
|
+
];
|
|
251
|
+
/** Directory @puppeteer/browsers installs into. */
|
|
252
|
+
function puppeteerCacheDir() {
|
|
253
|
+
return process.env.PUPPETEER_CACHE_DIR ?? join(homedir(), ".cache", "puppeteer");
|
|
49
254
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
255
|
+
/** Finds an installed browser in the @puppeteer/browsers cache. */
|
|
256
|
+
function findCachedBrowser() {
|
|
257
|
+
const root = join(puppeteerCacheDir(), "chrome");
|
|
258
|
+
if (!existsSync(root))
|
|
259
|
+
return null;
|
|
260
|
+
const candidates = [];
|
|
261
|
+
for (const build of readdirSync(root)) {
|
|
262
|
+
const buildDir = join(root, build);
|
|
263
|
+
let stat;
|
|
264
|
+
try {
|
|
265
|
+
stat = statSync(buildDir);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (!stat.isDirectory())
|
|
271
|
+
continue;
|
|
272
|
+
for (const flavour of readdirSync(buildDir)) {
|
|
273
|
+
candidates.push(join(buildDir, flavour, "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join(buildDir, flavour, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join(buildDir, flavour, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join(buildDir, flavour, "chrome-linux64", "chrome"), join(buildDir, flavour, "chrome-headless-shell-linux64", "chrome-headless-shell"));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
54
277
|
}
|
|
55
|
-
function
|
|
56
|
-
|
|
57
|
-
|
|
278
|
+
function systemBrowser() {
|
|
279
|
+
const candidates = platform() === "darwin" ? [MAC_CHROME, MAC_CHROMIUM] : LINUX_PATHS;
|
|
280
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Path of the browser to launch, or `null` when none is installed.
|
|
284
|
+
*/
|
|
285
|
+
function resolveBrowserExecutable(explicit) {
|
|
286
|
+
const candidates = [explicit, process.env.CHROME_PATH, findCachedBrowser(), systemBrowser()];
|
|
287
|
+
for (const candidate of candidates) {
|
|
288
|
+
if (candidate !== undefined && candidate !== null && candidate !== "" && existsSync(candidate))
|
|
289
|
+
return candidate;
|
|
58
290
|
}
|
|
59
|
-
|
|
60
|
-
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Chrome flags for headless rendering.
|
|
295
|
+
*
|
|
296
|
+
* SwiftShader keeps WebGL (three.js, A-Frame) working without a GPU, and the
|
|
297
|
+
* ANGLE/WebGPU flags extend that to WebGPU on headless machines (best effort:
|
|
298
|
+
* pages report `navigator.gpu == null` when the build still lacks it).
|
|
299
|
+
* `--disable-web-security` lets the page load the cross-origin embeds it shows.
|
|
300
|
+
*/
|
|
301
|
+
function chromeArgs(extra = []) {
|
|
302
|
+
return [
|
|
303
|
+
"--disable-field-trial-config",
|
|
304
|
+
"--disable-back-forward-cache",
|
|
305
|
+
"--disable-component-update",
|
|
306
|
+
"--no-default-browser-check",
|
|
307
|
+
"--disable-features=AcceptCHFrame,AvoidUnnecessaryBeforeUnloadCheckSync,DestroyProfileInBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,MediaRouter,PaintHolding,ThirdPartyPartitioning,Translate,AutofillServerCommunication,DestroyProfileOnBrowserClose",
|
|
308
|
+
"--no-service-autorun",
|
|
309
|
+
"--enable-unsafe-swiftshader",
|
|
310
|
+
"--use-angle=swiftshader",
|
|
311
|
+
"--enable-unsafe-webgpu",
|
|
312
|
+
"--disable-web-security",
|
|
313
|
+
"--hide-scrollbars",
|
|
314
|
+
"--mute-audio",
|
|
315
|
+
"--force-device-scale-factor=1",
|
|
316
|
+
...extra
|
|
317
|
+
];
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/render/pdf.ts
|
|
321
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
322
|
+
// Licensed under the MIT License.
|
|
323
|
+
/**
|
|
324
|
+
* PDF rendering on top of the Vivliostyle viewer and Chrome's print-to-PDF.
|
|
325
|
+
*
|
|
326
|
+
* The viewer page is served by our own static server (see src/server.ts), so
|
|
327
|
+
* the document's origin — and therefore the base URI of the scripts the page
|
|
328
|
+
* runs — is the site we serve, not an internal viewer base.
|
|
329
|
+
*/
|
|
330
|
+
/** URL of the viewer page, with the publication and layout parameters. */
|
|
331
|
+
function buildViewerUrl(viewerPageUrl, params) {
|
|
332
|
+
const parts = [];
|
|
333
|
+
for (const [key, value] of Object.entries(params)) {
|
|
334
|
+
if (value === undefined || value === "")
|
|
335
|
+
continue;
|
|
336
|
+
parts.push(`${key}=${String(value).replaceAll("&", "%26")}`);
|
|
61
337
|
}
|
|
338
|
+
const query = parts.join("&");
|
|
339
|
+
return query === "" ? viewerPageUrl : `${viewerPageUrl}#${query}`;
|
|
62
340
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
341
|
+
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
342
|
+
/** Writes the PDF and stamps the metadata Vivliostyle would have written. */
|
|
343
|
+
async function writePdfWithMetadata(pdf, meta) {
|
|
344
|
+
const hasMetadata = meta.title !== undefined || meta.author !== undefined || meta.subject !== undefined || meta.language !== undefined;
|
|
345
|
+
if (!hasMetadata)
|
|
346
|
+
return pdf;
|
|
347
|
+
const document = await PDFDocument.load(pdf, { updateMetadata: false });
|
|
348
|
+
if (meta.title !== undefined)
|
|
349
|
+
document.setTitle(meta.title);
|
|
350
|
+
if (meta.author !== undefined)
|
|
351
|
+
document.setAuthor(meta.author);
|
|
352
|
+
if (meta.subject !== undefined)
|
|
353
|
+
document.setSubject(meta.subject);
|
|
354
|
+
if (meta.keywords !== undefined)
|
|
355
|
+
document.setKeywords([meta.keywords]);
|
|
356
|
+
if (meta.language !== undefined)
|
|
357
|
+
document.setLanguage(meta.language);
|
|
358
|
+
document.setProducer("vivliostyle-batch-cli");
|
|
359
|
+
document.setCreator("vivliostyle-batch-cli");
|
|
360
|
+
return document.save();
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Runs inside one frame (viewer window or a document/iframe within it):
|
|
364
|
+
* scrolls JS-painted elements into view so out-of-process iframes rasterize,
|
|
365
|
+
* reports GPU capabilities and canvas sizes, and — when the page exposes the
|
|
366
|
+
* `window.__vivResize(factor)` hook — redraws at HiDPI backing resolution.
|
|
367
|
+
*
|
|
368
|
+
* Blindly rewriting `canvas.width` here would blank WebGL contexts without
|
|
369
|
+
* `preserveDrawingBuffer`, so generic canvases are left for the page to redraw
|
|
370
|
+
* via the dispatched `resize` event; only the explicit hook changes pixels.
|
|
371
|
+
*/
|
|
372
|
+
function buildFrameProbeScript(factor) {
|
|
373
|
+
return `(async function(factor){
|
|
374
|
+
function nextFrame(){ return new Promise(function(r){ requestAnimationFrame(function(){ requestAnimationFrame(r); }); }); }
|
|
375
|
+
var canvases = Array.prototype.slice.call(document.querySelectorAll("canvas"));
|
|
376
|
+
var iframes = Array.prototype.slice.call(document.querySelectorAll("iframe"));
|
|
377
|
+
canvases.forEach(function(c){ try{ c.scrollIntoView({block:"nearest"}); }catch(e){} });
|
|
378
|
+
iframes.forEach(function(f){ try{ f.scrollIntoView({block:"nearest"}); }catch(e){} });
|
|
379
|
+
function canvasSizes(){
|
|
380
|
+
return Array.prototype.slice.call(document.querySelectorAll("canvas")).map(function(c){
|
|
381
|
+
return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);
|
|
382
|
+
}).join(",");
|
|
383
|
+
}
|
|
384
|
+
var resized = null;
|
|
385
|
+
if (factor > 1 && typeof window.__vivResize === "function") {
|
|
386
|
+
try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
|
|
387
|
+
}
|
|
388
|
+
try { window.dispatchEvent(new Event("resize")); } catch(e){}
|
|
389
|
+
// Hooks like echarts re-init dispose the canvas synchronously; let layout
|
|
390
|
+
// settle a frame before measuring so sizes reflect the repainted state.
|
|
391
|
+
try { await nextFrame(); } catch(e){}
|
|
392
|
+
if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
|
|
393
|
+
var webgl = false, webgl2 = false;
|
|
394
|
+
try {
|
|
395
|
+
var t = document.createElement("canvas");
|
|
396
|
+
webgl = !!t.getContext("webgl");
|
|
397
|
+
var t2 = document.createElement("canvas");
|
|
398
|
+
webgl2 = !!t2.getContext("webgl2");
|
|
399
|
+
} catch(e){}
|
|
400
|
+
return {
|
|
401
|
+
url: String(location.href),
|
|
402
|
+
ready: window.__vivReady === true,
|
|
403
|
+
fixture: typeof window.__vivFixture === "string" ? window.__vivFixture : null,
|
|
404
|
+
webgl: webgl, webgl2: webgl2,
|
|
405
|
+
webgpu: typeof navigator !== "undefined" && "gpu" in navigator,
|
|
406
|
+
canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
|
|
407
|
+
iframeCount: document.querySelectorAll("iframe").length,
|
|
408
|
+
dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
|
|
409
|
+
resized: resized
|
|
410
|
+
};
|
|
411
|
+
})(${JSON.stringify(factor)})`;
|
|
412
|
+
}
|
|
413
|
+
/** Best-effort capability + HiDPI pass over every frame before `page.pdf()`. */
|
|
414
|
+
async function prepareForPrint(page, options = {}) {
|
|
415
|
+
const factor = options.settleMs !== undefined && options.canvasScale === undefined ? 1 : (options.canvasScale ?? 1);
|
|
416
|
+
const scale = Number.isFinite(factor) && factor > 1 ? factor : 1;
|
|
417
|
+
const script = buildFrameProbeScript(scale);
|
|
418
|
+
const out = [];
|
|
419
|
+
for (const frame of page.frames()) {
|
|
420
|
+
try {
|
|
421
|
+
out.push((await frame.evaluate(script)));
|
|
75
422
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
console.log(`[static-server] Dir mount: ${mountPath} → ${absLocal}`);
|
|
423
|
+
catch {
|
|
424
|
+
// Cross-origin embeds that refuse evaluation still print as pixels.
|
|
425
|
+
continue;
|
|
80
426
|
}
|
|
81
|
-
dbg("[static-server] mount", { virtual, absLocal });
|
|
82
427
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
428
|
+
if (scale > 1) {
|
|
429
|
+
await new Promise((resolve) => setTimeout(resolve, options.settleMs ?? 500));
|
|
430
|
+
}
|
|
431
|
+
return out;
|
|
432
|
+
}
|
|
433
|
+
/** One-line summary for logs: capabilities per frame that owns content. */
|
|
434
|
+
function summarizeCapabilities(caps) {
|
|
435
|
+
return caps
|
|
436
|
+
.filter((c) => c.canvasCount > 0 || c.iframeCount > 0 || c.fixture !== null)
|
|
437
|
+
.map((c) => `${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
|
|
438
|
+
`webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
|
|
439
|
+
(c.resized !== null ? ` resized=[${c.resized}]` : ""))
|
|
440
|
+
.join(" | ");
|
|
441
|
+
}
|
|
442
|
+
async function renderPdf(request) {
|
|
443
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
444
|
+
const executablePath = resolveBrowserExecutable(request.chromeExecutable);
|
|
445
|
+
if (executablePath === null) {
|
|
446
|
+
throw new Error("No Chrome/Chromium found. Install one (e.g. `npx @puppeteer/browsers install chrome@stable`) or pass --executable-browser <path>.");
|
|
100
447
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
448
|
+
const viewerUrl = buildViewerUrl(request.viewerPageUrl, {
|
|
449
|
+
src: request.documentUrl,
|
|
450
|
+
bookMode: false,
|
|
451
|
+
renderAllPages: true,
|
|
452
|
+
...request.viewerParams
|
|
105
453
|
});
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
dbg("[static-server] assetBase roots", assetBases.map((ab) => ab.localBase));
|
|
113
|
-
let closed = false;
|
|
114
|
-
const close = () => {
|
|
115
|
-
if (closed)
|
|
116
|
-
return;
|
|
117
|
-
closed = true;
|
|
118
|
-
httpServer.close((err) => {
|
|
119
|
-
if (err)
|
|
120
|
-
console.warn(`[static-server] close error: ${err.message}`);
|
|
121
|
-
else
|
|
122
|
-
dbg("[static-server] stopped");
|
|
123
|
-
});
|
|
124
|
-
};
|
|
125
|
-
resolvePromise({ baseUrl, close });
|
|
126
|
-
});
|
|
127
|
-
httpServer.once("error", reject);
|
|
454
|
+
log.trace("viewerUrl", viewerUrl);
|
|
455
|
+
const browser = await puppeteer.launch({
|
|
456
|
+
executablePath,
|
|
457
|
+
headless: true,
|
|
458
|
+
args: chromeArgs(request.extraChromeArgs ?? []),
|
|
459
|
+
acceptInsecureCerts: true
|
|
128
460
|
});
|
|
461
|
+
const startedAt = Date.now();
|
|
462
|
+
let settle = null;
|
|
463
|
+
try {
|
|
464
|
+
const page = await browser.newPage();
|
|
465
|
+
page.setDefaultTimeout(timeoutMs);
|
|
466
|
+
page.setDefaultNavigationTimeout(timeoutMs);
|
|
467
|
+
page.on("pageerror", (err) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
|
|
468
|
+
// Viewer and page errors are the usual reason a render produces nothing.
|
|
469
|
+
page.on("console", (message) => {
|
|
470
|
+
const type = message.type();
|
|
471
|
+
if (type !== "error" && type !== "warn")
|
|
472
|
+
return;
|
|
473
|
+
const where = message.location();
|
|
474
|
+
log.warn(`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`);
|
|
475
|
+
});
|
|
476
|
+
page.on("requestfailed", (request) => {
|
|
477
|
+
log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
|
|
478
|
+
});
|
|
479
|
+
// Print media has to be active *before* the document loads: the page's print
|
|
480
|
+
// stylesheet is what gives JS-driven containers their size, and a chart that
|
|
481
|
+
// initialises against a zero-sized box never recovers.
|
|
482
|
+
await page.emulateMediaType("print");
|
|
483
|
+
await page.goto(viewerUrl, { waitUntil: "domcontentloaded" });
|
|
484
|
+
// The viewer's contract: coreViewer exists and has finished typesetting.
|
|
485
|
+
await page.waitForFunction(() => window.coreViewer !== undefined);
|
|
486
|
+
await page.waitForFunction(() => window.coreViewer?.readyState === "complete", {
|
|
487
|
+
polling: 500
|
|
488
|
+
});
|
|
489
|
+
if (request.waitForSettle === true) {
|
|
490
|
+
const handle = await page.waitForFunction(() => {
|
|
491
|
+
const settleState = window.__vivSettle;
|
|
492
|
+
// Pages with mocked/measured async work set __vivReady when painted;
|
|
493
|
+
// Vivliostyle re-runs document scripts in the viewer context, so both
|
|
494
|
+
// live on the same window the renderer polls here.
|
|
495
|
+
const ready = window.__vivReady === true;
|
|
496
|
+
if (ready)
|
|
497
|
+
return { reason: "ready", at: 0 };
|
|
498
|
+
return settleState?.done === true ? { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 } : false;
|
|
499
|
+
}, { polling: 200, timeout: timeoutMs });
|
|
500
|
+
const state = (await handle.jsonValue());
|
|
501
|
+
settle = { reason: state.reason, waitedMs: Date.now() - startedAt };
|
|
502
|
+
log.trace("settle", settle);
|
|
503
|
+
}
|
|
504
|
+
// Iframes/canvas/WebGL/WebGPU rasterize as pixels in print-to-PDF: force
|
|
505
|
+
// off-screen frames to paint, redraw HiDPI-aware pages at backing scale.
|
|
506
|
+
try {
|
|
507
|
+
const caps = await prepareForPrint(page, {
|
|
508
|
+
canvasScale: request.canvasScale,
|
|
509
|
+
settleMs: request.canvasSettleMs
|
|
510
|
+
});
|
|
511
|
+
const summary = summarizeCapabilities(caps);
|
|
512
|
+
if (summary !== "")
|
|
513
|
+
log.info(`[render] frames: ${summary}`);
|
|
514
|
+
if (caps.length > 0 && caps.every((c) => !c.webgpu)) {
|
|
515
|
+
log.trace("[render] WebGPU unavailable in this Chrome (best-effort software rendering)");
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
catch (err) {
|
|
519
|
+
log.warn(`[render] pre-print probe failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
|
|
520
|
+
}
|
|
521
|
+
const pdf = await page.pdf({
|
|
522
|
+
margin: { top: 0, bottom: 0, left: 0, right: 0 },
|
|
523
|
+
printBackground: true,
|
|
524
|
+
preferCSSPageSize: true,
|
|
525
|
+
tagged: true
|
|
526
|
+
});
|
|
527
|
+
const stamped = await writePdfWithMetadata(pdf, request);
|
|
528
|
+
mkdirSync(dirname(request.output), { recursive: true });
|
|
529
|
+
writeFileSync(request.output, stamped);
|
|
530
|
+
const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
|
|
531
|
+
return { output: request.output, bytes: stamped.length, pageCount, settle };
|
|
532
|
+
}
|
|
533
|
+
finally {
|
|
534
|
+
await browser.close();
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/render/viewer.ts
|
|
539
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
540
|
+
// Licensed under the MIT License.
|
|
541
|
+
/**
|
|
542
|
+
* Locates the Vivliostyle viewer that renders the document.
|
|
543
|
+
*
|
|
544
|
+
* The viewer is served by our own static server (see src/server.ts) so that the
|
|
545
|
+
* document's origin — and with it the base URI of the scripts the page runs — is
|
|
546
|
+
* the site we serve.
|
|
547
|
+
*/
|
|
548
|
+
const require$1 = createRequire(import.meta.url);
|
|
549
|
+
/** Directory of `@vivliostyle/viewer/lib`, which holds index.html and assets. */
|
|
550
|
+
function resolveViewerLibDir() {
|
|
551
|
+
const candidates = [];
|
|
552
|
+
try {
|
|
553
|
+
candidates.push(dirname(require$1.resolve("@vivliostyle/viewer/package.json")));
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
// fall through to the paths below
|
|
557
|
+
}
|
|
558
|
+
candidates.push(resolve(dirname(fileURLOfSelf()), "../node_modules/@vivliostyle/viewer"), "/usr/local/lib/node_modules/@vivliostyle/viewer", "/usr/lib/node_modules/@vivliostyle/viewer");
|
|
559
|
+
for (const candidate of candidates) {
|
|
560
|
+
const libDir = join(candidate, "lib");
|
|
561
|
+
if (existsSync(join(libDir, "index.html")))
|
|
562
|
+
return libDir;
|
|
563
|
+
}
|
|
564
|
+
throw new Error("Could not find @vivliostyle/viewer. Install it as a dependency of this package.");
|
|
565
|
+
}
|
|
566
|
+
function fileURLOfSelf() {
|
|
567
|
+
return new URL(import.meta.url).pathname;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// src/vivliostyle-cli.ts
|
|
571
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
572
|
+
// Licensed under the MIT License.
|
|
573
|
+
const validFormats = ["pdf"];
|
|
574
|
+
const validLogLevels = ["silent", "info", "verbose", "debug"];
|
|
575
|
+
const validModes = ["build", "preview"];
|
|
576
|
+
/**
|
|
577
|
+
* Wrapper log levels mapped onto loglevel. Diagnostics are written to the trace
|
|
578
|
+
* channel, so `--log-level verbose` stays quiet while `debug` shows them.
|
|
579
|
+
*/
|
|
580
|
+
const LOG_LEVELS = {
|
|
581
|
+
silent: log.levels.SILENT,
|
|
582
|
+
info: log.levels.INFO,
|
|
583
|
+
verbose: log.levels.DEBUG,
|
|
584
|
+
debug: log.levels.TRACE
|
|
585
|
+
};
|
|
586
|
+
/**
|
|
587
|
+
* Send every level to the console channel the CLI contract uses: progress to
|
|
588
|
+
* stdout, diagnostics and problems to stderr. The method is resolved per call so
|
|
589
|
+
* that patched consoles stay visible.
|
|
590
|
+
*/
|
|
591
|
+
const CONSOLE_CHANNEL = {
|
|
592
|
+
trace: "error",
|
|
593
|
+
debug: "error",
|
|
594
|
+
info: "log",
|
|
595
|
+
warn: "warn",
|
|
596
|
+
error: "error"
|
|
597
|
+
};
|
|
598
|
+
log.methodFactory =
|
|
599
|
+
(methodName) => (...args) => {
|
|
600
|
+
console[CONSOLE_CHANNEL[methodName] ?? "log"](...args);
|
|
601
|
+
};
|
|
602
|
+
// ---------------------------------------------------------------------------
|
|
603
|
+
// Site path + settle gate helpers
|
|
604
|
+
// ---------------------------------------------------------------------------
|
|
605
|
+
/** Directory part of a site path, without a trailing slash (`""` for the root). */
|
|
606
|
+
function siteDirectory(sitePath) {
|
|
607
|
+
const dir = posix.dirname(sitePath);
|
|
608
|
+
return dir === "/" ? "" : dir;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Path the document has on the mapped site, e.g. `/post/tag-pairs/article.html`
|
|
612
|
+
* for `<localBase>/post/tag-pairs/article.html`. Used as the URL Vivliostyle
|
|
613
|
+
* loads, so page-relative and root-relative references resolve like they do on
|
|
614
|
+
* the real site.
|
|
615
|
+
*/
|
|
616
|
+
function deriveSitePath(inputAbs, assetBases) {
|
|
617
|
+
for (const ab of assetBases) {
|
|
618
|
+
const relativePath = relative(resolve(ab.localBase), resolve(inputAbs));
|
|
619
|
+
if (relativePath === "" || relativePath.startsWith("..") || isAbsolute(relativePath))
|
|
620
|
+
continue;
|
|
621
|
+
return `/${relativePath.split(sep).join("/")}`;
|
|
622
|
+
}
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Opens every `<details>` element, now and for any the page adds later.
|
|
627
|
+
*
|
|
628
|
+
* Print output has to contain the collapsed content too, and the page's own
|
|
629
|
+
* print script cannot do it: Vivliostyle re-dispatches `DOMContentLoaded` on
|
|
630
|
+
* the window rather than on the document, so a `document`-level listener never
|
|
631
|
+
* runs.
|
|
632
|
+
*/
|
|
633
|
+
const EXPAND_DETAILS_SNIPPET = `function expandDetails(root){
|
|
634
|
+
var open=function(el){
|
|
635
|
+
if(el.tagName!=="DETAILS"||el.open)return;
|
|
636
|
+
el.open=true;
|
|
637
|
+
el.setAttribute("data-viv-details-expanded","");
|
|
638
|
+
};
|
|
639
|
+
if(root.nodeType!==1)return;
|
|
640
|
+
[].forEach.call(root.querySelectorAll("details"),open);
|
|
641
|
+
open(root);
|
|
642
|
+
}
|
|
643
|
+
expandDetails(document);
|
|
644
|
+
try{new MutationObserver(function(records){
|
|
645
|
+
for(var i=0;i<records.length;i++){
|
|
646
|
+
var added=records[i].addedNodes;
|
|
647
|
+
for(var j=0;j<added.length;j++)expandDetails(added[j]);
|
|
648
|
+
}
|
|
649
|
+
}).observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
|
|
650
|
+
`;
|
|
651
|
+
/** Gate image Vivliostyle waits for before it paginates. */
|
|
652
|
+
function buildSettleGateImage(origin) {
|
|
653
|
+
// Out of flow and invisible, but rendered: Vivliostyle only loads resources of
|
|
654
|
+
// elements that end up in the render tree, so `display:none` would be skipped.
|
|
655
|
+
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>`;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* The script injected into the document: it routes the URLs that page scripts
|
|
659
|
+
* create to our server and tracks whether the page has finished.
|
|
660
|
+
*
|
|
661
|
+
* Everything lives in one scope on purpose — the settle tracker wraps the same
|
|
662
|
+
* `fetch`/XHR that the routing patches.
|
|
663
|
+
*/
|
|
664
|
+
function buildRuntimeScript(options) {
|
|
665
|
+
const { origin, documentBaseUrl, gate } = options;
|
|
666
|
+
const expandDetails = options.expandDetails === true ? EXPAND_DETAILS_SNIPPET : "";
|
|
667
|
+
// Vivliostyle paginates incrementally, so collapsed content has to be opened
|
|
668
|
+
// again while it lays the document out, not just once up front.
|
|
669
|
+
const expandDetailsTick = options.expandDetails === true ? "expandDetails(document);" : "";
|
|
670
|
+
return `(function(){
|
|
671
|
+
var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
|
|
672
|
+
var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
|
|
673
|
+
var pending=0,frames=0,last=0,mutations=0,done=false;
|
|
674
|
+
var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
|
|
675
|
+
|
|
676
|
+
// Root-relative URLs resolve against the site root, document-relative ones
|
|
677
|
+
// against the directory the page has on the site (e.g. model/x.glb next to it).
|
|
678
|
+
function fix(u){
|
|
679
|
+
if(typeof u!=="string"||u==="")return u;
|
|
680
|
+
if(u.slice(0,2)==="//"||u.charAt(0)==="#"||u.charAt(0)==="?")return u;
|
|
681
|
+
if(/^[a-z][a-z0-9+.-]*:/i.test(u))return u;
|
|
682
|
+
return u.charAt(0)==="/"?ORIGIN+u:BASE+u;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function canvases(){
|
|
686
|
+
try{return[].map.call(document.querySelectorAll("canvas"),function(c){
|
|
687
|
+
return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);}).join(",");}catch(e){return"";}
|
|
688
|
+
}
|
|
689
|
+
// Canvases with real backing pixels and layout size: the minimum for charts,
|
|
690
|
+
// three.js, maps and OSD tiles to survive print-to-PDF as sharp raster.
|
|
691
|
+
function paintedCanvases(){
|
|
692
|
+
try{return[].filter.call(document.querySelectorAll("canvas"),function(c){
|
|
693
|
+
return c.width>2&&c.height>2&&c.clientWidth>0&&c.clientHeight>0;}).length;}catch(e){return 0;}
|
|
694
|
+
}
|
|
695
|
+
// Sizes of the containers pages fill at runtime; zero means the layout has not
|
|
696
|
+
// happened yet, which is what breaks canvas and chart initialisation.
|
|
697
|
+
function containers(){
|
|
698
|
+
try{return[].map.call(document.querySelectorAll(".script,[class*=script]"),function(el){
|
|
699
|
+
return (el.id||el.className)+"@"+Math.round(el.clientWidth)+"x"+Math.round(el.clientHeight);}).join(",");}catch(e){return"";}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function signal(why){
|
|
703
|
+
if(done)return;done=true;
|
|
704
|
+
var at=Math.round(performance.now());
|
|
705
|
+
state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
|
|
706
|
+
var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
|
|
707
|
+
"&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&dpr="+window.devicePixelRatio+
|
|
708
|
+
"&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
|
|
709
|
+
"&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
|
|
710
|
+
try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// An embed that never fires load must not hold the layout open forever.
|
|
714
|
+
function watchFrame(frame){
|
|
715
|
+
if(frame.__vivWatched)return;frame.__vivWatched=true;frames++;
|
|
716
|
+
var settled=false;
|
|
717
|
+
function finish(){if(settled)return;settled=true;frames--;last=performance.now();}
|
|
718
|
+
frame.addEventListener("load",finish);
|
|
719
|
+
frame.addEventListener("error",finish);
|
|
720
|
+
try{ if(frame.contentDocument&&frame.contentDocument.readyState==="complete"){finish();return;} }catch(e){}
|
|
721
|
+
setTimeout(finish,FRAME_GRACE);
|
|
722
|
+
}
|
|
723
|
+
function watchFrames(root){
|
|
724
|
+
try{
|
|
725
|
+
[].forEach.call(root.querySelectorAll("iframe"),watchFrame);
|
|
726
|
+
if(root.tagName==="IFRAME")watchFrame(root);
|
|
727
|
+
}catch(e){}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
var of=window.fetch;
|
|
731
|
+
if(of){window.fetch=function(input,init){
|
|
732
|
+
try{
|
|
733
|
+
if(typeof input==="string")input=fix(input);
|
|
734
|
+
else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
|
|
735
|
+
}catch(e){}
|
|
736
|
+
pending++;last=performance.now();
|
|
737
|
+
return of.call(this,input,init).then(function(v){pending--;last=performance.now();return v;},
|
|
738
|
+
function(e){pending--;last=performance.now();throw e;});};}
|
|
739
|
+
var XHR=window.XMLHttpRequest;
|
|
740
|
+
if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
|
|
741
|
+
XHR.prototype.open=function(m,u){this.__vscounted=true;return open.apply(this,arguments);};
|
|
742
|
+
XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
|
|
743
|
+
this.addEventListener("loadend",function(){pending--;last=performance.now();});}
|
|
744
|
+
return send.apply(this,arguments);};}
|
|
745
|
+
["Image","Audio"].forEach(function(n){
|
|
746
|
+
var Orig=window[n];if(!Orig)return;
|
|
747
|
+
var Wrapped=function(u){return new Orig(fix(u));};
|
|
748
|
+
Wrapped.prototype=Orig.prototype;
|
|
749
|
+
try{window[n]=Wrapped;}catch(e){}
|
|
750
|
+
});
|
|
751
|
+
["HTMLImageElement","HTMLIFrameElement","HTMLScriptElement","HTMLSourceElement","HTMLVideoElement","HTMLAudioElement"].forEach(function(n){
|
|
752
|
+
var C=window[n];if(!C)return;
|
|
753
|
+
var d=Object.getOwnPropertyDescriptor(C.prototype,"src");
|
|
754
|
+
if(!d||!d.set)return;
|
|
755
|
+
try{Object.defineProperty(C.prototype,"src",{configurable:true,enumerable:d.enumerable,get:d.get,
|
|
756
|
+
set:function(v){d.set.call(this,fix(v));if(n==="HTMLIFrameElement")watchFrame(this);}});}catch(e){}
|
|
757
|
+
});
|
|
758
|
+
try{Object.defineProperty(document,"baseURI",{configurable:true,get:function(){return BASE;}});}catch(e){}
|
|
759
|
+
try{new MutationObserver(function(){mutations++;watchFrames(document.documentElement);last=performance.now();})
|
|
760
|
+
.observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
|
|
761
|
+
try{new ResizeObserver(function(){last=performance.now();}).observe(document.documentElement);}catch(e){}
|
|
762
|
+
${expandDetails}watchFrames(document.documentElement);
|
|
763
|
+
last=performance.now();
|
|
764
|
+
(function check(){
|
|
765
|
+
if(done)return;
|
|
766
|
+
${expandDetailsTick}
|
|
767
|
+
var now=performance.now();
|
|
768
|
+
if(now>=DEADLINE){signal("deadline");return;}
|
|
769
|
+
// Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
|
|
770
|
+
// painted instead of making the gate guess from network quietness. Shader
|
|
771
|
+
// compile and tile decode finish after the last fetch, so readiness wins.
|
|
772
|
+
if(window.__vivReady===true&&pending===0&&frames===0){signal("ready");return;}
|
|
773
|
+
if(pending===0&&frames===0&&now-last>=QUIET){signal("quiet");return;}
|
|
774
|
+
setTimeout(check,50);
|
|
775
|
+
})();
|
|
776
|
+
})();`;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Injects the runtime script as the first thing in `<head>` (so it wraps `fetch`
|
|
780
|
+
* before any page script runs) and the gate image at the end of `<body>`.
|
|
781
|
+
*/
|
|
782
|
+
function injectRuntimeScriptInDom(document, options) {
|
|
783
|
+
const head = document.head;
|
|
784
|
+
const anchor = head.firstChild;
|
|
785
|
+
const base = document.createElement("base");
|
|
786
|
+
base.setAttribute("href", options.documentBaseUrl);
|
|
787
|
+
head.insertBefore(base, anchor);
|
|
788
|
+
const script = document.createElement("script");
|
|
789
|
+
script.textContent = buildRuntimeScript(options);
|
|
790
|
+
head.insertBefore(script, anchor);
|
|
791
|
+
if (options.gate === null)
|
|
792
|
+
return;
|
|
793
|
+
document.body?.insertAdjacentHTML("beforeend", buildSettleGateImage(options.origin));
|
|
794
|
+
}
|
|
795
|
+
// ---------------------------------------------------------------------------
|
|
796
|
+
// HTML input detection
|
|
797
|
+
// ---------------------------------------------------------------------------
|
|
798
|
+
function isHtmlInput(inputAbs) {
|
|
799
|
+
return /\.html?$/i.test(inputAbs);
|
|
800
|
+
}
|
|
801
|
+
// ---------------------------------------------------------------------------
|
|
802
|
+
// Arg splitting
|
|
803
|
+
// ---------------------------------------------------------------------------
|
|
804
|
+
function splitArgsAtDoubleDash(argv) {
|
|
805
|
+
const dd = argv.indexOf("--");
|
|
806
|
+
if (dd === -1)
|
|
807
|
+
return { cliArgv: argv, extraArgs: [] };
|
|
808
|
+
return { cliArgv: argv.slice(0, dd), extraArgs: argv.slice(dd + 1) };
|
|
129
809
|
}
|
|
130
810
|
// ---------------------------------------------------------------------------
|
|
811
|
+
// Static mappings
|
|
812
|
+
// ---------------------------------------------------------------------------
|
|
813
|
+
/**
|
|
814
|
+
* Serve a single local file directly, bypassing Vite's transform pipeline.
|
|
815
|
+
* Returns true if the file was served, false if it should fall through.
|
|
816
|
+
*/
|
|
817
|
+
// ---------------------------------------------------------------------------
|
|
131
818
|
// DOM-level rewriters
|
|
132
819
|
// ---------------------------------------------------------------------------
|
|
133
820
|
const URL_ATTR_SELECTORS = [
|
|
@@ -140,39 +827,334 @@ const URL_ATTR_SELECTORS = [
|
|
|
140
827
|
["video[poster]", "poster"],
|
|
141
828
|
["input[src]", "src"]
|
|
142
829
|
];
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
830
|
+
/**
|
|
831
|
+
* Subresource attributes that would trigger a network request. Hyperlink
|
|
832
|
+
* attributes (`<a href>`) are deliberately absent: a link is not fetched.
|
|
833
|
+
*/
|
|
834
|
+
const SUBRESOURCE_ATTR_SELECTORS = [
|
|
835
|
+
...URL_ATTR_SELECTORS,
|
|
836
|
+
["img[srcset]", "srcset"],
|
|
837
|
+
["source[srcset]", "srcset"],
|
|
838
|
+
["iframe[src]", "src"],
|
|
839
|
+
["object[data]", "data"],
|
|
840
|
+
["embed[src]", "src"],
|
|
841
|
+
// A-Frame keeps its assets in custom elements
|
|
842
|
+
["a-asset-item[src]", "src"]
|
|
843
|
+
];
|
|
844
|
+
/** URL schemes that never leave the document. */
|
|
845
|
+
const INLINE_URL_SCHEME_RE = /^(?:data|blob|about|javascript|mailto|tel):/i;
|
|
846
|
+
/**
|
|
847
|
+
* Applies `transform` to every URL of every subresource attribute.
|
|
848
|
+
*
|
|
849
|
+
* A `srcset` candidate list is transformed candidate by candidate, keeping the
|
|
850
|
+
* descriptors (`1x`, `480w`). Returning `null` drops the candidate; an attribute
|
|
851
|
+
* without any remaining candidate is removed.
|
|
852
|
+
*/
|
|
853
|
+
function rewriteUrlAttributes(document, transform) {
|
|
146
854
|
let changed = false;
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
855
|
+
const apply = (el, attr) => {
|
|
856
|
+
const raw = el.getAttribute(attr);
|
|
857
|
+
if (raw === null)
|
|
858
|
+
return;
|
|
859
|
+
if (attr !== "srcset") {
|
|
860
|
+
const current = raw.trim();
|
|
861
|
+
const next = transform(current);
|
|
862
|
+
if (next === null) {
|
|
863
|
+
el.removeAttribute(attr);
|
|
153
864
|
changed = true;
|
|
865
|
+
return;
|
|
154
866
|
}
|
|
867
|
+
if (next === current)
|
|
868
|
+
return;
|
|
869
|
+
el.setAttribute(attr, next);
|
|
870
|
+
changed = true;
|
|
871
|
+
return;
|
|
155
872
|
}
|
|
873
|
+
const candidates = raw
|
|
874
|
+
.split(",")
|
|
875
|
+
.map((candidate) => candidate.trim())
|
|
876
|
+
.filter(Boolean);
|
|
877
|
+
const kept = [];
|
|
878
|
+
let touched = false;
|
|
879
|
+
for (const candidate of candidates) {
|
|
880
|
+
const [url, ...descriptor] = candidate.split(/\s+/);
|
|
881
|
+
const next = transform(url);
|
|
882
|
+
if (next === null) {
|
|
883
|
+
touched = true;
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
if (next !== url)
|
|
887
|
+
touched = true;
|
|
888
|
+
kept.push([next, ...descriptor].join(" "));
|
|
889
|
+
}
|
|
890
|
+
if (!touched)
|
|
891
|
+
return;
|
|
892
|
+
changed = true;
|
|
893
|
+
if (kept.length === 0)
|
|
894
|
+
el.removeAttribute(attr);
|
|
895
|
+
else
|
|
896
|
+
el.setAttribute(attr, kept.join(", "));
|
|
897
|
+
};
|
|
898
|
+
for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
|
|
899
|
+
for (const el of document.querySelectorAll(selector))
|
|
900
|
+
apply(el, attr);
|
|
156
901
|
}
|
|
157
902
|
return changed;
|
|
158
903
|
}
|
|
159
|
-
|
|
160
|
-
|
|
904
|
+
/**
|
|
905
|
+
* True when the browser would have to fetch the URL over the network.
|
|
906
|
+
*/
|
|
907
|
+
function isRemoteUrl(value) {
|
|
908
|
+
const trimmed = value.trim();
|
|
909
|
+
if (!trimmed)
|
|
910
|
+
return false;
|
|
911
|
+
if (trimmed.startsWith("//"))
|
|
912
|
+
return true;
|
|
913
|
+
return /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !INLINE_URL_SCHEME_RE.test(trimmed);
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Drops subresource references that are not available locally so nothing is
|
|
917
|
+
* fetched from the web. `srcset` candidates are filtered individually; an
|
|
918
|
+
* attribute whose candidates are all remote is removed entirely.
|
|
919
|
+
*
|
|
920
|
+
* `isAllowed` exempts URLs that are served by the wrapper itself, e.g. the
|
|
921
|
+
* static server URLs produced by the virtual-path rewrite.
|
|
922
|
+
*
|
|
923
|
+
* Returns every dropped URL.
|
|
924
|
+
*/
|
|
925
|
+
function dropRemoteReferencesInDom(document, isAllowed = () => false) {
|
|
926
|
+
const dropped = [];
|
|
927
|
+
const droppedSet = new Set();
|
|
928
|
+
rewriteUrlAttributes(document, (url) => {
|
|
929
|
+
if (isAllowed(url) || !isRemoteUrl(url))
|
|
930
|
+
return url;
|
|
931
|
+
droppedSet.add(url);
|
|
932
|
+
return null;
|
|
933
|
+
});
|
|
934
|
+
dropped.push(...droppedSet);
|
|
935
|
+
// A meta refresh navigates the document, which is a fetch just like a
|
|
936
|
+
// subresource. Redirect stubs are dropped as well.
|
|
937
|
+
for (const el of document.querySelectorAll("meta[http-equiv]")) {
|
|
938
|
+
if ((el.getAttribute("http-equiv") ?? "").toLowerCase() !== "refresh")
|
|
939
|
+
continue;
|
|
940
|
+
const target = parseMetaRefreshTarget(el.getAttribute("content") ?? "");
|
|
941
|
+
if (target === null || !isRemoteUrl(target) || isAllowed(target))
|
|
942
|
+
continue;
|
|
943
|
+
el.remove();
|
|
944
|
+
dropped.push(target);
|
|
945
|
+
}
|
|
946
|
+
return dropped;
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Extracts the target of `<meta http-equiv="refresh" content="0; url=…">`.
|
|
950
|
+
*/
|
|
951
|
+
function parseMetaRefreshTarget(content) {
|
|
952
|
+
const match = /^\s*[\d.]*\s*;?\s*url\s*=\s*(.*)$/i.exec(content);
|
|
953
|
+
if (match === null)
|
|
954
|
+
return null;
|
|
955
|
+
const target = match[1].trim().replace(/^["']|["']$/g, "");
|
|
956
|
+
return target === "" ? null : target;
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Root-relative subresource paths that survive the rewrites and therefore end
|
|
960
|
+
* up resolved against the file system location of the input document. They are
|
|
961
|
+
* broken unless something else provides them (e.g. the input is served over
|
|
962
|
+
* HTTP), so they are worth reporting.
|
|
963
|
+
*/
|
|
964
|
+
function collectUnservedVirtualPaths(document, staticMapKeys, isServable) {
|
|
965
|
+
const isMapped = (path) => staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
|
|
966
|
+
const unserved = new Set();
|
|
967
|
+
for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
|
|
968
|
+
for (const el of document.querySelectorAll(selector)) {
|
|
969
|
+
const raw = el.getAttribute(attr);
|
|
970
|
+
if (raw === null)
|
|
971
|
+
continue;
|
|
972
|
+
const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
|
|
973
|
+
for (const value of values) {
|
|
974
|
+
if (!value.startsWith("/"))
|
|
975
|
+
continue;
|
|
976
|
+
if (isMapped(value))
|
|
977
|
+
continue;
|
|
978
|
+
if (isServable !== undefined && isServable(value))
|
|
979
|
+
continue;
|
|
980
|
+
unserved.add(value);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
return [...unserved];
|
|
985
|
+
}
|
|
986
|
+
/** Remote subresource URLs a document would have to fetch. */
|
|
987
|
+
function collectRemoteReferences(document) {
|
|
988
|
+
const urls = new Set();
|
|
989
|
+
for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
|
|
990
|
+
for (const el of document.querySelectorAll(selector)) {
|
|
991
|
+
const raw = el.getAttribute(attr);
|
|
992
|
+
if (raw === null)
|
|
993
|
+
continue;
|
|
994
|
+
const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
|
|
995
|
+
for (const value of values) {
|
|
996
|
+
if (isRemoteUrl(value))
|
|
997
|
+
urls.add(value);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
return [...urls];
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Whether a remote reference is worth probing on the live site.
|
|
1005
|
+
*
|
|
1006
|
+
* A reference that resolves to a local file is served from disk, so only that
|
|
1007
|
+
* file decides whether it stays: the live site may have moved on (a new CSS
|
|
1008
|
+
* hash, a rotated upload) while our copy of the page still has what it needs.
|
|
1009
|
+
*/
|
|
1010
|
+
function referencesToProbe(url, assetBases) {
|
|
1011
|
+
const mapped = mapAbsoluteUrlToLocal(url, assetBases);
|
|
1012
|
+
return mapped.kind === "mapped" ? !existsSync(mapped.localPath) : true;
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Checks which remote references actually exist, so that content that is gone
|
|
1016
|
+
* (a deleted slide deck, a retired CSS file) is dropped instead of leaving a
|
|
1017
|
+
* broken embed that never finishes loading.
|
|
1018
|
+
*/
|
|
1019
|
+
async function probeRemoteReferences(urls, timeoutMs = 8000) {
|
|
1020
|
+
const unavailable = new Set();
|
|
1021
|
+
await Promise.all(urls.map(async (url) => {
|
|
1022
|
+
try {
|
|
1023
|
+
const response = await fetch(url, { method: "HEAD", redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
|
|
1024
|
+
// Only a definite "gone" counts: servers that reject HEAD still have the file.
|
|
1025
|
+
if (response.status === 404 || response.status === 410)
|
|
1026
|
+
unavailable.add(url);
|
|
1027
|
+
log.trace("probeRemoteReferences", { url, status: response.status });
|
|
1028
|
+
}
|
|
1029
|
+
catch (err) {
|
|
1030
|
+
// A failed probe is no proof that the resource is gone: Chromium loads
|
|
1031
|
+
// it with a browser user agent, which many sites accept where a HEAD
|
|
1032
|
+
// request from Node is rejected or blocked outright.
|
|
1033
|
+
log.trace("probeRemoteReferences failed", { url, error: String(err) });
|
|
1034
|
+
}
|
|
1035
|
+
}));
|
|
1036
|
+
return unavailable;
|
|
1037
|
+
}
|
|
1038
|
+
/** Removes the attributes that point at the given URLs. */
|
|
1039
|
+
function dropUnavailableReferencesInDom(document, unavailable) {
|
|
1040
|
+
if (unavailable.size === 0)
|
|
1041
|
+
return [];
|
|
1042
|
+
const dropped = [];
|
|
1043
|
+
for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
|
|
1044
|
+
for (const el of document.querySelectorAll(selector)) {
|
|
1045
|
+
const raw = el.getAttribute(attr);
|
|
1046
|
+
if (raw === null)
|
|
1047
|
+
continue;
|
|
1048
|
+
const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
|
|
1049
|
+
const hit = values.filter((value) => unavailable.has(value));
|
|
1050
|
+
if (hit.length === 0)
|
|
1051
|
+
continue;
|
|
1052
|
+
dropped.push(...hit);
|
|
1053
|
+
const kept = attr === "srcset"
|
|
1054
|
+
? raw
|
|
1055
|
+
.split(",")
|
|
1056
|
+
.map((e) => e.trim())
|
|
1057
|
+
.filter((c) => !unavailable.has(c.split(/\s+/)[0] ?? ""))
|
|
1058
|
+
: [];
|
|
1059
|
+
if (kept.length === 0)
|
|
1060
|
+
el.removeAttribute(attr);
|
|
1061
|
+
else
|
|
1062
|
+
el.setAttribute(attr, kept.join(", "));
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
for (const url of new Set(dropped)) {
|
|
1066
|
+
log.warn(`[fetch] Dropped unavailable remote reference: ${url}`);
|
|
1067
|
+
}
|
|
1068
|
+
return dropped;
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Exempts the wrapper's own static server from the offline pass: URLs pointing
|
|
1072
|
+
* at it are served from the local file system, never from the web.
|
|
1073
|
+
*/
|
|
1074
|
+
function isStaticServerUrl(serverBaseUrl) {
|
|
1075
|
+
return (url) => serverBaseUrl !== "" && url.startsWith(serverBaseUrl);
|
|
1076
|
+
}
|
|
1077
|
+
function reportDroppedRemoteRefs(dropped) {
|
|
1078
|
+
for (const url of new Set(dropped)) {
|
|
1079
|
+
log.info(`[offline] Dropped remote reference: ${url}`);
|
|
1080
|
+
}
|
|
1081
|
+
log.trace("dropRemoteReferencesInDom: dropped", dropped);
|
|
1082
|
+
}
|
|
1083
|
+
function reportUnservedVirtualPaths(unserved) {
|
|
1084
|
+
for (const path of unserved) {
|
|
1085
|
+
log.warn(`[html] Warning: reference is not available and will not resolve: ${path}`);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
function mapAbsoluteUrlToLocal(url, assetBases) {
|
|
1089
|
+
for (const mapping of assetBases) {
|
|
1090
|
+
if (!url.startsWith(mapping.urlBase))
|
|
1091
|
+
continue;
|
|
1092
|
+
let cleanRelative;
|
|
1093
|
+
try {
|
|
1094
|
+
cleanRelative = new URL(url).pathname.slice(1);
|
|
1095
|
+
}
|
|
1096
|
+
catch {
|
|
1097
|
+
const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
|
|
1098
|
+
cleanRelative = noQuery.split("#")[0];
|
|
1099
|
+
}
|
|
1100
|
+
if (!cleanRelative) {
|
|
1101
|
+
// The URL points to the asset-base root itself
|
|
1102
|
+
// (e.g. https://cdn.example.com/ with no sub-path).
|
|
1103
|
+
return { kind: "root-only" };
|
|
1104
|
+
}
|
|
1105
|
+
const virtualPath = posix.resolve("/", cleanRelative);
|
|
1106
|
+
const localPath = resolve(mapping.localBase, cleanRelative);
|
|
1107
|
+
return { kind: "mapped", virtualPath, localPath };
|
|
1108
|
+
}
|
|
1109
|
+
return { kind: "no-match" };
|
|
1110
|
+
}
|
|
1111
|
+
function rewriteAbsoluteUrlsInDom(document, assetBases, keepMissing = false) {
|
|
1112
|
+
if (assetBases.length === 0)
|
|
1113
|
+
return false;
|
|
1114
|
+
// "root-only" and "no-match" — leave the URL unchanged. With `keepMissing`,
|
|
1115
|
+
// URLs whose local file does not exist keep their absolute form so the browser
|
|
1116
|
+
// can load them from the mapped origin.
|
|
1117
|
+
return rewriteUrlAttributes(document, (url) => {
|
|
1118
|
+
const match = mapAbsoluteUrlToLocal(url, assetBases);
|
|
1119
|
+
if (match.kind !== "mapped")
|
|
1120
|
+
return url;
|
|
1121
|
+
if (keepMissing && !existsSync(match.localPath))
|
|
1122
|
+
return url;
|
|
1123
|
+
return match.virtualPath;
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
function rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, isServable) {
|
|
161
1127
|
const shouldRewrite = (path) => {
|
|
162
1128
|
if (!path.startsWith("/"))
|
|
163
1129
|
return false;
|
|
164
|
-
|
|
1130
|
+
if (staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`)))
|
|
1131
|
+
return true;
|
|
1132
|
+
return isServable !== undefined && isServable(path);
|
|
165
1133
|
};
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
1134
|
+
return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Returns a predicate that reports whether a root-relative path can be served
|
|
1138
|
+
* from one of the configured asset-base local roots.
|
|
1139
|
+
*
|
|
1140
|
+
* Absolute URLs that were rewritten to root-relative virtual paths (see
|
|
1141
|
+
* rewriteAbsoluteUrlsInDom) are not necessarily part of the static map — an
|
|
1142
|
+
* `<img src>` is never collected by extractUrlsFromHtml — but the static server
|
|
1143
|
+
* resolves any request path against an asset-base localBase, so those paths are
|
|
1144
|
+
* servable and must be pointed at the server instead of being resolved against
|
|
1145
|
+
* the file system location of the input document.
|
|
1146
|
+
*/
|
|
1147
|
+
function createAssetBasePathProbe(assetBases) {
|
|
1148
|
+
return (virtualPath) => {
|
|
1149
|
+
for (const ab of assetBases) {
|
|
1150
|
+
const localPath = resolve(ab.localBase, virtualPath.replace(/^\//, ""));
|
|
1151
|
+
if (existsSync(localPath)) {
|
|
1152
|
+
log.trace("createAssetBasePathProbe: servable via asset-base", { virtualPath, localPath });
|
|
1153
|
+
return true;
|
|
172
1154
|
}
|
|
173
1155
|
}
|
|
174
|
-
|
|
175
|
-
|
|
1156
|
+
return false;
|
|
1157
|
+
};
|
|
176
1158
|
}
|
|
177
1159
|
// ---------------------------------------------------------------------------
|
|
178
1160
|
// String-level wrappers (kept for external callers / tests)
|
|
@@ -211,16 +1193,27 @@ function extractUrlsFromHtml(htmlPath, includeScripts = true, doc) {
|
|
|
211
1193
|
document = new JSDOM(content).window.document;
|
|
212
1194
|
}
|
|
213
1195
|
const urls = new Set();
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
for (const el of document.querySelectorAll(
|
|
221
|
-
const
|
|
222
|
-
if (
|
|
223
|
-
|
|
1196
|
+
// Every subresource is collected, not just <link> and <script>: an <img> that
|
|
1197
|
+
// is not part of the static map can only be resolved by the fallback roots of
|
|
1198
|
+
// the static server, and a missing one would fail silently.
|
|
1199
|
+
for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
|
|
1200
|
+
if (selector === "script[src]" && !includeScripts)
|
|
1201
|
+
continue;
|
|
1202
|
+
for (const el of document.querySelectorAll(selector)) {
|
|
1203
|
+
const raw = el.getAttribute(attr);
|
|
1204
|
+
if (raw === null)
|
|
1205
|
+
continue;
|
|
1206
|
+
if (attr !== "srcset") {
|
|
1207
|
+
const url = raw.trim();
|
|
1208
|
+
if (url)
|
|
1209
|
+
urls.add(url);
|
|
1210
|
+
continue;
|
|
1211
|
+
}
|
|
1212
|
+
for (const candidate of raw.split(",")) {
|
|
1213
|
+
const url = candidate.trim().split(/\s+/)[0] ?? "";
|
|
1214
|
+
if (url)
|
|
1215
|
+
urls.add(url);
|
|
1216
|
+
}
|
|
224
1217
|
}
|
|
225
1218
|
}
|
|
226
1219
|
return [...urls];
|
|
@@ -228,25 +1221,7 @@ function extractUrlsFromHtml(htmlPath, includeScripts = true, doc) {
|
|
|
228
1221
|
// ---------------------------------------------------------------------------
|
|
229
1222
|
// Preview HTML builder
|
|
230
1223
|
// ---------------------------------------------------------------------------
|
|
231
|
-
|
|
232
|
-
* Rewrites absolute external URLs to root-relative virtual paths and writes
|
|
233
|
-
* the result as a sibling of the original input file so that
|
|
234
|
-
* cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
|
|
235
|
-
*
|
|
236
|
-
* The output filename uses a non-dotfile prefix so Vite's static server
|
|
237
|
-
* (which ignores dotfiles by default) can serve it correctly.
|
|
238
|
-
*
|
|
239
|
-
* Also derives extra static mounts from each assetBase so that secondary
|
|
240
|
-
* assets referenced from CSS (fonts, images) are served by Vivliostyle's
|
|
241
|
-
* own Vite server without needing Express.
|
|
242
|
-
*
|
|
243
|
-
* Returns:
|
|
244
|
-
* - htmlPath – sibling file path, or inputAbs if no rewriting was needed
|
|
245
|
-
* - extraStatic – virtual→local entries for assetBase roots to merge into
|
|
246
|
-
* the static map passed to Vivliostyle
|
|
247
|
-
* - cleanup – deletes the sibling file (no-op if inputAbs was returned)
|
|
248
|
-
*/
|
|
249
|
-
function buildPreviewHtml(inputAbs, assetBases, dbg) {
|
|
1224
|
+
function buildPreviewHtml(inputAbs, assetBases, options = {}) {
|
|
250
1225
|
let content;
|
|
251
1226
|
try {
|
|
252
1227
|
content = readFileSync(inputAbs, "utf-8");
|
|
@@ -254,8 +1229,6 @@ function buildPreviewHtml(inputAbs, assetBases, dbg) {
|
|
|
254
1229
|
catch (err) {
|
|
255
1230
|
throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
|
|
256
1231
|
}
|
|
257
|
-
// Derive extra static mounts for each assetBase root so secondary assets
|
|
258
|
-
// referenced from CSS are also reachable through Vivliostyle's Vite server.
|
|
259
1232
|
const extraStatic = {};
|
|
260
1233
|
for (const ab of assetBases) {
|
|
261
1234
|
let virtualPrefix;
|
|
@@ -269,34 +1242,41 @@ function buildPreviewHtml(inputAbs, assetBases, dbg) {
|
|
|
269
1242
|
virtualPrefix = `${virtualPrefix}/`;
|
|
270
1243
|
const mapKey = virtualPrefix === "/" ? "/" : virtualPrefix.slice(0, -1);
|
|
271
1244
|
if (Object.hasOwn(extraStatic, mapKey)) {
|
|
272
|
-
|
|
1245
|
+
log.warn(`[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`);
|
|
273
1246
|
}
|
|
274
1247
|
extraStatic[mapKey] = resolve(ab.localBase);
|
|
275
|
-
|
|
1248
|
+
log.trace("buildPreviewHtml: assetBase extra static mount", { mapKey, local: ab.localBase });
|
|
276
1249
|
}
|
|
277
1250
|
const dom = new JSDOM(content);
|
|
278
1251
|
const document = dom.window.document;
|
|
279
1252
|
const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
|
|
280
1253
|
if (changed)
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
1254
|
+
log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
|
|
1255
|
+
const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
|
|
1256
|
+
if (dropped.length > 0)
|
|
1257
|
+
reportDroppedRemoteRefs(dropped);
|
|
1258
|
+
if (!changed && dropped.length === 0) {
|
|
1259
|
+
log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
|
|
284
1260
|
return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
|
|
285
1261
|
}
|
|
286
|
-
const
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
1262
|
+
const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
|
|
1263
|
+
const htmlPath = dumpDir === null ? join(dirname(inputAbs), `_vivliostyle_preview_${basename(inputAbs)}`) : join(dumpDir, basename(inputAbs));
|
|
1264
|
+
if (dumpDir !== null)
|
|
1265
|
+
mkdirSync(dumpDir, { recursive: true });
|
|
290
1266
|
writeFileSync(htmlPath, dom.serialize(), "utf-8");
|
|
291
|
-
|
|
292
|
-
|
|
1267
|
+
log.trace("buildPreviewHtml: wrote rewritten HTML", htmlPath);
|
|
1268
|
+
log.info(`[preview] Wrote rewritten HTML: ${htmlPath}`);
|
|
293
1269
|
const cleanup = () => {
|
|
1270
|
+
if (dumpDir !== null) {
|
|
1271
|
+
log.trace("buildPreviewHtml: keeping dumped HTML", htmlPath);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
294
1274
|
try {
|
|
295
1275
|
rmSync(htmlPath, { force: true });
|
|
296
|
-
|
|
1276
|
+
log.trace("buildPreviewHtml: removed rewritten HTML", htmlPath);
|
|
297
1277
|
}
|
|
298
1278
|
catch (err) {
|
|
299
|
-
|
|
1279
|
+
log.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
|
|
300
1280
|
}
|
|
301
1281
|
};
|
|
302
1282
|
return { htmlPath, extraStatic, cleanup };
|
|
@@ -304,13 +1284,7 @@ function buildPreviewHtml(inputAbs, assetBases, dbg) {
|
|
|
304
1284
|
// ---------------------------------------------------------------------------
|
|
305
1285
|
// Build HTML builder
|
|
306
1286
|
// ---------------------------------------------------------------------------
|
|
307
|
-
|
|
308
|
-
* Prepares the HTML for BUILD mode.
|
|
309
|
-
* Both rewrite passes (absolute → virtual, virtual → absolute server URL)
|
|
310
|
-
* are applied in a single DOM parse.
|
|
311
|
-
* If nothing changed the original file path is returned with a no-op cleanup.
|
|
312
|
-
*/
|
|
313
|
-
function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl, dbg) {
|
|
1287
|
+
function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl, options = {}) {
|
|
314
1288
|
let content;
|
|
315
1289
|
try {
|
|
316
1290
|
content = readFileSync(inputAbs, "utf-8");
|
|
@@ -321,28 +1295,60 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
|
|
|
321
1295
|
const dom = new JSDOM(content);
|
|
322
1296
|
const document = dom.window.document;
|
|
323
1297
|
const staticMapKeys = Object.keys(staticMap);
|
|
324
|
-
const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases);
|
|
1298
|
+
const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases, options.fetchMissing === true);
|
|
325
1299
|
if (absChanged)
|
|
326
|
-
|
|
327
|
-
const
|
|
1300
|
+
log.trace("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
|
|
1301
|
+
const probe = assetBases.length > 0 ? createAssetBasePathProbe(assetBases) : undefined;
|
|
1302
|
+
const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
|
|
328
1303
|
if (srvChanged)
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
1304
|
+
log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
|
|
1305
|
+
const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
|
|
1306
|
+
const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
|
|
1307
|
+
if (dropped.length > 0)
|
|
1308
|
+
reportDroppedRemoteRefs(dropped);
|
|
1309
|
+
const unserved = collectUnservedVirtualPaths(document, staticMapKeys, probe);
|
|
1310
|
+
if (unserved.length > 0)
|
|
1311
|
+
reportUnservedVirtualPaths(unserved);
|
|
1312
|
+
// The runtime script only matters for pages that run scripts; injecting it
|
|
1313
|
+
// into a plain document would rewrite the file for nothing.
|
|
1314
|
+
const hasScripts = document.querySelector("script") !== null;
|
|
1315
|
+
const wantsRuntime = (options.shimOrigin != null && hasScripts) || options.settle != null;
|
|
1316
|
+
if (wantsRuntime) {
|
|
1317
|
+
const origin = options.shimOrigin ?? serverBaseUrl;
|
|
1318
|
+
const documentBaseUrl = options.documentBaseUrl ?? `${origin}/`;
|
|
1319
|
+
// Only the PDF run expands `<details>`; the preview stays interactive.
|
|
1320
|
+
injectRuntimeScriptInDom(document, { origin, documentBaseUrl, gate: options.settle ?? null, expandDetails: true });
|
|
1321
|
+
log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
|
|
1322
|
+
}
|
|
1323
|
+
if (!absChanged && !srvChanged && dropped.length === 0 && gone.length === 0 && options.settle == null && !wantsRuntime) {
|
|
1324
|
+
log.trace("prepareInputHtmlForBuild: no changes, using original file");
|
|
332
1325
|
return { vivliostyleInput: inputAbs, cleanup: () => undefined };
|
|
333
1326
|
}
|
|
334
|
-
const
|
|
335
|
-
|
|
1327
|
+
const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
|
|
1328
|
+
let tmpDir = null;
|
|
1329
|
+
let tmpHtml;
|
|
1330
|
+
if (dumpDir !== null) {
|
|
1331
|
+
mkdirSync(dumpDir, { recursive: true });
|
|
1332
|
+
tmpHtml = join(dumpDir, basename(inputAbs));
|
|
1333
|
+
}
|
|
1334
|
+
else {
|
|
1335
|
+
tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
|
|
1336
|
+
tmpHtml = join(tmpDir, "index.html");
|
|
1337
|
+
}
|
|
336
1338
|
writeFileSync(tmpHtml, dom.serialize(), "utf-8");
|
|
337
|
-
|
|
338
|
-
|
|
1339
|
+
log.info(`[html] ${dumpDir === null ? "Prepared" : "Dumped"} input HTML → ${tmpHtml}`);
|
|
1340
|
+
log.trace("prepareInputHtmlForBuild: written", tmpHtml);
|
|
339
1341
|
const cleanup = () => {
|
|
1342
|
+
if (tmpDir === null) {
|
|
1343
|
+
log.trace("prepareInputHtmlForBuild: keeping dumped HTML", tmpHtml);
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
340
1346
|
try {
|
|
341
1347
|
rmSync(tmpDir, { recursive: true, force: true });
|
|
342
|
-
|
|
1348
|
+
log.trace("prepareInputHtmlForBuild: removed temp dir", tmpDir);
|
|
343
1349
|
}
|
|
344
1350
|
catch (err) {
|
|
345
|
-
|
|
1351
|
+
log.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
|
|
346
1352
|
}
|
|
347
1353
|
};
|
|
348
1354
|
return { vivliostyleInput: tmpHtml, cleanup };
|
|
@@ -374,53 +1380,41 @@ function parseAssetBaseMapping(value) {
|
|
|
374
1380
|
}
|
|
375
1381
|
return { urlBase: normalizeUrlBase(urlBase), localBase };
|
|
376
1382
|
}
|
|
377
|
-
function
|
|
378
|
-
for (const mapping of assetBases) {
|
|
379
|
-
if (!url.startsWith(mapping.urlBase))
|
|
380
|
-
continue;
|
|
381
|
-
let cleanRelative;
|
|
382
|
-
try {
|
|
383
|
-
cleanRelative = new URL(url).pathname.slice(1);
|
|
384
|
-
}
|
|
385
|
-
catch {
|
|
386
|
-
const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
|
|
387
|
-
cleanRelative = noQuery.split("#")[0];
|
|
388
|
-
}
|
|
389
|
-
if (!cleanRelative)
|
|
390
|
-
return null;
|
|
391
|
-
const virtualPath = posix.resolve("/", cleanRelative);
|
|
392
|
-
const localPath = resolve(mapping.localBase, cleanRelative);
|
|
393
|
-
return { virtualPath, localPath };
|
|
394
|
-
}
|
|
395
|
-
return null;
|
|
396
|
-
}
|
|
397
|
-
function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
|
|
1383
|
+
function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets) {
|
|
398
1384
|
const trimmed = url.trim();
|
|
399
1385
|
if (!trimmed)
|
|
400
1386
|
return { kind: "skipped", url, reason: "empty URL" };
|
|
401
1387
|
if (trimmed.startsWith("#"))
|
|
402
1388
|
return { kind: "skipped", url, reason: "fragment-only URL" };
|
|
403
|
-
const
|
|
404
|
-
if (
|
|
405
|
-
|
|
406
|
-
|
|
1389
|
+
const assetMatch = mapAbsoluteUrlToLocal(trimmed, assetBases);
|
|
1390
|
+
if (assetMatch.kind === "root-only") {
|
|
1391
|
+
return {
|
|
1392
|
+
kind: "skipped",
|
|
1393
|
+
url,
|
|
1394
|
+
reason: "URL matches an asset-base prefix but has no path component (root URL)"
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
if (assetMatch.kind === "mapped") {
|
|
1398
|
+
if (shouldIgnoreVirtualPath(assetMatch.virtualPath, ignoredAssets)) {
|
|
1399
|
+
log.trace("urlToStaticMapping: ignored (asset-base match)", { url, ...assetMatch });
|
|
407
1400
|
return {
|
|
408
1401
|
kind: "skipped",
|
|
409
1402
|
url,
|
|
410
|
-
reason: `matches --ignore-asset "${
|
|
1403
|
+
reason: `matches --ignore-asset "${assetMatch.virtualPath}"`
|
|
411
1404
|
};
|
|
412
1405
|
}
|
|
413
|
-
if (!existsSync(
|
|
414
|
-
|
|
1406
|
+
if (!existsSync(assetMatch.localPath)) {
|
|
1407
|
+
log.warn(`[html] Warning: asset-base mapped path does not exist\n` +
|
|
415
1408
|
` url : ${url}\n` +
|
|
416
|
-
` virtual : ${
|
|
417
|
-
` local : ${
|
|
1409
|
+
` virtual : ${assetMatch.virtualPath}\n` +
|
|
1410
|
+
` local : ${assetMatch.localPath}`);
|
|
418
1411
|
}
|
|
419
1412
|
return {
|
|
420
1413
|
kind: "mapped",
|
|
421
|
-
mapping: `${
|
|
1414
|
+
mapping: `${assetMatch.virtualPath}:${assetMatch.localPath}`
|
|
422
1415
|
};
|
|
423
1416
|
}
|
|
1417
|
+
// assetMatch.kind === "no-match" — proceed to local / external handling
|
|
424
1418
|
if (trimmed.startsWith("//")) {
|
|
425
1419
|
return { kind: "skipped", url, reason: "protocol-relative external URL" };
|
|
426
1420
|
}
|
|
@@ -434,12 +1428,16 @@ function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
|
|
|
434
1428
|
}
|
|
435
1429
|
const [cleanUrl] = trimmed.split(/[?#]/);
|
|
436
1430
|
if (!cleanUrl) {
|
|
437
|
-
return {
|
|
1431
|
+
return {
|
|
1432
|
+
kind: "skipped",
|
|
1433
|
+
url,
|
|
1434
|
+
reason: "URL is empty after stripping query/fragment"
|
|
1435
|
+
};
|
|
438
1436
|
}
|
|
439
1437
|
const localPath = resolve(htmlDir, cleanUrl);
|
|
440
1438
|
const virtualPath = cleanUrl.startsWith("/") ? posix.normalize(cleanUrl) : posix.resolve("/", posix.relative(htmlDir, localPath));
|
|
441
1439
|
if (shouldIgnoreVirtualPath(virtualPath, ignoredAssets)) {
|
|
442
|
-
|
|
1440
|
+
log.trace("urlToStaticMapping: ignored (ignore-asset match)", { url, virtualPath });
|
|
443
1441
|
return {
|
|
444
1442
|
kind: "skipped",
|
|
445
1443
|
url,
|
|
@@ -447,7 +1445,7 @@ function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
|
|
|
447
1445
|
};
|
|
448
1446
|
}
|
|
449
1447
|
if (!existsSync(localPath)) {
|
|
450
|
-
|
|
1448
|
+
log.warn(`[html] Warning: referenced path does not exist\n` +
|
|
451
1449
|
` url : ${url}\n` +
|
|
452
1450
|
` virtual : ${virtualPath}\n` +
|
|
453
1451
|
` local : ${localPath}`);
|
|
@@ -476,7 +1474,7 @@ function buildStaticMap(rawMappings) {
|
|
|
476
1474
|
for (const mapping of rawMappings) {
|
|
477
1475
|
const { virtual, local } = parseStaticMapping(mapping);
|
|
478
1476
|
if (Object.hasOwn(map, virtual)) {
|
|
479
|
-
|
|
1477
|
+
log.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
|
|
480
1478
|
}
|
|
481
1479
|
map[virtual] = local;
|
|
482
1480
|
}
|
|
@@ -485,40 +1483,53 @@ function buildStaticMap(rawMappings) {
|
|
|
485
1483
|
// ---------------------------------------------------------------------------
|
|
486
1484
|
// Extra args parser
|
|
487
1485
|
// ---------------------------------------------------------------------------
|
|
1486
|
+
/**
|
|
1487
|
+
* Vivliostyle's config object uses camelCase keys (`viewerParam`, `userStyle`)
|
|
1488
|
+
* and typed values, so `--viewer-param` has to arrive as `viewerParam` and
|
|
1489
|
+
* `--timeout 60000` as the number 60000.
|
|
1490
|
+
*/
|
|
1491
|
+
function normalizeExtraKey(key) {
|
|
1492
|
+
return key.replace(/-([a-z0-9])/g, (_match, char) => char.toUpperCase());
|
|
1493
|
+
}
|
|
1494
|
+
function coerceExtraValue(value) {
|
|
1495
|
+
if (value === "true")
|
|
1496
|
+
return true;
|
|
1497
|
+
if (value === "false")
|
|
1498
|
+
return false;
|
|
1499
|
+
// Only plain integers, so that version-like strings ("1.9.2") stay strings.
|
|
1500
|
+
return /^-?\d+$/.test(value) ? Number.parseInt(value, 10) : value;
|
|
1501
|
+
}
|
|
488
1502
|
function parseExtraArgs(extraArgs) {
|
|
489
1503
|
const extraConfig = {};
|
|
1504
|
+
const assign = (rawKey, rawValue) => {
|
|
1505
|
+
extraConfig[normalizeExtraKey(rawKey)] = typeof rawValue === "boolean" ? rawValue : coerceExtraValue(rawValue);
|
|
1506
|
+
};
|
|
490
1507
|
for (let i = 0; i < extraArgs.length; i++) {
|
|
491
1508
|
const arg = extraArgs[i];
|
|
492
1509
|
if (!arg.startsWith("--")) {
|
|
493
1510
|
if (arg.startsWith("-")) {
|
|
494
|
-
|
|
1511
|
+
log.warn(`[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
|
|
495
1512
|
` Use the long-form --flag equivalent instead.`);
|
|
496
1513
|
}
|
|
497
1514
|
continue;
|
|
498
1515
|
}
|
|
499
1516
|
if (arg.includes("=")) {
|
|
500
1517
|
const eqIdx = arg.indexOf("=");
|
|
501
|
-
|
|
502
|
-
const val = arg.slice(eqIdx + 1);
|
|
503
|
-
extraConfig[key] = val === "true" ? true : val === "false" ? false : val;
|
|
1518
|
+
assign(arg.slice(2, eqIdx), arg.slice(eqIdx + 1));
|
|
504
1519
|
continue;
|
|
505
1520
|
}
|
|
506
1521
|
const key = arg.slice(2);
|
|
507
1522
|
const next = extraArgs[i + 1];
|
|
508
|
-
if (next === "true") {
|
|
509
|
-
|
|
510
|
-
i++;
|
|
511
|
-
}
|
|
512
|
-
else if (next === "false") {
|
|
513
|
-
extraConfig[key] = false;
|
|
1523
|
+
if (next === "true" || next === "false") {
|
|
1524
|
+
assign(key, next === "true");
|
|
514
1525
|
i++;
|
|
515
1526
|
}
|
|
516
|
-
else if (next && !next.startsWith("-")) {
|
|
517
|
-
|
|
1527
|
+
else if (next !== undefined && !next.startsWith("-")) {
|
|
1528
|
+
assign(key, next);
|
|
518
1529
|
i++;
|
|
519
1530
|
}
|
|
520
1531
|
else {
|
|
521
|
-
extraConfig[key] = true;
|
|
1532
|
+
extraConfig[normalizeExtraKey(key)] = true;
|
|
522
1533
|
}
|
|
523
1534
|
}
|
|
524
1535
|
return extraConfig;
|
|
@@ -590,7 +1601,37 @@ function buildProgram() {
|
|
|
590
1601
|
"Example: --ignore-asset /livereload.js",
|
|
591
1602
|
"Repeatable. Only applies when the input is an HTML file."
|
|
592
1603
|
].join("\n "), (val, prev) => prev.concat(val), [])
|
|
593
|
-
.option("--
|
|
1604
|
+
.option("--allow-remote", [
|
|
1605
|
+
"Keep subresource references that would be fetched from the network.",
|
|
1606
|
+
"By default every reference without a local file is removed from the",
|
|
1607
|
+
"input HTML so that nothing is loaded from the web.",
|
|
1608
|
+
"Hyperlinks (<a href>) are never touched. See also --fetch-missing."
|
|
1609
|
+
].join("\n "))
|
|
1610
|
+
.option("--fetch-missing", [
|
|
1611
|
+
"Load references without a local file from the mapped origin instead of",
|
|
1612
|
+
"dropping them. The local server redirects missing files to the site",
|
|
1613
|
+
"origin, which also covers data that page scripts fetch by relative URL.",
|
|
1614
|
+
"Implies --allow-remote, so remote iframes and scripts are loaded too.",
|
|
1615
|
+
"Nothing is written to the input directory."
|
|
1616
|
+
].join("\n "))
|
|
1617
|
+
.option("--wait-for-content [ms]", [
|
|
1618
|
+
"Delay pagination until the page's own async work finished: no request in",
|
|
1619
|
+
"flight and the document height stable for --quiet-ms (default 400).",
|
|
1620
|
+
"Without [ms] the hard limit of 25000ms applies; larger values are capped."
|
|
1621
|
+
].join("\n "))
|
|
1622
|
+
.option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
|
|
1623
|
+
.option("--timeout <ms>", ["Give up on a page after <ms> (Vivliostyle default: 300000).", "Lower it for pages with embeds that never finish loading."].join("\n "))
|
|
1624
|
+
.option("--pixel-ratio <n>", [
|
|
1625
|
+
"Render at n times the output resolution (Vivliostyle pixelRatio), e.g. 2.",
|
|
1626
|
+
"Layout and raster resolution increase while the page keeps its size,",
|
|
1627
|
+
"which removes pixel artifacts in canvas and WebGL content.",
|
|
1628
|
+
"Pages exposing window.__vivResize(factor) are also redrawn at n×",
|
|
1629
|
+
"backing pixels before printing, so output past 96dpi stays sharp."
|
|
1630
|
+
].join("\n "))
|
|
1631
|
+
.option("--dump-html <dir>", [
|
|
1632
|
+
"Write the rewritten input HTML into <dir> and keep it, instead of a",
|
|
1633
|
+
"temporary file. Use it to inspect what Vivliostyle actually renders."
|
|
1634
|
+
].join("\n "))
|
|
594
1635
|
.option("--format <format>", `Output format: ${validFormats.join(" | ")}`, "pdf")
|
|
595
1636
|
.option("--log-level <level>", `Vivliostyle log level: ${validLogLevels.join(" | ")}`, "info")
|
|
596
1637
|
.option("--mode <mode>", `Execution mode: ${validModes.join(" | ")}`, "build")
|
|
@@ -601,16 +1642,18 @@ function buildProgram() {
|
|
|
601
1642
|
"Notes:",
|
|
602
1643
|
" • HTML input (.html/.htm) is detected automatically from the file extension.",
|
|
603
1644
|
" • For HTML input, <link href> and <script src> are parsed and auto-mapped.",
|
|
1645
|
+
" • References without a local file are dropped (offline by default); use --allow-remote to keep them.",
|
|
604
1646
|
" • Options after -- are forwarded verbatim to Vivliostyle.",
|
|
605
1647
|
" • --debug sets --log-level to debug automatically.",
|
|
606
1648
|
" • --preview and --mode preview are equivalent.",
|
|
607
|
-
" •
|
|
608
|
-
" •
|
|
1649
|
+
" • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
|
|
1650
|
+
" • the browser prints that page to PDF, so canvases and iframes stay real content.",
|
|
1651
|
+
" • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
|
|
609
1652
|
" • --asset-base localBase is also a fallback root for CSS-referenced assets."
|
|
610
1653
|
].join("\n"));
|
|
611
1654
|
}
|
|
612
1655
|
function printHelp() {
|
|
613
|
-
buildProgram().help();
|
|
1656
|
+
buildProgram().help({ error: false });
|
|
614
1657
|
}
|
|
615
1658
|
function parseArgs(argv) {
|
|
616
1659
|
const { cliArgv, extraArgs } = splitArgsAtDoubleDash(argv);
|
|
@@ -629,27 +1672,71 @@ function parseArgs(argv) {
|
|
|
629
1672
|
}
|
|
630
1673
|
return { options: program.opts(), extraArgs };
|
|
631
1674
|
}
|
|
1675
|
+
async function runRender(params) {
|
|
1676
|
+
const request = {
|
|
1677
|
+
documentUrl: params.documentUrl,
|
|
1678
|
+
viewerPageUrl: params.viewerPageUrl,
|
|
1679
|
+
output: params.outputAbs,
|
|
1680
|
+
viewerParams: params.viewerParams,
|
|
1681
|
+
timeoutMs: params.timeoutMs,
|
|
1682
|
+
waitForSettle: params.waitForSettle,
|
|
1683
|
+
...(params.chromeExecutable === undefined ? {} : { chromeExecutable: params.chromeExecutable }),
|
|
1684
|
+
...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
|
|
1685
|
+
...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
|
|
1686
|
+
...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
|
|
1687
|
+
...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language })
|
|
1688
|
+
};
|
|
1689
|
+
log.trace("renderPdf request", request);
|
|
1690
|
+
const result = await renderPdf(request);
|
|
1691
|
+
log.trace("renderPdf result", { pageCount: result.pageCount, bytes: result.bytes, settle: result.settle });
|
|
1692
|
+
log.info(`✓ Document created: ${result.output} (${result.pageCount} pages)`);
|
|
1693
|
+
}
|
|
632
1694
|
// ---------------------------------------------------------------------------
|
|
633
1695
|
// Core execute
|
|
634
1696
|
// ---------------------------------------------------------------------------
|
|
1697
|
+
/**
|
|
1698
|
+
* Log level for the wrapper's own output. `-d` wins over `--log-level`, which
|
|
1699
|
+
* is also forwarded to Vivliostyle unchanged.
|
|
1700
|
+
*/
|
|
1701
|
+
function resolveInternalLogLevel(options) {
|
|
1702
|
+
if (options.debug === true)
|
|
1703
|
+
return "debug";
|
|
1704
|
+
const level = options.logLevel;
|
|
1705
|
+
return validLogLevels.includes(level) ? level : "info";
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* `--wait-for-content [ms]`: hold the document's load event until the page's own
|
|
1709
|
+
* async work finished. Vivliostyle stops waiting for images after 30s, so the
|
|
1710
|
+
* hard limit is capped below that.
|
|
1711
|
+
*/
|
|
1712
|
+
const MAX_SETTLE_DEADLINE_MS = 25_000;
|
|
1713
|
+
function resolveSettleGate(options) {
|
|
1714
|
+
const raw = options.waitForContent;
|
|
1715
|
+
if (raw === undefined || raw === false)
|
|
1716
|
+
return null;
|
|
1717
|
+
const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
|
|
1718
|
+
if (!Number.isFinite(requested) || requested <= 0)
|
|
1719
|
+
throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
|
|
1720
|
+
const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
|
|
1721
|
+
if (!Number.isFinite(quietRaw) || quietRaw <= 0)
|
|
1722
|
+
throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
|
|
1723
|
+
return {
|
|
1724
|
+
quietMs: quietRaw,
|
|
1725
|
+
deadlineMs: Math.min(requested, MAX_SETTLE_DEADLINE_MS)
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
635
1728
|
async function execute(options, extraArgs = []) {
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
dbg("extra args (after --)", extraArgs);
|
|
1729
|
+
log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
|
|
1730
|
+
log.trace("raw CLI options", options);
|
|
1731
|
+
log.trace("extra args (after --)", extraArgs);
|
|
640
1732
|
if (!options.input)
|
|
641
1733
|
throw new Error("Missing required option: --input");
|
|
642
1734
|
const inputAbs = resolve(options.input);
|
|
643
|
-
|
|
1735
|
+
log.trace("resolved input", inputAbs);
|
|
644
1736
|
if (!existsSync(inputAbs))
|
|
645
1737
|
throw new Error(`Input file does not exist: ${inputAbs}`);
|
|
646
|
-
const cwd = options.cwd ? resolve(options.cwd) : dirname(inputAbs);
|
|
647
|
-
if (!existsSync(cwd)) {
|
|
648
|
-
throw new Error(`Working directory does not exist: ${cwd}`);
|
|
649
|
-
}
|
|
650
|
-
dbg("cwd", cwd);
|
|
651
1738
|
const outputAbs = resolve(options.output);
|
|
652
|
-
|
|
1739
|
+
log.trace("resolved output", outputAbs);
|
|
653
1740
|
if (!validFormats.includes(options.format)) {
|
|
654
1741
|
throw new Error(`Invalid format: "${options.format}". Allowed: ${validFormats.join(", ")}`);
|
|
655
1742
|
}
|
|
@@ -658,202 +1745,275 @@ async function execute(options, extraArgs = []) {
|
|
|
658
1745
|
throw new Error(`Invalid log level: "${options.logLevel}". Allowed: ${validLogLevels.join(", ")}`);
|
|
659
1746
|
}
|
|
660
1747
|
const logLevel = options.debug ? "debug" : options.logLevel;
|
|
661
|
-
|
|
1748
|
+
log.trace("logLevel", logLevel);
|
|
662
1749
|
const mode = (options.preview ? "preview" : options.mode);
|
|
663
1750
|
if (!validModes.includes(mode)) {
|
|
664
1751
|
throw new Error(`Invalid mode: "${mode}". Allowed: ${validModes.join(", ")}`);
|
|
665
1752
|
}
|
|
666
|
-
|
|
1753
|
+
log.trace("mode", mode);
|
|
667
1754
|
const htmlMode = isHtmlInput(inputAbs);
|
|
668
|
-
|
|
1755
|
+
log.trace("htmlMode (auto-detected)", htmlMode);
|
|
669
1756
|
if (!htmlMode) {
|
|
670
1757
|
if (options.assetBase.length > 0) {
|
|
671
|
-
|
|
1758
|
+
log.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
|
|
672
1759
|
}
|
|
673
1760
|
if (options.ignoreAsset.length > 0) {
|
|
674
|
-
|
|
1761
|
+
log.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
|
|
675
1762
|
}
|
|
676
1763
|
}
|
|
677
1764
|
const assetBases = options.assetBase.map(parseAssetBaseMapping);
|
|
678
|
-
|
|
1765
|
+
log.trace("parsed assetBases", assetBases);
|
|
679
1766
|
const ignoredAssets = new Set(options.ignoreAsset.map(normalizeIgnoreAssetPath));
|
|
680
|
-
|
|
1767
|
+
log.trace("ignoredAssets", [...ignoredAssets]);
|
|
681
1768
|
// ── HTML-derived mappings ────────────────────────────────────────────────
|
|
682
1769
|
const derivedMappings = [];
|
|
683
1770
|
if (htmlMode) {
|
|
684
1771
|
const htmlDir = dirname(inputAbs);
|
|
685
|
-
|
|
1772
|
+
log.info(`[html] Analysing input as HTML: ${inputAbs}`);
|
|
686
1773
|
const includeScripts = mode === "preview" ? true : options.scripts;
|
|
687
1774
|
const urls = extractUrlsFromHtml(inputAbs, includeScripts);
|
|
688
1775
|
if (urls.length === 0) {
|
|
689
|
-
|
|
1776
|
+
log.info("[html] No URLs found in input HTML");
|
|
690
1777
|
}
|
|
691
1778
|
else {
|
|
692
|
-
|
|
1779
|
+
log.info(`[html] Found URLs (${urls.length}):`);
|
|
693
1780
|
}
|
|
694
1781
|
for (const url of urls) {
|
|
695
|
-
const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets
|
|
1782
|
+
const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets);
|
|
696
1783
|
if (result.kind === "skipped") {
|
|
697
|
-
|
|
1784
|
+
log.info(` → Skipped (${result.reason}): ${url}`);
|
|
698
1785
|
continue;
|
|
699
1786
|
}
|
|
700
|
-
|
|
1787
|
+
log.info(` → Mapping: ${result.mapping}`);
|
|
701
1788
|
derivedMappings.push(result.mapping);
|
|
702
1789
|
}
|
|
703
|
-
|
|
1790
|
+
log.trace("derived static mappings from HTML", derivedMappings);
|
|
704
1791
|
}
|
|
705
1792
|
// ── static map ────────────────────────────────────────────────────────────
|
|
706
1793
|
const allStaticMappings = [...options.static, ...derivedMappings];
|
|
707
|
-
|
|
1794
|
+
log.trace("all raw static mappings", allStaticMappings);
|
|
708
1795
|
const staticMap = buildStaticMap(allStaticMappings);
|
|
709
|
-
|
|
710
|
-
|
|
1796
|
+
log.trace("assembled staticMap", staticMap);
|
|
1797
|
+
// Mappings derived from the HTML have already been reported by
|
|
1798
|
+
// urlToStaticMapping; only explicit --static mounts are checked here.
|
|
1799
|
+
const derivedVirtualPaths = new Set(derivedMappings.map((mapping) => parseStaticMapping(mapping).virtual));
|
|
711
1800
|
for (const [virtualPath, localPath] of Object.entries(staticMap)) {
|
|
1801
|
+
if (derivedVirtualPaths.has(virtualPath))
|
|
1802
|
+
continue;
|
|
712
1803
|
if (!existsSync(localPath)) {
|
|
713
|
-
|
|
1804
|
+
log.warn(`[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`);
|
|
714
1805
|
}
|
|
715
1806
|
}
|
|
716
1807
|
const extraConfig = parseExtraArgs(extraArgs);
|
|
717
|
-
|
|
1808
|
+
log.trace("extraConfig (parsed from -- args)", extraConfig);
|
|
718
1809
|
const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
|
|
719
|
-
|
|
720
|
-
|
|
1810
|
+
const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
|
|
1811
|
+
const settle = resolveSettleGate(options);
|
|
1812
|
+
const htmlOptions = {
|
|
1813
|
+
allowRemote: fetchMissing,
|
|
1814
|
+
fetchMissing,
|
|
1815
|
+
dumpDir: options.dumpHtml ?? null,
|
|
1816
|
+
settle,
|
|
1817
|
+
...(typeof extraConfig.css === "string" ? { css: extraConfig.css } : {}),
|
|
1818
|
+
...(typeof extraConfig.userStyle === "string" ? { userStyle: extraConfig.userStyle } : {})
|
|
1819
|
+
};
|
|
1820
|
+
log.trace("htmlRewriteOptions", htmlOptions);
|
|
1821
|
+
if (options.timeout !== undefined) {
|
|
1822
|
+
const timeoutMs = Number.parseInt(options.timeout, 10);
|
|
1823
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
|
|
1824
|
+
throw new Error(`Invalid --timeout: "${options.timeout}"`);
|
|
1825
|
+
extraConfig.timeout = timeoutMs;
|
|
1826
|
+
log.info(`[render] timeout=${timeoutMs}ms`);
|
|
1827
|
+
}
|
|
1828
|
+
if (options.pixelRatio !== undefined) {
|
|
1829
|
+
const ratio = Number.parseFloat(options.pixelRatio);
|
|
1830
|
+
if (!Number.isFinite(ratio) || ratio <= 0)
|
|
1831
|
+
throw new Error(`Invalid --pixel-ratio: "${options.pixelRatio}"`);
|
|
1832
|
+
const existing = typeof extraConfig.viewerParam === "string" ? extraConfig.viewerParam : "";
|
|
1833
|
+
extraConfig.viewerParam = existing === "" ? `pixelRatio=${ratio}` : `${existing}&pixelRatio=${ratio}`;
|
|
1834
|
+
log.info(`[render] pixelRatio=${ratio}`);
|
|
1835
|
+
}
|
|
1836
|
+
// Canvas/WebGL backing-store upscale follows --pixel-ratio: layout keeps its
|
|
1837
|
+
// CSS size while JS-painted pixels are redrawn at n× resolution so print
|
|
1838
|
+
// output past 96dpi stays sharp. Pages opt in via window.__vivResize(factor).
|
|
1839
|
+
const canvasScale = options.pixelRatio === undefined
|
|
1840
|
+
? undefined
|
|
1841
|
+
: (() => {
|
|
1842
|
+
const ratio = Number.parseFloat(options.pixelRatio);
|
|
1843
|
+
return Number.isFinite(ratio) && ratio > 1 ? ratio : undefined;
|
|
1844
|
+
})();
|
|
1845
|
+
log.info(`Starting Vivliostyle in mode: ${mode}`);
|
|
1846
|
+
// ── BUILD mode ───────────────────────────────────────────────────────────────
|
|
721
1847
|
if (mode === "build") {
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
1848
|
+
if (format !== "pdf")
|
|
1849
|
+
throw new Error(`Unsupported format: ${format}. This renderer produces PDF only.`);
|
|
1850
|
+
const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
|
|
1851
|
+
const viewerLibDir = resolveViewerLibDir();
|
|
1852
|
+
log.trace("viewerLibDir", viewerLibDir);
|
|
1853
|
+
log.trace("sitePath", sitePath);
|
|
1854
|
+
const entry = { localPath: null, sitePath };
|
|
1855
|
+
const server = await startStaticServer({
|
|
1856
|
+
staticMap,
|
|
1857
|
+
assetBases,
|
|
1858
|
+
entry,
|
|
1859
|
+
fetchMissing: htmlOptions.fetchMissing === true,
|
|
1860
|
+
settle: htmlOptions.settle ?? null,
|
|
1861
|
+
viewerLibDir,
|
|
1862
|
+
viewerFilePath: join(viewerLibDir, "index.html"),
|
|
1863
|
+
log: (message) => log.info(message),
|
|
1864
|
+
onSettled: ({ reason, waitedMs, detail }) => {
|
|
1865
|
+
// Detail is logged in both branches: the deadline case is exactly
|
|
1866
|
+
// when canvas sizes and readiness matter most (e.g. slow WebGL).
|
|
1867
|
+
const line = `[wait] layout gate ${reason} after ${waitedMs}ms`;
|
|
1868
|
+
const withDetail = detail === undefined ? line : `${line} ${JSON.stringify(detail)}`;
|
|
1869
|
+
if (reason === "settled")
|
|
1870
|
+
log.info(withDetail);
|
|
1871
|
+
else
|
|
1872
|
+
log.warn(`${withDetail} — content may be incomplete`);
|
|
743
1873
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
1874
|
+
});
|
|
1875
|
+
const htmlResource = { cleanup: () => undefined };
|
|
1876
|
+
try {
|
|
1877
|
+
// Remote references are only worth keeping if they still exist.
|
|
1878
|
+
const remoteReferences = collectRemoteReferences(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document).filter((url) => referencesToProbe(url, assetBases));
|
|
1879
|
+
const unavailableUrls = htmlOptions.fetchMissing === true ? await probeRemoteReferences(remoteReferences) : undefined;
|
|
1880
|
+
if (unavailableUrls !== undefined && unavailableUrls.size > 0) {
|
|
1881
|
+
log.warn(`[fetch] ${unavailableUrls.size} remote reference(s) are unavailable and will be dropped`);
|
|
747
1882
|
}
|
|
1883
|
+
const prepared = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, {
|
|
1884
|
+
...htmlOptions,
|
|
1885
|
+
unavailableUrls,
|
|
1886
|
+
shimOrigin: server.baseUrl,
|
|
1887
|
+
// The viewer is served next to the document, so scripts the page runs
|
|
1888
|
+
// resolve their relative URLs against the document's own directory.
|
|
1889
|
+
documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
|
|
1890
|
+
});
|
|
1891
|
+
htmlResource.cleanup = prepared.cleanup;
|
|
1892
|
+
entry.localPath = prepared.vivliostyleInput;
|
|
1893
|
+
const documentUrl = `${server.baseUrl}${sitePath}`;
|
|
1894
|
+
const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
|
|
1895
|
+
log.info(`[html] Serving document at ${documentUrl}`);
|
|
1896
|
+
await runRender({
|
|
1897
|
+
documentUrl,
|
|
1898
|
+
viewerPageUrl,
|
|
1899
|
+
outputAbs,
|
|
1900
|
+
metaFields,
|
|
1901
|
+
viewerParams: buildRenderViewerParams(extraConfig, htmlOptions),
|
|
1902
|
+
timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
|
|
1903
|
+
waitForSettle: htmlOptions.settle != null,
|
|
1904
|
+
chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
|
|
1905
|
+
canvasScale
|
|
1906
|
+
});
|
|
748
1907
|
}
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
cwd,
|
|
753
|
-
input: vivliostyleInput,
|
|
754
|
-
output: [{ path: outputAbs, format }],
|
|
755
|
-
...metaFields,
|
|
756
|
-
logLevel,
|
|
757
|
-
...(options.debug ? { debug: true } : {}),
|
|
758
|
-
...extraConfig
|
|
759
|
-
};
|
|
760
|
-
dbg("final BuildConfig", config);
|
|
761
|
-
await build(config);
|
|
762
|
-
console.log(`✓ Document created: ${outputAbs}`);
|
|
1908
|
+
finally {
|
|
1909
|
+
htmlResource.cleanup();
|
|
1910
|
+
await server.close();
|
|
763
1911
|
}
|
|
764
|
-
|
|
1912
|
+
return;
|
|
765
1913
|
}
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
dbg("final PreviewConfig", config);
|
|
819
|
-
const shutdown = () => {
|
|
820
|
-
htmlCleanup();
|
|
821
|
-
process.exit(0);
|
|
822
|
-
};
|
|
823
|
-
process.once("SIGINT", shutdown);
|
|
824
|
-
process.once("SIGTERM", shutdown);
|
|
825
|
-
try {
|
|
826
|
-
await preview(config);
|
|
1914
|
+
// ── PREVIEW mode ─────────────────────────────────────────────────────────────
|
|
1915
|
+
{
|
|
1916
|
+
const preview = await startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraConfig);
|
|
1917
|
+
log.info(`[preview] ${preview.url}`);
|
|
1918
|
+
await openInBrowser(preview.url);
|
|
1919
|
+
await new Promise((resolvePromise) => {
|
|
1920
|
+
const stop = () => {
|
|
1921
|
+
process.off("SIGINT", stop);
|
|
1922
|
+
process.off("SIGTERM", stop);
|
|
1923
|
+
resolvePromise();
|
|
1924
|
+
};
|
|
1925
|
+
process.once("SIGINT", stop);
|
|
1926
|
+
process.once("SIGTERM", stop);
|
|
1927
|
+
});
|
|
1928
|
+
await preview.close();
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Serves the rewritten document next to the viewer and returns the URL to open.
|
|
1933
|
+
*
|
|
1934
|
+
* The viewer page lives in the document's own directory, so the preview shows
|
|
1935
|
+
* exactly what the PDF render would lay out.
|
|
1936
|
+
*/
|
|
1937
|
+
async function startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraConfig) {
|
|
1938
|
+
const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
|
|
1939
|
+
const viewerLibDir = resolveViewerLibDir();
|
|
1940
|
+
const entry = { localPath: null, sitePath };
|
|
1941
|
+
const server = await startStaticServer({
|
|
1942
|
+
staticMap,
|
|
1943
|
+
assetBases,
|
|
1944
|
+
entry,
|
|
1945
|
+
fetchMissing: htmlOptions.fetchMissing === true,
|
|
1946
|
+
viewerLibDir,
|
|
1947
|
+
viewerFilePath: join(viewerLibDir, "index.html"),
|
|
1948
|
+
log: (message) => log.info(message)
|
|
1949
|
+
});
|
|
1950
|
+
const prepared = buildPreviewHtml(inputAbs, assetBases, htmlOptions);
|
|
1951
|
+
entry.localPath = prepared.htmlPath;
|
|
1952
|
+
const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
|
|
1953
|
+
const documentUrl = `${server.baseUrl}${sitePath}`;
|
|
1954
|
+
const url = buildViewerUrl(viewerPageUrl, {
|
|
1955
|
+
src: documentUrl,
|
|
1956
|
+
bookMode: false,
|
|
1957
|
+
renderAllPages: false,
|
|
1958
|
+
...buildRenderViewerParams(extraConfig, htmlOptions)
|
|
1959
|
+
});
|
|
1960
|
+
return {
|
|
1961
|
+
url,
|
|
1962
|
+
documentUrl,
|
|
1963
|
+
close: async () => {
|
|
1964
|
+
prepared.cleanup();
|
|
1965
|
+
await server.close();
|
|
827
1966
|
}
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
1967
|
+
};
|
|
1968
|
+
}
|
|
1969
|
+
/** Opens a URL in the user's browser; preview mode is a plain server. */
|
|
1970
|
+
async function openInBrowser(url) {
|
|
1971
|
+
const { spawn } = await import('node:child_process');
|
|
1972
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
|
|
1973
|
+
try {
|
|
1974
|
+
const child = spawn(command, [url], { stdio: "ignore", detached: true });
|
|
1975
|
+
child.unref();
|
|
1976
|
+
}
|
|
1977
|
+
catch (err) {
|
|
1978
|
+
log.warn(`[preview] Could not open a browser: ${String(err)}`);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Viewer parameters for the render: layout overrides from `--` plus the options
|
|
1983
|
+
* the wrapper owns (page size, output resolution, user stylesheet).
|
|
1984
|
+
*/
|
|
1985
|
+
function buildRenderViewerParams(extraConfig, htmlOptions) {
|
|
1986
|
+
const params = {};
|
|
1987
|
+
if (typeof extraConfig.size === "string")
|
|
1988
|
+
params.size = extraConfig.size;
|
|
1989
|
+
if (typeof extraConfig.viewerParam === "string") {
|
|
1990
|
+
for (const pair of extraConfig.viewerParam.split("&")) {
|
|
1991
|
+
if (pair === "")
|
|
1992
|
+
continue;
|
|
1993
|
+
const eq = pair.indexOf("=");
|
|
1994
|
+
if (eq === -1)
|
|
1995
|
+
params[pair] = true;
|
|
1996
|
+
else
|
|
1997
|
+
params[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
835
1998
|
}
|
|
836
|
-
process.off("SIGINT", shutdown);
|
|
837
|
-
process.off("SIGTERM", shutdown);
|
|
838
|
-
htmlCleanup();
|
|
839
1999
|
}
|
|
2000
|
+
if (htmlOptions.css !== undefined)
|
|
2001
|
+
params.style = htmlOptions.css;
|
|
2002
|
+
if (htmlOptions.userStyle !== undefined)
|
|
2003
|
+
params.userStyle = htmlOptions.userStyle;
|
|
2004
|
+
return params;
|
|
840
2005
|
}
|
|
841
2006
|
// ---------------------------------------------------------------------------
|
|
842
2007
|
// Direct execution
|
|
843
2008
|
// ---------------------------------------------------------------------------
|
|
844
|
-
let _resolvedEntry = null;
|
|
845
|
-
try {
|
|
846
|
-
_resolvedEntry = resolve(fileURLToPath(import.meta.url));
|
|
847
|
-
}
|
|
848
|
-
catch {
|
|
849
|
-
// ESM import.meta.url not available — not a direct invocation
|
|
850
|
-
}
|
|
851
2009
|
function isDirectExecution() {
|
|
852
2010
|
const entry = process.argv[1];
|
|
853
|
-
if (!entry
|
|
2011
|
+
if (!entry)
|
|
854
2012
|
return false;
|
|
855
2013
|
try {
|
|
856
|
-
|
|
2014
|
+
const realEntry = realpathSync(entry);
|
|
2015
|
+
const realSelf = realpathSync(fileURLToPath(import.meta.url));
|
|
2016
|
+
return realEntry === realSelf;
|
|
857
2017
|
}
|
|
858
2018
|
catch {
|
|
859
2019
|
return false;
|
|
@@ -865,14 +2025,12 @@ if (isDirectExecution()) {
|
|
|
865
2025
|
}
|
|
866
2026
|
const parsed = parseArgs(process.argv);
|
|
867
2027
|
if (!parsed) {
|
|
868
|
-
|
|
869
|
-
}
|
|
870
|
-
else {
|
|
871
|
-
execute(parsed.options, parsed.extraArgs).catch((err) => {
|
|
872
|
-
console.error(err instanceof Error ? err.message : err);
|
|
873
|
-
process.exit(1);
|
|
874
|
-
});
|
|
2028
|
+
process.exit(0);
|
|
875
2029
|
}
|
|
2030
|
+
execute(parsed.options, parsed.extraArgs).catch((err) => {
|
|
2031
|
+
log.error(err instanceof Error ? err.message : String(err));
|
|
2032
|
+
process.exit(1);
|
|
2033
|
+
});
|
|
876
2034
|
}
|
|
877
2035
|
|
|
878
|
-
export { buildPreviewHtml, execute, extractUrlsFromHtml, isHtmlInput, mapAbsoluteUrlToLocal, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseStaticMapping, prepareInputHtmlForBuild, printHelp, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, splitArgsAtDoubleDash,
|
|
2036
|
+
export { EXPAND_DETAILS_SNIPPET, buildPreviewHtml, buildRuntimeScript, buildSettleGateImage, coerceExtraValue, collectRemoteReferences, collectUnservedVirtualPaths, createAssetBasePathProbe, deriveSitePath, dropRemoteReferencesInDom, dropUnavailableReferencesInDom, execute, extractUrlsFromHtml, injectRuntimeScriptInDom, isHtmlInput, isRemoteUrl, isStaticServerUrl, mapAbsoluteUrlToLocal, normalizeExtraKey, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseMetaRefreshTarget, parseStaticMapping, prepareInputHtmlForBuild, printHelp, probeRemoteReferences, referencesToProbe, resolveSettleGate, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteUrlAttributes, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, siteDirectory, splitArgsAtDoubleDash, startPreview, urlToStaticMapping };
|