@projektemacher/vivliostyle-batch-cli 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{LICENCE → LICENSE} +1 -1
- package/README.md +73 -30
- package/dist/index.d.ts +211 -42
- package/dist/vivliostyle-batch-cli.js +1557 -399
- package/package.json +31 -20
- package/src/render/chrome.ts +103 -0
- package/src/render/pdf.ts +306 -0
- package/src/render/viewer.ts +46 -0
- package/src/server.ts +300 -0
- package/src/vivliostyle-cli.ts +1164 -439
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@projektemacher/vivliostyle-batch-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A vivliostyle-cli with more options for batch processing",
|
|
6
6
|
"bin": {
|
|
7
|
-
"vivliostyle-
|
|
7
|
+
"vivliostyle-cli": "dist/vivliostyle-batch-cli.js"
|
|
8
8
|
},
|
|
9
9
|
"engines": {
|
|
10
10
|
"node": ">=20.0.0"
|
|
@@ -12,43 +12,54 @@
|
|
|
12
12
|
"scripts": {
|
|
13
13
|
"test": "npx vitest",
|
|
14
14
|
"build": "npx rimraf dist/* && npx rollup -c",
|
|
15
|
-
"start": "node dist/vivliostyle-cli.js",
|
|
15
|
+
"start": "node dist/vivliostyle-batch-cli.js",
|
|
16
16
|
"format": "npx prettier . --check",
|
|
17
17
|
"clean": "npx rimraf dist/*",
|
|
18
|
-
"lint": "npx tsc && eslint . -c eslint.config.mjs --report-unused-disable-directives --max-warnings 0"
|
|
18
|
+
"lint": "npx tsc && eslint . -c eslint.config.mjs --report-unused-disable-directives --max-warnings 0",
|
|
19
|
+
"site:collect": "node site/collect-manifest.mjs",
|
|
20
|
+
"site:dev": "node site/collect-manifest.mjs --sample && vite dev site",
|
|
21
|
+
"site:build": "vite build site"
|
|
19
22
|
},
|
|
20
23
|
"dependencies": {
|
|
21
|
-
"@vivliostyle/
|
|
22
|
-
"commander": "^
|
|
23
|
-
"
|
|
24
|
-
"
|
|
24
|
+
"@vivliostyle/viewer": "^2.45.2",
|
|
25
|
+
"commander": "^15.0.0",
|
|
26
|
+
"jsdom": "^30.1.2",
|
|
27
|
+
"loglevel": "^1.9.2",
|
|
25
28
|
"mime-types": "^3.0.2",
|
|
26
|
-
"
|
|
29
|
+
"pdf-lib": "^1.17.1",
|
|
30
|
+
"puppeteer-core": "^25.12.0"
|
|
27
31
|
},
|
|
28
32
|
"devDependencies": {
|
|
29
|
-
"@
|
|
33
|
+
"@puppeteer/browsers": "^3.2.4",
|
|
34
|
+
"@rollup/plugin-commonjs": "^29.0.3",
|
|
30
35
|
"@rollup/plugin-node-resolve": "^16.0.3",
|
|
31
36
|
"@rollup/plugin-typescript": "^12.3.0",
|
|
32
37
|
"@types/express": "^5.0.6",
|
|
33
|
-
"@types/jsdom": "^
|
|
38
|
+
"@types/jsdom": "^30.0.0",
|
|
34
39
|
"@types/mime-types": "^3.0.1",
|
|
35
|
-
"@types/node": "^
|
|
40
|
+
"@types/node": "^26.6.4",
|
|
36
41
|
"@types/serve-static": "^2.2.0",
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
42
|
+
"d3": "^7.9.0",
|
|
43
|
+
"echarts": "^6.1.0",
|
|
44
|
+
"eslint": "^10.12.0",
|
|
45
|
+
"globals": "^17.13.0",
|
|
46
|
+
"marked": "^18.1.0",
|
|
47
|
+
"openseadragon": "^6.1.1",
|
|
48
|
+
"prettier": "^3.9.9",
|
|
40
49
|
"rimraf": "^6.1.3",
|
|
41
|
-
"rollup": "^4.
|
|
42
|
-
"rollup-plugin-dts": "^6.
|
|
50
|
+
"rollup": "^4.64.0",
|
|
51
|
+
"rollup-plugin-dts": "^6.5.1",
|
|
52
|
+
"three": "^0.186.1",
|
|
43
53
|
"tslib": "^2.8.1",
|
|
44
54
|
"typescript": "^6.0.3",
|
|
45
|
-
"typescript-eslint": "^8.
|
|
46
|
-
"
|
|
55
|
+
"typescript-eslint": "^8.71.1",
|
|
56
|
+
"vite": "^8.3.4",
|
|
57
|
+
"vitest": "^5.0.3"
|
|
47
58
|
},
|
|
48
59
|
"license": "MIT",
|
|
49
60
|
"exports": {
|
|
50
61
|
"types": "./dist/index.d.ts",
|
|
51
|
-
"import": "./dist/vivliostyle-cli.js"
|
|
62
|
+
"import": "./dist/vivliostyle-batch-cli.js"
|
|
52
63
|
},
|
|
53
64
|
"files": [
|
|
54
65
|
"dist",
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// src/render/chrome.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Locates a Chrome/Chromium binary for the renderer.
|
|
8
|
+
*
|
|
9
|
+
* `--executable-browser` wins, then a binary installed by @puppeteer/browsers
|
|
10
|
+
* (the same cache Vivliostyle CLI used), then the usual system locations.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
14
|
+
import { homedir, platform } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
|
|
17
|
+
const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
|
|
18
|
+
const MAC_CHROMIUM = "/Applications/Chromium.app/Contents/MacOS/Chromium";
|
|
19
|
+
const LINUX_PATHS = [
|
|
20
|
+
"/usr/bin/google-chrome",
|
|
21
|
+
"/usr/bin/google-chrome-stable",
|
|
22
|
+
"/usr/bin/chromium",
|
|
23
|
+
"/usr/bin/chromium-browser",
|
|
24
|
+
"/snap/bin/chromium"
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
/** Directory @puppeteer/browsers installs into. */
|
|
28
|
+
export function puppeteerCacheDir(): string {
|
|
29
|
+
return process.env.PUPPETEER_CACHE_DIR ?? join(homedir(), ".cache", "puppeteer");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Finds an installed browser in the @puppeteer/browsers cache. */
|
|
33
|
+
export function findCachedBrowser(): string | null {
|
|
34
|
+
const root = join(puppeteerCacheDir(), "chrome");
|
|
35
|
+
if (!existsSync(root)) return null;
|
|
36
|
+
|
|
37
|
+
const candidates: string[] = [];
|
|
38
|
+
for (const build of readdirSync(root)) {
|
|
39
|
+
const buildDir = join(root, build);
|
|
40
|
+
let stat;
|
|
41
|
+
try {
|
|
42
|
+
stat = statSync(buildDir);
|
|
43
|
+
} catch {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (!stat.isDirectory()) continue;
|
|
47
|
+
|
|
48
|
+
for (const flavour of readdirSync(buildDir)) {
|
|
49
|
+
candidates.push(
|
|
50
|
+
join(buildDir, flavour, "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
|
|
51
|
+
join(buildDir, flavour, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
|
|
52
|
+
join(buildDir, flavour, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
|
|
53
|
+
join(buildDir, flavour, "chrome-linux64", "chrome"),
|
|
54
|
+
join(buildDir, flavour, "chrome-headless-shell-linux64", "chrome-headless-shell")
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function systemBrowser(): string | null {
|
|
63
|
+
const candidates = platform() === "darwin" ? [MAC_CHROME, MAC_CHROMIUM] : LINUX_PATHS;
|
|
64
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Path of the browser to launch, or `null` when none is installed.
|
|
69
|
+
*/
|
|
70
|
+
export function resolveBrowserExecutable(explicit?: string | undefined): string | null {
|
|
71
|
+
const candidates = [explicit, process.env.CHROME_PATH, findCachedBrowser(), systemBrowser()];
|
|
72
|
+
for (const candidate of candidates) {
|
|
73
|
+
if (candidate !== undefined && candidate !== null && candidate !== "" && existsSync(candidate)) return candidate;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Chrome flags for headless rendering.
|
|
80
|
+
*
|
|
81
|
+
* SwiftShader keeps WebGL (three.js, A-Frame) working without a GPU, and the
|
|
82
|
+
* ANGLE/WebGPU flags extend that to WebGPU on headless machines (best effort:
|
|
83
|
+
* pages report `navigator.gpu == null` when the build still lacks it).
|
|
84
|
+
* `--disable-web-security` lets the page load the cross-origin embeds it shows.
|
|
85
|
+
*/
|
|
86
|
+
export function chromeArgs(extra: string[] = []): string[] {
|
|
87
|
+
return [
|
|
88
|
+
"--disable-field-trial-config",
|
|
89
|
+
"--disable-back-forward-cache",
|
|
90
|
+
"--disable-component-update",
|
|
91
|
+
"--no-default-browser-check",
|
|
92
|
+
"--disable-features=AcceptCHFrame,AvoidUnnecessaryBeforeUnloadCheckSync,DestroyProfileInBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,MediaRouter,PaintHolding,ThirdPartyPartitioning,Translate,AutofillServerCommunication,DestroyProfileOnBrowserClose",
|
|
93
|
+
"--no-service-autorun",
|
|
94
|
+
"--enable-unsafe-swiftshader",
|
|
95
|
+
"--use-angle=swiftshader",
|
|
96
|
+
"--enable-unsafe-webgpu",
|
|
97
|
+
"--disable-web-security",
|
|
98
|
+
"--hide-scrollbars",
|
|
99
|
+
"--mute-audio",
|
|
100
|
+
"--force-device-scale-factor=1",
|
|
101
|
+
...extra
|
|
102
|
+
];
|
|
103
|
+
}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// src/render/pdf.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* PDF rendering on top of the Vivliostyle viewer and Chrome's print-to-PDF.
|
|
8
|
+
*
|
|
9
|
+
* The viewer page is served by our own static server (see src/server.ts), so
|
|
10
|
+
* the document's origin — and therefore the base URI of the scripts the page
|
|
11
|
+
* runs — is the site we serve, not an internal viewer base.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { dirname } from "node:path";
|
|
16
|
+
import puppeteer from "puppeteer-core";
|
|
17
|
+
import { PDFDocument } from "pdf-lib";
|
|
18
|
+
import log from "loglevel";
|
|
19
|
+
import { chromeArgs, resolveBrowserExecutable } from "./chrome.js";
|
|
20
|
+
|
|
21
|
+
export type ViewerParams = Record<string, string | number | boolean | undefined>;
|
|
22
|
+
|
|
23
|
+
/** URL of the viewer page, with the publication and layout parameters. */
|
|
24
|
+
export function buildViewerUrl(viewerPageUrl: string, params: ViewerParams): string {
|
|
25
|
+
const parts: string[] = [];
|
|
26
|
+
|
|
27
|
+
for (const [key, value] of Object.entries(params)) {
|
|
28
|
+
if (value === undefined || value === "") continue;
|
|
29
|
+
parts.push(`${key}=${String(value).replaceAll("&", "%26")}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const query = parts.join("&");
|
|
33
|
+
return query === "" ? viewerPageUrl : `${viewerPageUrl}#${query}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type RenderPdfRequest = {
|
|
37
|
+
/** Absolute URL of the document on our static server. */
|
|
38
|
+
documentUrl: string;
|
|
39
|
+
/** Absolute URL of the viewer page on our static server. */
|
|
40
|
+
viewerPageUrl: string;
|
|
41
|
+
/** Absolute path of the PDF to write. */
|
|
42
|
+
output: string;
|
|
43
|
+
viewerParams?: ViewerParams;
|
|
44
|
+
title?: string;
|
|
45
|
+
author?: string;
|
|
46
|
+
subject?: string;
|
|
47
|
+
keywords?: string;
|
|
48
|
+
language?: string;
|
|
49
|
+
/** Hard limit for the whole render. */
|
|
50
|
+
timeoutMs?: number;
|
|
51
|
+
/** Wait for the page to report that it settled before printing. */
|
|
52
|
+
waitForSettle?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Redraw canvas/WebGL content at `clientSize * canvasScale` backing pixels
|
|
55
|
+
* before printing (layout/CSS size unchanged). Values `<= 1` skip the step.
|
|
56
|
+
* Wired from `--pixel-ratio` so `--pixel-ratio 2` stays sharp past 96dpi.
|
|
57
|
+
*/
|
|
58
|
+
canvasScale?: number;
|
|
59
|
+
/** Pause after the upscale call so charts can repaint (default 500ms). */
|
|
60
|
+
canvasSettleMs?: number;
|
|
61
|
+
chromeExecutable?: string;
|
|
62
|
+
extraChromeArgs?: string[];
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export type RenderPdfResult = {
|
|
66
|
+
output: string;
|
|
67
|
+
bytes: number;
|
|
68
|
+
pageCount: number;
|
|
69
|
+
settle: { reason: string; waitedMs: number } | null;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
73
|
+
|
|
74
|
+
/** Writes the PDF and stamps the metadata Vivliostyle would have written. */
|
|
75
|
+
export async function writePdfWithMetadata(pdf: Uint8Array, meta: RenderPdfRequest): Promise<Uint8Array> {
|
|
76
|
+
const hasMetadata = meta.title !== undefined || meta.author !== undefined || meta.subject !== undefined || meta.language !== undefined;
|
|
77
|
+
if (!hasMetadata) return pdf;
|
|
78
|
+
|
|
79
|
+
const document = await PDFDocument.load(pdf, { updateMetadata: false });
|
|
80
|
+
if (meta.title !== undefined) document.setTitle(meta.title);
|
|
81
|
+
if (meta.author !== undefined) document.setAuthor(meta.author);
|
|
82
|
+
if (meta.subject !== undefined) document.setSubject(meta.subject);
|
|
83
|
+
if (meta.keywords !== undefined) document.setKeywords([meta.keywords]);
|
|
84
|
+
if (meta.language !== undefined) document.setLanguage(meta.language);
|
|
85
|
+
document.setProducer("vivliostyle-batch-cli");
|
|
86
|
+
document.setCreator("vivliostyle-batch-cli");
|
|
87
|
+
return document.save();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type SettleState = { reason: string; at: number };
|
|
91
|
+
|
|
92
|
+
export type FrameRenderCapability = {
|
|
93
|
+
url: string;
|
|
94
|
+
ready: boolean;
|
|
95
|
+
fixture: string | null;
|
|
96
|
+
webgl: boolean;
|
|
97
|
+
webgl2: boolean;
|
|
98
|
+
webgpu: boolean;
|
|
99
|
+
canvasCount: number;
|
|
100
|
+
canvases: string;
|
|
101
|
+
iframeCount: number;
|
|
102
|
+
dpr: number;
|
|
103
|
+
resized: string | null;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Runs inside one frame (viewer window or a document/iframe within it):
|
|
108
|
+
* scrolls JS-painted elements into view so out-of-process iframes rasterize,
|
|
109
|
+
* reports GPU capabilities and canvas sizes, and — when the page exposes the
|
|
110
|
+
* `window.__vivResize(factor)` hook — redraws at HiDPI backing resolution.
|
|
111
|
+
*
|
|
112
|
+
* Blindly rewriting `canvas.width` here would blank WebGL contexts without
|
|
113
|
+
* `preserveDrawingBuffer`, so generic canvases are left for the page to redraw
|
|
114
|
+
* via the dispatched `resize` event; only the explicit hook changes pixels.
|
|
115
|
+
*/
|
|
116
|
+
export function buildFrameProbeScript(factor: number): string {
|
|
117
|
+
return `(async function(factor){
|
|
118
|
+
function nextFrame(){ return new Promise(function(r){ requestAnimationFrame(function(){ requestAnimationFrame(r); }); }); }
|
|
119
|
+
var canvases = Array.prototype.slice.call(document.querySelectorAll("canvas"));
|
|
120
|
+
var iframes = Array.prototype.slice.call(document.querySelectorAll("iframe"));
|
|
121
|
+
canvases.forEach(function(c){ try{ c.scrollIntoView({block:"nearest"}); }catch(e){} });
|
|
122
|
+
iframes.forEach(function(f){ try{ f.scrollIntoView({block:"nearest"}); }catch(e){} });
|
|
123
|
+
function canvasSizes(){
|
|
124
|
+
return Array.prototype.slice.call(document.querySelectorAll("canvas")).map(function(c){
|
|
125
|
+
return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);
|
|
126
|
+
}).join(",");
|
|
127
|
+
}
|
|
128
|
+
var resized = null;
|
|
129
|
+
if (factor > 1 && typeof window.__vivResize === "function") {
|
|
130
|
+
try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
|
|
131
|
+
}
|
|
132
|
+
try { window.dispatchEvent(new Event("resize")); } catch(e){}
|
|
133
|
+
// Hooks like echarts re-init dispose the canvas synchronously; let layout
|
|
134
|
+
// settle a frame before measuring so sizes reflect the repainted state.
|
|
135
|
+
try { await nextFrame(); } catch(e){}
|
|
136
|
+
if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
|
|
137
|
+
var webgl = false, webgl2 = false;
|
|
138
|
+
try {
|
|
139
|
+
var t = document.createElement("canvas");
|
|
140
|
+
webgl = !!t.getContext("webgl");
|
|
141
|
+
var t2 = document.createElement("canvas");
|
|
142
|
+
webgl2 = !!t2.getContext("webgl2");
|
|
143
|
+
} catch(e){}
|
|
144
|
+
return {
|
|
145
|
+
url: String(location.href),
|
|
146
|
+
ready: window.__vivReady === true,
|
|
147
|
+
fixture: typeof window.__vivFixture === "string" ? window.__vivFixture : null,
|
|
148
|
+
webgl: webgl, webgl2: webgl2,
|
|
149
|
+
webgpu: typeof navigator !== "undefined" && "gpu" in navigator,
|
|
150
|
+
canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
|
|
151
|
+
iframeCount: document.querySelectorAll("iframe").length,
|
|
152
|
+
dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
|
|
153
|
+
resized: resized
|
|
154
|
+
};
|
|
155
|
+
})(${JSON.stringify(factor)})`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Best-effort capability + HiDPI pass over every frame before `page.pdf()`. */
|
|
159
|
+
export async function prepareForPrint(
|
|
160
|
+
page: {
|
|
161
|
+
frames: () => Array<{ evaluate: (script: string) => Promise<unknown> }>;
|
|
162
|
+
},
|
|
163
|
+
options: { canvasScale?: number; settleMs?: number } = {}
|
|
164
|
+
): Promise<FrameRenderCapability[]> {
|
|
165
|
+
const factor = options.settleMs !== undefined && options.canvasScale === undefined ? 1 : (options.canvasScale ?? 1);
|
|
166
|
+
const scale = Number.isFinite(factor) && factor > 1 ? factor : 1;
|
|
167
|
+
const script = buildFrameProbeScript(scale);
|
|
168
|
+
const out: FrameRenderCapability[] = [];
|
|
169
|
+
for (const frame of page.frames()) {
|
|
170
|
+
try {
|
|
171
|
+
out.push((await frame.evaluate(script)) as FrameRenderCapability);
|
|
172
|
+
} catch {
|
|
173
|
+
// Cross-origin embeds that refuse evaluation still print as pixels.
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (scale > 1) {
|
|
178
|
+
await new Promise((resolve) => setTimeout(resolve, options.settleMs ?? 500));
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** One-line summary for logs: capabilities per frame that owns content. */
|
|
184
|
+
export function summarizeCapabilities(caps: FrameRenderCapability[]): string {
|
|
185
|
+
return caps
|
|
186
|
+
.filter((c) => c.canvasCount > 0 || c.iframeCount > 0 || c.fixture !== null)
|
|
187
|
+
.map(
|
|
188
|
+
(c) =>
|
|
189
|
+
`${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
|
|
190
|
+
`webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
|
|
191
|
+
(c.resized !== null ? ` resized=[${c.resized}]` : "")
|
|
192
|
+
)
|
|
193
|
+
.join(" | ");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfResult> {
|
|
197
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
198
|
+
const executablePath = resolveBrowserExecutable(request.chromeExecutable);
|
|
199
|
+
|
|
200
|
+
if (executablePath === null) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
"No Chrome/Chromium found. Install one (e.g. `npx @puppeteer/browsers install chrome@stable`) or pass --executable-browser <path>."
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const viewerUrl = buildViewerUrl(request.viewerPageUrl, {
|
|
207
|
+
src: request.documentUrl,
|
|
208
|
+
bookMode: false,
|
|
209
|
+
renderAllPages: true,
|
|
210
|
+
...request.viewerParams
|
|
211
|
+
});
|
|
212
|
+
log.trace("viewerUrl", viewerUrl);
|
|
213
|
+
|
|
214
|
+
const browser = await puppeteer.launch({
|
|
215
|
+
executablePath,
|
|
216
|
+
headless: true,
|
|
217
|
+
args: chromeArgs(request.extraChromeArgs ?? []),
|
|
218
|
+
acceptInsecureCerts: true
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
const startedAt = Date.now();
|
|
222
|
+
let settle: RenderPdfResult["settle"] = null;
|
|
223
|
+
|
|
224
|
+
try {
|
|
225
|
+
const page = await browser.newPage();
|
|
226
|
+
page.setDefaultTimeout(timeoutMs);
|
|
227
|
+
page.setDefaultNavigationTimeout(timeoutMs);
|
|
228
|
+
|
|
229
|
+
page.on("pageerror", (err: unknown) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
|
|
230
|
+
// Viewer and page errors are the usual reason a render produces nothing.
|
|
231
|
+
page.on("console", (message) => {
|
|
232
|
+
const type = message.type();
|
|
233
|
+
if (type !== "error" && type !== "warn") return;
|
|
234
|
+
const where = message.location();
|
|
235
|
+
log.warn(`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`);
|
|
236
|
+
});
|
|
237
|
+
page.on("requestfailed", (request) => {
|
|
238
|
+
log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// Print media has to be active *before* the document loads: the page's print
|
|
242
|
+
// stylesheet is what gives JS-driven containers their size, and a chart that
|
|
243
|
+
// initialises against a zero-sized box never recovers.
|
|
244
|
+
await page.emulateMediaType("print");
|
|
245
|
+
|
|
246
|
+
await page.goto(viewerUrl, { waitUntil: "domcontentloaded" });
|
|
247
|
+
|
|
248
|
+
// The viewer's contract: coreViewer exists and has finished typesetting.
|
|
249
|
+
await page.waitForFunction(() => (window as { coreViewer?: unknown }).coreViewer !== undefined);
|
|
250
|
+
await page.waitForFunction(() => (window as { coreViewer?: { readyState?: string } }).coreViewer?.readyState === "complete", {
|
|
251
|
+
polling: 500
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
if (request.waitForSettle === true) {
|
|
255
|
+
const handle = await page.waitForFunction(
|
|
256
|
+
() => {
|
|
257
|
+
const settleState = (window as { __vivSettle?: { done?: boolean; reason?: string; at?: number } }).__vivSettle;
|
|
258
|
+
// Pages with mocked/measured async work set __vivReady when painted;
|
|
259
|
+
// Vivliostyle re-runs document scripts in the viewer context, so both
|
|
260
|
+
// live on the same window the renderer polls here.
|
|
261
|
+
const ready = (window as { __vivReady?: boolean }).__vivReady === true;
|
|
262
|
+
if (ready) return { reason: "ready", at: 0 };
|
|
263
|
+
return settleState?.done === true ? { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 } : false;
|
|
264
|
+
},
|
|
265
|
+
{ polling: 200, timeout: timeoutMs }
|
|
266
|
+
);
|
|
267
|
+
const state = (await handle.jsonValue()) as SettleState;
|
|
268
|
+
|
|
269
|
+
settle = { reason: state.reason, waitedMs: Date.now() - startedAt };
|
|
270
|
+
log.trace("settle", settle);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Iframes/canvas/WebGL/WebGPU rasterize as pixels in print-to-PDF: force
|
|
274
|
+
// off-screen frames to paint, redraw HiDPI-aware pages at backing scale.
|
|
275
|
+
try {
|
|
276
|
+
const caps = await prepareForPrint(page, {
|
|
277
|
+
canvasScale: request.canvasScale,
|
|
278
|
+
settleMs: request.canvasSettleMs
|
|
279
|
+
});
|
|
280
|
+
const summary = summarizeCapabilities(caps);
|
|
281
|
+
if (summary !== "") log.info(`[render] frames: ${summary}`);
|
|
282
|
+
if (caps.length > 0 && caps.every((c) => !c.webgpu)) {
|
|
283
|
+
log.trace("[render] WebGPU unavailable in this Chrome (best-effort software rendering)");
|
|
284
|
+
}
|
|
285
|
+
} catch (err) {
|
|
286
|
+
log.warn(`[render] pre-print probe failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const pdf = await page.pdf({
|
|
290
|
+
margin: { top: 0, bottom: 0, left: 0, right: 0 },
|
|
291
|
+
printBackground: true,
|
|
292
|
+
preferCSSPageSize: true,
|
|
293
|
+
tagged: true
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
const stamped = await writePdfWithMetadata(pdf, request);
|
|
297
|
+
mkdirSync(dirname(request.output), { recursive: true });
|
|
298
|
+
writeFileSync(request.output, stamped);
|
|
299
|
+
|
|
300
|
+
const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
|
|
301
|
+
|
|
302
|
+
return { output: request.output, bytes: stamped.length, pageCount, settle };
|
|
303
|
+
} finally {
|
|
304
|
+
await browser.close();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// src/render/viewer.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Locates the Vivliostyle viewer that renders the document.
|
|
8
|
+
*
|
|
9
|
+
* The viewer is served by our own static server (see src/server.ts) so that the
|
|
10
|
+
* document's origin — and with it the base URI of the scripts the page runs — is
|
|
11
|
+
* the site we serve.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
import { createRequire } from "node:module";
|
|
16
|
+
import { dirname, join, resolve } from "node:path";
|
|
17
|
+
|
|
18
|
+
const require = createRequire(import.meta.url);
|
|
19
|
+
|
|
20
|
+
/** Directory of `@vivliostyle/viewer/lib`, which holds index.html and assets. */
|
|
21
|
+
export function resolveViewerLibDir(): string {
|
|
22
|
+
const candidates: string[] = [];
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
candidates.push(dirname(require.resolve("@vivliostyle/viewer/package.json")));
|
|
26
|
+
} catch {
|
|
27
|
+
// fall through to the paths below
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
candidates.push(
|
|
31
|
+
resolve(dirname(fileURLOfSelf()), "../node_modules/@vivliostyle/viewer"),
|
|
32
|
+
"/usr/local/lib/node_modules/@vivliostyle/viewer",
|
|
33
|
+
"/usr/lib/node_modules/@vivliostyle/viewer"
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
for (const candidate of candidates) {
|
|
37
|
+
const libDir = join(candidate, "lib");
|
|
38
|
+
if (existsSync(join(libDir, "index.html"))) return libDir;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
throw new Error("Could not find @vivliostyle/viewer. Install it as a dependency of this package.");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function fileURLOfSelf(): string {
|
|
45
|
+
return new URL(import.meta.url).pathname;
|
|
46
|
+
}
|