174 lines
8.8 KiB
TypeScript
174 lines
8.8 KiB
TypeScript
import { spawn } from "node:child_process"
|
|
import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
|
import { homedir, tmpdir } from "node:os"
|
|
import { dirname, join } from "node:path"
|
|
import { pathToFileURL } from "node:url"
|
|
import { CliError, validationError } from "../../../core/errors.js"
|
|
import { pngDimensions, stitchPngBands, type PngBand } from "./png.js"
|
|
|
|
export const PNG_BAND_HEIGHT = 14_000
|
|
|
|
function executable(path: string | null | undefined): path is string {
|
|
if (!path) return false
|
|
try { accessSync(path, constants.X_OK); return statSync(path).isFile() } catch { return false }
|
|
}
|
|
|
|
function cachedHeadlessShells(): string[] {
|
|
const roots = [join(homedir(), "Library", "Caches", "ms-playwright"), join(homedir(), ".cache", "ms-playwright")]
|
|
if (process.env.LOCALAPPDATA) roots.push(join(process.env.LOCALAPPDATA, "ms-playwright"))
|
|
const candidates: string[] = []
|
|
for (const root of roots) {
|
|
if (!existsSync(root)) continue
|
|
for (const version of readdirSync(root, { withFileTypes: true })) {
|
|
if (!version.isDirectory() || !version.name.startsWith("chromium_headless_shell-")) continue
|
|
const versionRoot = join(root, version.name)
|
|
for (const platform of readdirSync(versionRoot, { withFileTypes: true })) {
|
|
if (!platform.isDirectory() || !platform.name.startsWith("chrome-headless-shell-")) continue
|
|
for (const name of ["chrome-headless-shell", "chrome-headless-shell.exe"]) {
|
|
const path = join(versionRoot, platform.name, name)
|
|
if (executable(path)) candidates.push(path)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
|
|
}
|
|
|
|
/** Dedicated headless shells avoid desktop Chrome startup/shutdown problems on headless hosts. */
|
|
export function findReportChrome(explicit?: string): string {
|
|
if (explicit) {
|
|
const path = Bun.which(explicit) ?? explicit
|
|
if (executable(path)) return path
|
|
throw validationError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定")
|
|
}
|
|
const candidates = [
|
|
Bun.which("chrome-headless-shell"), ...cachedHeadlessShells(),
|
|
...["google-chrome", "chromium", "chromium-browser", "chrome", "msedge"].map((name) => Bun.which(name)),
|
|
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
join(process.env.PROGRAMFILES || "C:/Program Files", "Google", "Chrome", "Application", "chrome.exe"),
|
|
join(process.env["PROGRAMFILES(X86)"] || "C:/Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe")
|
|
]
|
|
const path = candidates.find(executable)
|
|
if (!path) throw validationError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定")
|
|
return path
|
|
}
|
|
|
|
function chrome(binary: string, profile: string, args: string[], scaleFactor = 1): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn(binary, [
|
|
"--headless", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${profile}`,
|
|
"--no-first-run", "--no-default-browser-check", `--force-device-scale-factor=${scaleFactor}`,
|
|
"--run-all-compositor-stages-before-draw", ...args
|
|
], { stdio: ["ignore", "pipe", "pipe"] })
|
|
let title = "", tail = "", diagnostic = "", settled = false
|
|
const finish = (error?: Error) => {
|
|
if (settled) return
|
|
settled = true
|
|
clearTimeout(timeout)
|
|
if (error) reject(error); else resolve(title)
|
|
}
|
|
const timeout = setTimeout(() => {
|
|
child.kill("SIGKILL")
|
|
finish(new CliError("浏览器渲染超时。可通过 --chrome 指定可用的 Chrome/Chromium 或 chrome-headless-shell。", 1))
|
|
}, 60_000)
|
|
// dump-dom contains embedded images and can be very large. Retain only the measured title,
|
|
// including cross-chunk matches, rather than imposing a new buffer limit on report size.
|
|
child.stdout?.on("data", (chunk: Buffer) => {
|
|
if (!args.includes("--dump-dom")) return
|
|
const text = tail + chunk.toString()
|
|
for (const match of text.matchAll(/<title>PAGEH:(\d+)<\/title>/g)) title = `PAGEH:${match[1]}`
|
|
tail = text.slice(-256)
|
|
})
|
|
child.stderr?.on("data", (chunk: Buffer) => { diagnostic = (diagnostic + chunk.toString()).slice(-65_536) })
|
|
child.once("error", (error) => finish(new CliError(`报告浏览器执行失败:${error.message}`, 1)))
|
|
child.once("close", (code, signal) => finish(code === 0 ? undefined : new CliError(`报告浏览器执行失败:${diagnostic.trim() || `退出 ${code ?? signal}`}`, 1)))
|
|
})
|
|
}
|
|
|
|
/** 注入测量脚本,用 dump-dom 取文档真实高度,等待图片和公式字体加载。 */
|
|
async function measureHeight(html: string, width: number, binary: string, profile: string): Promise<number> {
|
|
const probe = join(dirname(html), "_measure.html")
|
|
const script = '<script>async function measureReport(){await document.fonts.ready;document.title="PAGEH:"+Math.ceil(document.documentElement.scrollHeight)}window.addEventListener("load",measureReport);setTimeout(measureReport,3000)</script>'
|
|
writeFileSync(probe, readFileSync(html, "utf8").replace("</body>", script + "</body>"))
|
|
const output = await chrome(binary, profile, [`--window-size=${width},1000`, "--virtual-time-budget=30000", "--dump-dom", pathToFileURL(probe).href])
|
|
const hits = [...output.matchAll(/PAGEH:(\d+)/g)]
|
|
const height = Number(hits.at(-1)?.[1])
|
|
if (!Number.isSafeInteger(height) || height <= 0) throw new CliError("量取页面高度失败,未生成 PNG。", 1)
|
|
return height
|
|
}
|
|
|
|
/** 位移样式放在所有样式之后,避免长图分带重复开头或丢失结尾。 */
|
|
export function offsetReportBand(html: string, offset: number): string {
|
|
return html.replace("</head>", `<style>body{margin-top:-${offset}px}</style></head>`)
|
|
}
|
|
|
|
async function renderPng(html: string, output: string, width: number, binary: string, profile: string) {
|
|
const height = await measureHeight(html, width, binary, profile)
|
|
const screenshot = async (source: string, destination: string, bandHeight: number) => {
|
|
await chrome(binary, profile, [`--screenshot=${destination}`, `--window-size=${width},${bandHeight}`, "--virtual-time-budget=30000", pathToFileURL(source).href])
|
|
const dimensions = pngDimensions(destination)
|
|
if (dimensions.width !== width || dimensions.height !== bandHeight) throw new CliError("浏览器截图尺寸与请求不一致,未发布 PNG。", 1)
|
|
}
|
|
if (height <= PNG_BAND_HEIGHT) {
|
|
await screenshot(html, output, height)
|
|
return
|
|
}
|
|
const bands: PngBand[] = []
|
|
const content = readFileSync(html, "utf8")
|
|
for (let offset = 0; offset < height; offset += PNG_BAND_HEIGHT) {
|
|
const bandHeight = Math.min(PNG_BAND_HEIGHT, height - offset)
|
|
const source = join(dirname(html), `_band${bands.length}.html`)
|
|
const file = join(dirname(html), `_band${bands.length}.png`)
|
|
writeFileSync(source, offsetReportBand(content, offset))
|
|
await screenshot(source, file, bandHeight)
|
|
bands.push({ file, height: bandHeight })
|
|
}
|
|
stitchPngBands(bands, width, height, output)
|
|
}
|
|
|
|
/** PNG 为完整长图;PDF 使用 Chrome 的 A4 打印管线,保留表头重复和行不跨页样式。 */
|
|
export async function renderBrowserArtifacts(html: string, formats: string[], width: number, binary: string, profile: string) {
|
|
const stem = html.slice(0, -".html".length)
|
|
if (formats.includes("png")) await renderPng(html, `${stem}.png`, width, binary, profile)
|
|
if (formats.includes("pdf")) {
|
|
await chrome(binary, profile, [`--print-to-pdf=${stem}.pdf`, "--no-pdf-header-footer", "--virtual-time-budget=30000", pathToFileURL(html).href])
|
|
if (!existsSync(`${stem}.pdf`) || statSync(`${stem}.pdf`).size === 0) throw new CliError("浏览器未生成 PDF 文件。", 1)
|
|
}
|
|
}
|
|
|
|
/** 渲染独立 HTML/SVG 图表为高清晰度 PNG 图片 Buffer(默认 4x 超高分屏/印刷级采样)。 */
|
|
export async function renderHtmlToImageBuffer(options: {
|
|
html: string;
|
|
width: number;
|
|
height: number;
|
|
scale?: number;
|
|
chrome?: string;
|
|
}): Promise<Buffer> {
|
|
const binary = findReportChrome(options.chrome)
|
|
const stage = mkdtempSync(join(tmpdir(), "seal-chart-render-"))
|
|
const profile = join(stage, "profile")
|
|
mkdirSync(profile, { mode: 0o700 })
|
|
const htmlFile = join(stage, "index.html")
|
|
const pngFile = join(stage, "output.png")
|
|
writeFileSync(htmlFile, options.html, "utf8")
|
|
try {
|
|
await chrome(
|
|
binary,
|
|
profile,
|
|
[
|
|
`--screenshot=${pngFile}`,
|
|
`--window-size=${options.width},${options.height}`,
|
|
"--virtual-time-budget=10000",
|
|
pathToFileURL(htmlFile).href
|
|
],
|
|
options.scale ?? 4
|
|
)
|
|
if (!existsSync(pngFile)) throw new CliError("Chrome 截图渲染失败,未产出图片文件。", 1)
|
|
return readFileSync(pngFile)
|
|
} finally {
|
|
rmSync(stage, { recursive: true, force: true })
|
|
}
|
|
}
|
|
|