clio.html32 0.0.0-stage → 0.1.1

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/src/build.mjs ADDED
@@ -0,0 +1,601 @@
1
+ // clio.html32 — Compile static sites and clio.css pages into pure HTML 3.2 + GIFs
2
+ // for vintage Classic Mac browsers (Netscape 3/4, IE 3-5, System 6/7, Mac OS 8/9).
3
+ import { chromium } from "playwright";
4
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, readdirSync, statSync, copyFileSync } from "node:fs";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
+ import { createHash } from "node:crypto";
7
+ import { join, dirname, relative, posix, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { createRequire } from "node:module";
10
+ import { encodeGif } from "./gif.mjs";
11
+ import { checkLinks } from "./checklinks.mjs";
12
+ import { downgradeHTML5, inlineStyleToHTML32 } from "./downgrade.mjs";
13
+ import { esc, imgMap, windowFrame, menuHTML, pageBody } from "./chrome.mjs";
14
+
15
+ const here = dirname(fileURLToPath(import.meta.url));
16
+ const flag = k => process.argv.includes("--" + k);
17
+ const arg = (k, d) => { const i = process.argv.indexOf("--" + k); return i > 0 ? process.argv[i + 1] : d; };
18
+
19
+ const SRC = arg("src");
20
+ const OUT = arg("out", join(process.cwd(), "dist-html32"));
21
+ const BASE = arg("base", "/");
22
+ const ORIGIN = arg("origin", "http://classicmac.top/");
23
+ const ERA = arg("era", "system7");
24
+ // Desktop colours and patterns are clio.css's --clio-desktop for each era. Window frames and menu bars
25
+ // are measured from clio.css at build time (measureFrame, measureMenus).
26
+ const ALL_ERAS = {
27
+ system6: { deskBg: "#808080", deskTile: "s6-desk.gif", css: "clio.css", layout: "bar" },
28
+ system7: { deskBg: "#888888", deskTile: "s7-desk.gif", css: "clio.css", layout: "bar" },
29
+ platinum: { deskBg: "#4a71ab", deskTile: "", css: "clio.css", layout: "bar" },
30
+ drawingboard: { deskBg: "#4a71ab", deskTile: "", css: "clio.css", layout: "bar" },
31
+ nextstep: { deskBg: "#555577", deskTile: "", css: "clio.nextstep.css", layout: "column" },
32
+ };
33
+ if (!ALL_ERAS[ERA]) { console.error(`--era must be one of: ${Object.keys(ALL_ERAS).join(", ")}`); process.exit(2); }
34
+ const ERA_CONFIG = ALL_ERAS[ERA];
35
+ // clio.css: --clio <file> for the build era, else this repository's dist/, else the installed clio.css package.
36
+ const cssPath = name => {
37
+ const local = join(here, "../../../dist", name);
38
+ if (existsSync(local)) return local;
39
+ try { return createRequire(import.meta.url).resolve(`clio.css/dist/${name}`); } catch { return local; }
40
+ };
41
+ const CLIO = arg("clio", cssPath(ERA_CONFIG.css));
42
+ const cssFor = era => era === ERA ? CLIO : cssPath(ALL_ERAS[era].css);
43
+ const DEPTH = arg("depth", ERA === "system6" ? "1bit" : "auto");
44
+ const STATIC_ONLY = flag("static-only");
45
+ const PRESET = arg("preset", "auto");
46
+ const CHECK_LINKS = flag("check-links");
47
+
48
+ if (!SRC) { console.error("--src <site dir> is required"); process.exit(2); }
49
+ if (!existsSync(CLIO)) { console.error(`clio.css not found at ${CLIO}`); process.exit(2); }
50
+
51
+ const W = 680, TW = W - 2 - 16;
52
+ const BUDGET = { bytes: 100 * 1024, images: 30 };
53
+ const SLICE = 320;
54
+
55
+ mkdirSync(OUT, { recursive: true });
56
+ for (const n of readdirSync(OUT)) rmSync(join(OUT, n), { recursive: true, force: true });
57
+ for (const d of ["g", "i", "art", "t", "f"]) mkdirSync(join(OUT, d), { recursive: true });
58
+ for (const a of ["sp.gif", "s7-desk.gif"]) copyFileSync(join(here, "assets", a), join(OUT, "art", a));
59
+ // Always emit s6-desk.gif so runtime ?era=system6 can use it too.
60
+ {
61
+ const b = Buffer.from([0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0]);
62
+ writeFileSync(join(OUT, "art", "s6-desk.gif"), encodeGif(b, 2, 2));
63
+ }
64
+ writeFileSync(join(OUT, "blank.html"), `<html><body bgcolor="${ERA_CONFIG.deskBg}"></body></html>\n`);
65
+
66
+ // ---- Source pages ----------------------------------------------------------------------------
67
+ // Skips dot files, node_modules and the output directory when --out is inside --src.
68
+ const outAbs = resolve(OUT);
69
+ const walk = d => readdirSync(d).flatMap(n => {
70
+ const p = join(d, n);
71
+ if (n.startsWith(".") || n === "node_modules" || resolve(p) === outAbs) return [];
72
+ return statSync(p).isDirectory() ? walk(p) : [p];
73
+ });
74
+ const files = walk(SRC);
75
+ const pagesSrc = files.filter(f => /\.html?$/i.test(f)).map(f => relative(SRC, f).split("\\").join("/")).sort();
76
+ const pageSet = new Set(pagesSrc);
77
+ const decode = buf => {
78
+ if (!buf.some(b => b > 127)) return { text: buf.toString("latin1"), enc: "us-ascii" };
79
+ const score = t => { const n = t.match(/[^\x00-\x7f]/g) || []; return n.filter(c => /[\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]/.test(c)).length / (n.length || 1); };
80
+ const gb = new TextDecoder("gb18030").decode(buf), b5 = new TextDecoder("big5").decode(buf);
81
+ return score(b5) > score(gb) + 0.1 ? { text: b5, enc: "big5" } : { text: gb, enc: "gb2312" };
82
+ };
83
+ const encodeOut = (s, enc) => enc === "us-ascii"
84
+ ? Buffer.from(s.replace(/[^\x00-\x7f]/g, c => `&#${c.codePointAt(0)};`), "latin1")
85
+ : spawnSync("iconv", ["-c", "-f", "UTF-8", "-t", enc === "big5" ? "BIG5" : "GB18030"], { input: s, maxBuffer: 1 << 26 }).stdout;
86
+
87
+ // ---- Renderer --------------------------------------------------------------------------------
88
+ const browser = await chromium.launch();
89
+ const ctxB = await browser.newContext({ deviceScaleFactor: 1, viewport: { width: 1400, height: 1000 } });
90
+ const chrome = await ctxB.newPage();
91
+ const reading = `
92
+ .doc { width:${TW}px; font-family:var(--clio-font-text); font-size:12px; line-height:16px; color:#000; background:#fff; }
93
+ .doc a[href] { color:#0000cc; text-decoration:underline; }
94
+ .doc h1 { font-family:var(--clio-font-chrome); font-size:24px; line-height:28px; margin:4px 0 12px; }
95
+ .doc h2 { font-family:var(--clio-font-chrome); font-size:16px; line-height:20px; margin:16px 0 8px; }
96
+ .doc h3, .doc h4, .doc h5, .doc h6 { font-family:var(--clio-font-chrome); font-size:12px; line-height:16px; margin:12px 0 4px; }
97
+ .doc p, .doc ul, .doc ol, .doc table, .doc pre, .doc dl, .doc .run { margin:0 0 12px; }
98
+ .doc ul, .doc ol { padding-left:24px; }
99
+ .doc li { margin:0; }
100
+ .doc b, .doc strong { font-weight:normal; text-shadow:1px 0 0 currentColor; }
101
+ .doc pre { font-family:var(--clio-font-mono, monospace); white-space:pre-wrap; }
102
+ .doc img { max-width:${TW}px; height:auto; }
103
+ .doc table { border-collapse:separate; }
104
+ .doc td, .doc th { vertical-align:top; }
105
+ .doc * { max-width:${TW}px; }
106
+ `;
107
+ const renderHtmlPath = join(OUT, ".render.tmp.html");
108
+ const docHtmlPath = join(OUT, ".doc.tmp.html");
109
+ const shellFor = era => `<!doctype html><html lang="zh-CN" data-era="${era}"><head><meta charset="utf-8">
110
+ <link rel="stylesheet" href="file://${cssFor(era)}"><style>${reading}</style></head>
111
+ <body style="margin:0;padding:20px;background:#fff"><div id="stage"></div></body></html>`;
112
+ async function loadEra(era) {
113
+ writeFileSync(renderHtmlPath, shellFor(era));
114
+ await chrome.goto("file://" + renderHtmlPath);
115
+ await chrome.evaluate(() => document.fonts.ready);
116
+ }
117
+ await loadEra(ERA);
118
+
119
+ const ffmpegGif = (png, colors = 256) => execFileSync("ffmpeg", ["-loglevel", "error", "-f", "png_pipe", "-i", "-",
120
+ "-vf", `split[a][b];[a]palettegen=max_colors=${colors}:reserve_transparent=0:stats_mode=full[p];[b][p]paletteuse=dither=none`, "-f", "gif", "-"], { input: png, maxBuffer: 1 << 28 });
121
+ const rawOf = png => execFileSync("ffmpeg", ["-loglevel", "error", "-f", "png_pipe", "-i", "-", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { input: png, maxBuffer: 1 << 28 });
122
+ const gifOfRaw = (raw, w, h, png) => encodeGif(raw, w, h) || ffmpegGif(png);
123
+ const gifBytes = new Map();
124
+ function store(gif) {
125
+ const hash = createHash("sha1").update(gif).digest("hex").slice(0, 16), url = `${BASE}g/${hash}.gif`;
126
+ if (!gifBytes.has(url)) { writeFileSync(join(OUT, "g", hash + ".gif"), gif); gifBytes.set(url, gif.length); }
127
+ return url;
128
+ }
129
+ const pngOfRaw = (raw, w, h) => execFileSync("ffmpeg", ["-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", `${w}x${h}`, "-i", "-", "-f", "image2pipe", "-vcodec", "png", "-"], { input: raw, maxBuffer: 1 << 28 });
130
+
131
+ const memo = new Map();
132
+ let stageQueue = Promise.resolve();
133
+ const withStage = fn => {
134
+ const next = stageQueue.then(fn, fn);
135
+ stageQueue = next.catch(() => {});
136
+ return next;
137
+ };
138
+ async function snapHTML(key, html, width = 0) {
139
+ if (memo.has(key)) return memo.get(key);
140
+ return withStage(async () => {
141
+ if (memo.has(key)) return memo.get(key);
142
+ await chrome.evaluate(([h, w]) => { document.getElementById("stage").innerHTML = `<div id="t" class="clio" style="display:inline-block;background:#fff;vertical-align:top;${w ? `width:${w}px;` : ""}">${h}</div>`; }, [html, width]);
143
+ await chrome.evaluate(() => document.fonts.ready);
144
+ const r = await chrome.evaluate(() => {
145
+ const t = document.getElementById("t").getBoundingClientRect();
146
+ const areas = [...document.querySelectorAll("#t [data-href]")].flatMap(a => [...a.getClientRects()].map(b => ({ href: a.dataset.href, alt: a.textContent.trim(), x: Math.floor(b.x - t.x), y: Math.floor(b.y - t.y), w: Math.ceil(b.width), h: Math.ceil(b.height) })));
147
+ return { x: t.x, y: t.y, w: Math.ceil(t.width), h: Math.ceil(t.height), areas };
148
+ });
149
+ const png = await chrome.screenshot({ clip: { x: r.x, y: r.y, width: r.w, height: r.h } });
150
+ const out = { url: store(gifOfRaw(rawOf(png), r.w, r.h, png)), w: r.w, h: r.h, areas: r.areas };
151
+ memo.set(key, out); return out;
152
+ });
153
+ }
154
+ // ---- Window frames, measured from clio.css ----------------------------------------------------
155
+ const hex = (raw, W, x, y) => { const o = (y * W + x) * 3; return "#" + [raw[o], raw[o + 1], raw[o + 2]].map(v => v.toString(16).padStart(2, "0")).join(""); };
156
+ function crop(raw, W, x, y, w, h) {
157
+ const rows = Buffer.alloc(w * h * 3);
158
+ for (let r = 0; r < h; r++) raw.copy(rows, r * w * 3, ((y + r) * W + x) * 3, ((y + r) * W + x + w) * 3);
159
+ return { url: store(encodeGif(rows, w, h) || ffmpegGif(pngOfRaw(rows, w, h))), w, h };
160
+ }
161
+ // One clio.css window drawn on magenta, so whatever is not magenta around it is its shadow.
162
+ async function windowShot(title, active, width) {
163
+ await chrome.evaluate(([t, a, w]) => {
164
+ document.getElementById("stage").innerHTML = `<div id="wrap" style="display:inline-block;padding:12px;background:#ff00ff"><div class="window${a ? "" : " inactive"}" style="width:${w}px;margin:0"><div class="title-bar"><button class="close" aria-label="Close"></button><h3 class="title"></h3><button class="resize" aria-label="Zoom"></button></div><div class="window-pane" style="height:120px"></div></div></div>`;
165
+ document.querySelector("#wrap .title").textContent = t;
166
+ }, [title, active, width]);
167
+ await chrome.evaluate(() => document.fonts.ready);
168
+ const g = await chrome.evaluate(() => {
169
+ const n = v => Math.round(parseFloat(v) || 0), R = e => e.getBoundingClientRect();
170
+ const wrap = document.getElementById("wrap"), win = wrap.querySelector(".window"), pane = wrap.querySelector(".window-pane");
171
+ const W = R(wrap), r = R(win), p = R(pane), cs = getComputedStyle(win), ps = getComputedStyle(pane);
172
+ return {
173
+ clip: { x: Math.round(W.x), y: Math.round(W.y), width: Math.round(W.width), height: Math.round(W.height) },
174
+ x: Math.round(r.x - W.x), y: Math.round(r.y - W.y), w: Math.round(r.width), h: Math.round(r.height), b: n(cs.borderTopWidth),
175
+ px: Math.round(p.x - W.x) + n(ps.borderLeftWidth), py: Math.round(p.y - W.y) + n(ps.borderTopWidth),
176
+ pr: Math.round(p.right - W.x) - n(ps.borderRightWidth), pb: Math.round(p.bottom - W.y) - n(ps.borderBottomWidth),
177
+ };
178
+ });
179
+ const png = await chrome.screenshot({ clip: g.clip });
180
+ return { ...g, raw: rawOf(png), W: g.clip.width };
181
+ }
182
+ // Frame of an era: border width and colour, the bands between border and pane (one colour per
183
+ // pixel column, sampled halfway down the pane), and the 1px drop shadow if the era has one.
184
+ const frames = {};
185
+ async function measureFrame(era) {
186
+ if (frames[era]) return frames[era];
187
+ const fr = { border: 0, borderColor: {}, bandL: {}, bandR: {}, shadow: {}, paper: "#ffffff" };
188
+ for (const [s, active] of [["a", true], ["i", false]]) {
189
+ const g = await withStage(() => windowShot("x", active, 200));
190
+ const px = (x, y) => hex(g.raw, g.W, x, y), mid = g.py + 60, ix = g.x + g.b, ir = g.x + g.w - g.b;
191
+ fr.border = g.b;
192
+ fr.borderColor[s] = g.b ? px(g.x, mid) : "";
193
+ fr.bandL[s] = Array.from({ length: Math.max(0, g.px - ix) }, (_, k) => px(ix + k, mid));
194
+ fr.bandR[s] = Array.from({ length: Math.max(0, ir - g.pr) }, (_, k) => px(g.pr + k, mid));
195
+ const sh = px(g.x + g.w, mid);
196
+ fr.shadow[s] = sh === "#ff00ff" ? "" : sh;
197
+ }
198
+ return (frames[era] = fr);
199
+ }
200
+ // Head (title bar down to the pane) and foot (below the pane: size box, resize bar) of one window.
201
+ const winKey = (title, active, width) => createHash("sha1").update(`${title}|${active ? 1 : 0}|${width}`).digest("hex").slice(0, 10);
202
+ const titleSpecs = new Map(); // winKey -> { title, active, width }
203
+ async function titleParts(era, title, active, width) {
204
+ const key = `parts|${era}|${active}|${width}|${title}`;
205
+ if (memo.has(key)) return memo.get(key);
206
+ return withStage(async () => {
207
+ if (memo.has(key)) return memo.get(key);
208
+ const g = await windowShot(title, active, width);
209
+ const ix = g.x + g.b, iy = g.y + g.b, iw = g.w - 2 * g.b, ib = g.y + g.h - g.b;
210
+ const out = { head: crop(g.raw, g.W, ix, iy, iw, g.py - iy), foot: ib > g.pb ? crop(g.raw, g.W, ix, g.pb, iw, ib - g.pb) : null };
211
+ memo.set(key, out); return out;
212
+ });
213
+ }
214
+ const isClassicMacSite = PRESET === "classicmac" || (PRESET === "auto" && pageSet.has("index.html") && decode(readFileSync(join(SRC, "index.html"))).text.includes("犄角旮旯"));
215
+ const staticOrHome = target => (pageSet.has(target) || (isClassicMacSite && target === "fonts.html")) ? `${BASE}${target}` : `${BASE}index.html`;
216
+ // Carefully partitioned menu items with zero duplicates across all 5 menus.
217
+ const MENU_DEFS = [
218
+ { key: "file", label: "文件", alt: "File", staticHref: () => `${BASE}index.html`, items: [
219
+ { label: "主页", alt: "Home", href: `${BASE}index.html` },
220
+ { label: "原站页面", alt: "Original Page", href: "__ORIGIN_PAGE__" },
221
+ { sep: true },
222
+ { label: "关闭菜单", alt: "Close Menu", href: "__CLOSE_MENU__" },
223
+ ]},
224
+ { key: "edit", label: "编辑", alt: "Edit", staticHref: () => staticOrHome("fonts.html"), items: [
225
+ { label: "文字模式可全选与复制", alt: "Select and Copy in Text Mode", disabled: true },
226
+ { sep: true },
227
+ { label: "窗口切换:点非活动标题栏", alt: "Click Inactive Title Bar", disabled: true },
228
+ ]},
229
+ { key: "view", label: "显示", alt: "View", staticHref: (p, mode) => mode === "img" ? `${BASE}t/${p}` : `${BASE}${p}`, items: [
230
+ { label: "以图片显示", alt: "Show Pictures", href: "__IMG_MODE__" },
231
+ { label: "以文字显示", alt: "Show Text", href: "__TEXT_MODE__" },
232
+ { label: "English 版", alt: "English", href: `${BASE}index_en.html` },
233
+ { sep: true },
234
+ { label: "System 6 (1-bit)", alt: "System 6", href: "__ERA_system6__" },
235
+ { label: "System 7", alt: "System 7", href: "__ERA_system7__" },
236
+ { label: "Mac OS 8/9 (Platinum)", alt: "Platinum", href: "__ERA_platinum__" },
237
+ { label: "Drawing Board", alt: "Drawing Board", href: "__ERA_drawingboard__" },
238
+ { label: "NeXTSTEP", alt: "NeXTSTEP", href: "__ERA_nextstep__" },
239
+ ]},
240
+ { key: "special", label: "特殊", alt: "Special", staticHref: () => staticOrHome("software.html"), items: [
241
+ { label: "入门", alt: "Beginner", href: `${BASE}beginner.html` },
242
+ { label: "硬件指南", alt: "Hardware", href: `${BASE}hardware.html` },
243
+ { label: "软件指南", alt: "Software", href: `${BASE}software.html` },
244
+ { label: "Mac OS X 专区", alt: "Mac OS X", href: `${BASE}macosx/index.html` },
245
+ ]},
246
+ { key: "help", label: "帮助", alt: "Help", staticHref: () => staticOrHome("help.html"), items: [
247
+ { label: "Mac 帮助", alt: "Mac Help", href: `${BASE}help.html` },
248
+ { label: "安装中文字体", alt: "Install Chinese Fonts", href: `${BASE}fonts.html` },
249
+ { sep: true },
250
+ { label: "关于本站", alt: "About", href: `${BASE}about.html` },
251
+ ]},
252
+ ];
253
+ // Menu bar of an era, closed and with each menu open. Mac OS eras: a bar across the top, cut after
254
+ // the last title; the page fills the rest with the bar's own colour. NeXTSTEP: the main menu panel.
255
+ async function measureMenus(era) {
256
+ const layout = ALL_ERAS[era].layout, col = layout === "column";
257
+ const defs = MENU_DEFS.map(({ key, label, alt, items }) => ({ key, label, alt, items }));
258
+ const shoot = async clip => { const png = await chrome.screenshot({ clip }); return { url: store(gifOfRaw(rawOf(png), clip.width, clip.height, png)), w: clip.width, h: clip.height }; };
259
+ const draw = async active => {
260
+ await chrome.evaluate(([defs, activeKey, col]) => {
261
+ const lis = defs.map(d => {
262
+ const btn = open => `<button role="menuitem"${col ? ` aria-haspopup="true"` : ""}${open ? ` aria-expanded="true"` : ""}>${d.label}</button>`;
263
+ if (d.key !== activeKey) return `<li role="none">${btn(false)}</li>`;
264
+ const sub = d.items.map(it => it.sep ? `<li role="separator"></li>` : `<li role="none"><button role="menuitem"${it.disabled ? ` aria-disabled="true"` : ""}>${it.label}</button></li>`).join("");
265
+ return `<li role="none" class="open">${btn(true)}<ul class="menu" role="menu"${col ? ` aria-label="${d.label}"` : ""}>${sub}</ul></li>`;
266
+ }).join("");
267
+ document.getElementById("stage").innerHTML = `<div style="padding-bottom:300px;width:1100px"><ul class="menu-bar" role="menubar"${col ? ` aria-label="Classic Mac"` : ` style="width:1000px"`}>${lis}</ul></div>`;
268
+ }, [defs, active, col]);
269
+ await chrome.evaluate(() => document.fonts.ready);
270
+ return chrome.evaluate(([defs, activeKey, col]) => {
271
+ const m = document.querySelector(".menu-bar").getBoundingClientRect();
272
+ const btns = [...document.querySelectorAll(".menu-bar > li > button")];
273
+ const h = col ? Math.round(m.height) : Math.round(m.height) - 1;
274
+ const w = col ? Math.round(m.width) : Math.ceil(btns[btns.length - 1].getBoundingClientRect().right - m.x);
275
+ const boxes = btns.map((b, i) => {
276
+ const r = b.getBoundingClientRect();
277
+ return { key: defs[i].key, alt: defs[i].alt, x: Math.floor(r.x - m.x), y: col ? Math.floor(r.y - m.y) : 0, w: Math.ceil(r.width), h: col ? Math.ceil(r.height) : h };
278
+ });
279
+ const out = { bar: { x: Math.round(m.x), y: Math.round(m.y), width: w, height: h }, boxes,
280
+ full: { x: Math.round(m.x), y: Math.round(m.y), width: Math.round(m.width), height: Math.round(m.height) } };
281
+ const drop = activeKey && document.querySelector(".menu-bar .menu");
282
+ if (drop) {
283
+ const dr = drop.getBoundingClientRect(), items = [...drop.querySelectorAll(":scope > li")], areas = [];
284
+ defs.find(d => d.key === activeKey).items.forEach((it, k) => {
285
+ if (it.sep || it.disabled || !it.href) return;
286
+ const r = items[k].getBoundingClientRect();
287
+ areas.push({ href: it.href, alt: it.alt, x: Math.floor(r.x - dr.x), y: Math.floor(r.y - dr.y), w: Math.ceil(r.width), h: Math.ceil(r.height) });
288
+ });
289
+ out.drop = { clip: { x: Math.round(dr.x), y: Math.round(dr.y), width: Math.ceil(dr.width), height: Math.ceil(dr.height) },
290
+ offsetX: Math.round(dr.x - m.x), offsetY: Math.round(dr.y - m.y), areas };
291
+ }
292
+ return out;
293
+ }, [defs, active, col]);
294
+ };
295
+ return withStage(async () => {
296
+ const closed = await draw("");
297
+ const full = rawOf(await chrome.screenshot({ clip: closed.full })), fw = closed.full.width;
298
+ const barFill = col ? "" : hex(full, fw, fw - 10, 2);
299
+ const barLine = col ? "" : hex(full, fw, fw - 10, closed.full.height - 1);
300
+ const closedBar = { ...(await shoot(closed.bar)), boxes: closed.boxes };
301
+ const menus = {};
302
+ for (const d of defs) {
303
+ const o = await draw(d.key);
304
+ menus[d.key] = {
305
+ bar: { ...(await shoot(o.bar)), areas: o.boxes.map(b => ({ href: b.key === d.key ? "__CLOSE_MENU__" : `?menu=${b.key}`, alt: b.alt, x: b.x, y: b.y, w: b.w, h: b.h })) },
306
+ drop: { ...(await shoot(o.drop.clip)), offsetX: o.drop.offsetX, offsetY: o.drop.offsetY, areas: o.drop.areas },
307
+ };
308
+ }
309
+ return { layout, barFill, barLine, closedBar, menus };
310
+ });
311
+ }
312
+ // All eras for the edge worker's ?era= switch: frames, menus and the head/foot of every window built.
313
+ async function exportEras() {
314
+ if (STATIC_ONLY) return;
315
+ const eras = {};
316
+ for (const [name, cfg] of Object.entries(ALL_ERAS)) {
317
+ if (!existsSync(cssFor(name))) continue;
318
+ await loadEra(name);
319
+ const frame = await measureFrame(name), m = await measureMenus(name), titles = {};
320
+ for (const [k, t] of titleSpecs) titles[k] = await titleParts(name, t.title, t.active, t.width);
321
+ eras[name] = { deskBg: cfg.deskBg, deskTile: cfg.deskTile ? `${BASE}art/${cfg.deskTile}` : "", frame, ...m, titles };
322
+ }
323
+ writeFileSync(join(OUT, "art", "eras.json"), JSON.stringify({ default: ERA, eras }));
324
+ }
325
+
326
+ // ---- HTML 3.2 building blocks --------------------------------------------------------------
327
+ const hEsc = s => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;");
328
+ const sp = (w, h) => `<img src="${BASE}art/sp.gif" width=${w} height=${h} alt="">`;
329
+ let mapSeq = 0;
330
+ const TOP = ` target="_top"`;
331
+ const img = (b, alt = "") => imgMap(b, { alt, name: `m${++mapSeq}` });
332
+ let FRAME, ERA_MENUS;
333
+ async function windowHTML({ title, width, active, body, titleHref = "" }) {
334
+ const key = winKey(title, active, width);
335
+ titleSpecs.set(key, { title, active, width });
336
+ const { head, foot } = await titleParts(ERA, title, active, width);
337
+ return windowFrame(FRAME, { key, width, active, head, foot, body, titleHref, alt: title, sp });
338
+ }
339
+ function closedMenu(pagePath, mode) {
340
+ const M = ERA_MENUS, fullPage = `${BASE}${mode === "text" ? "t/" : ""}${pagePath}`;
341
+ const bar = { ...M.closedBar, areas: M.closedBar.boxes.map((b, i) => ({
342
+ href: STATIC_ONLY ? MENU_DEFS[i].staticHref(pagePath, mode) : `${fullPage}?menu=${b.key}`, alt: b.alt, x: b.x, y: b.y, w: b.w, h: b.h })) };
343
+ return menuHTML(M, { layout: M.layout, bar, sp });
344
+ }
345
+ async function pageShell(title, inner, charset, pagePath = "index.html", mode = "img") {
346
+ const bgAttr = ERA_CONFIG.deskTile ? ` background="${BASE}art/${ERA_CONFIG.deskTile}"` : "";
347
+ return `<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
348
+ <html><head><meta http-equiv="Content-Type" content="text/html; charset=${charset}"><title>${hEsc(title)}</title></head>
349
+ <body bgcolor="${ERA_CONFIG.deskBg}"${bgAttr} text="#000000" link="#0000cc" vlink="#551a8b" topmargin=0 leftmargin=0 marginwidth=0 marginheight=0>
350
+ ${pageBody(ERA_MENUS.layout, closedMenu(pagePath, mode), inner, sp)}
351
+ </body></html>
352
+ `;
353
+ }
354
+ const indent = inner => `<table border=0 cellspacing=0 cellpadding=0><tr><td>${sp(16, 1)}</td><td valign=top>${inner}</td></tr></table>`;
355
+
356
+ // ---- Paths and links -------------------------------------------------------------------------
357
+ const pic = p => BASE + p, txt = p => BASE + "t/" + p;
358
+ const parts = new Map();
359
+ const anchorsAt = new Map();
360
+ const partName = (p, i) => i === 0 ? p : p.replace(/(\.html?)$/i, `_${i + 1}$1`);
361
+ function resolveHref(href, from, mode) {
362
+ href = href.trim();
363
+ if (!href || /^(javascript|data):/i.test(href)) return null;
364
+ if (/^[a-z][\w+.-]*:/i.test(href)) return href;
365
+ const [pathPart, frag] = href.split("#");
366
+ const target = pathPart ? posix.normalize(posix.join(posix.dirname(from), pathPart)).replace(/^\.\//, "") : from;
367
+ if (pageSet.has(target) || target === "fonts.html") {
368
+ let file = target;
369
+ if (mode === "img" && frag && anchorsAt.get(target)?.has(frag)) file = partName(target, anchorsAt.get(target).get(frag));
370
+ return (mode === "img" ? pic(file) : txt(file)) + (frag ? "#" + frag : "");
371
+ }
372
+ if (target.startsWith("..")) return null;
373
+ return ORIGIN + target + (frag ? "#" + frag : "");
374
+ }
375
+
376
+ // ---- Content images (converted to GIF, width <= TW) ------------------------------------------
377
+ const imgDone = new Map();
378
+ function contentImage(srcPath, maxW = TW) {
379
+ const key = srcPath + "|" + maxW;
380
+ if (imgDone.has(key)) return imgDone.get(key);
381
+ const file = join(SRC, srcPath);
382
+ if (!existsSync(file)) { imgDone.set(key, null); return null; }
383
+ const probe = execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]).toString().trim().split(",").map(Number);
384
+ let [w, h] = probe; if (w > maxW) { h = Math.round(h * maxW / w); w = maxW; }
385
+ const outRel = "i/" + srcPath.replace(/\.[^.]+$/, "") + (maxW !== TW ? `.${maxW}` : "") + ".gif";
386
+ mkdirSync(dirname(join(OUT, outRel)), { recursive: true });
387
+ if (/\.gif$/i.test(srcPath) && w === probe[0] && DEPTH !== "1bit") copyFileSync(file, join(OUT, outRel));
388
+ else {
389
+ const vf = DEPTH === "1bit"
390
+ ? `scale=${w}:${h}:flags=area,format=gray,split[a][b];[a]palettegen=max_colors=2:stats_mode=full[p];[b][p]paletteuse=dither=floyd_steinberg`
391
+ : `scale=${w}:${h}:flags=area,split[a][b];[a]palettegen=max_colors=${DEPTH === "16" ? 16 : 64}:stats_mode=full[p];[b][p]paletteuse=dither=bayer:bayer_scale=3`;
392
+ writeFileSync(join(OUT, outRel), execFileSync("ffmpeg", ["-loglevel", "error", "-i", file, "-vf", vf, "-f", "gif", "-"], { maxBuffer: 1 << 28 }));
393
+ }
394
+ const out = { url: BASE + outRel, w, h, bytes: statSync(join(OUT, outRel)).size };
395
+ imgDone.set(key, out); return out;
396
+ }
397
+
398
+ // ---- Layout one source page in Chromium and cut it into segments ----------------------------
399
+ const doc = await ctxB.newPage();
400
+ async function layout(srcPath, html) {
401
+ const clean = downgradeHTML5(html);
402
+ const body = (clean.match(/<body[^>]*>([\s\S]*)<\/body>/i) || [, clean])[1];
403
+ writeFileSync(docHtmlPath, `<!doctype html><html lang="zh-CN" data-era="${ERA}"><head><meta charset="utf-8"><base href="file://${join(SRC, dirname(srcPath))}/">
404
+ <link rel="stylesheet" href="file://${CLIO}"><style>${reading}</style></head><body style="margin:0;padding:20px;background:#ffffff"><div class="doc clio" id="doc">${body}</div></body></html>`);
405
+ await doc.goto("file://" + docHtmlPath, { waitUntil: "load" });
406
+ await doc.evaluate(() => document.fonts.ready);
407
+ return doc.evaluate(() => {
408
+ const BLOCK = /^(P|H[1-6]|UL|OL|DL|TABLE|PRE|BLOCKQUOTE|HR|FORM|ADDRESS)$/, WRAP = /^(DIV|CENTER|SECTION|ARTICLE|MAIN|HEADER|FOOTER|NAV)$/;
409
+ const root = document.getElementById("doc");
410
+ function normalize(el) {
411
+ const kids = [...el.childNodes]; let run = [];
412
+ const flush = () => {
413
+ while (run.length && (run[run.length - 1].nodeName === "BR" || (run[run.length - 1].nodeType === 3 && !run[run.length - 1].textContent.trim()))) run.pop().remove();
414
+ if (run.length && run.some(n => n.nodeType === 1 || n.textContent.trim())) { const d = document.createElement("div"); d.className = "run"; run[0].before(d); run.forEach(n => d.append(n)); }
415
+ else run.forEach(n => n.remove());
416
+ run = [];
417
+ };
418
+ for (let i = 0; i < kids.length; i++) {
419
+ const n = kids[i];
420
+ if (n.nodeType === 1 && (BLOCK.test(n.nodeName) || WRAP.test(n.nodeName))) { flush(); if (WRAP.test(n.nodeName)) normalize(n); continue; }
421
+ if (n.nodeType === 8) { n.remove(); continue; }
422
+ const prev = [...run].reverse().find(m => m.nodeType !== 3 || m.textContent.trim());
423
+ if (n.nodeName === "BR" && prev?.nodeName === "BR") { run.splice(run.indexOf(prev)).forEach(m => m.remove()); n.remove(); flush(); continue; }
424
+ if (n.nodeName === "BR" && !run.length) { n.remove(); continue; }
425
+ run.push(n);
426
+ }
427
+ flush();
428
+ }
429
+ normalize(root);
430
+ const segs = [];
431
+ (function collect(el) {
432
+ for (const n of el.children) {
433
+ if (/^(DIV|CENTER|SECTION|ARTICLE|MAIN|HEADER|FOOTER|NAV)$/.test(n.nodeName) && n.className !== "run" && [...n.children].some(c => c.className === "run" || /^(P|H[1-6]|UL|OL|DL|TABLE|PRE|BLOCKQUOTE|HR|FORM|DIV)$/.test(c.nodeName))) { collect(n); continue; }
434
+ segs.push(n);
435
+ }
436
+ })(root);
437
+ const R = root.getBoundingClientRect();
438
+ return segs.map((n, i) => {
439
+ n.dataset.seg = i;
440
+ const b = n.getBoundingClientRect(), text = n.textContent.replace(/\s+/g, " ").trim();
441
+ const imgs = [...n.querySelectorAll("img")].map(m => ({ src: m.getAttribute("src"), alt: m.alt || "", w: m.width, h: m.height, href: m.closest("a")?.getAttribute("href") || null }));
442
+ const links = [...n.querySelectorAll("a[href]")].flatMap(a => [...a.getClientRects()].map(r => ({ href: a.getAttribute("href"), alt: a.textContent.replace(/\s+/g, " ").trim(), x: Math.floor(r.x - R.x), y: Math.floor(r.y - b.y), w: Math.ceil(r.width), h: Math.ceil(r.height) })));
443
+ const names = [...n.querySelectorAll("a[name], [id]")].map(a => a.getAttribute("name") || a.id).filter(Boolean);
444
+ if (n.getAttribute("name") || n.id) names.push(n.getAttribute("name") || n.id);
445
+ const align = (n.getAttribute("align") || getComputedStyle(n).textAlign || "").toLowerCase();
446
+ return { i, tag: n.nodeName, html: n.outerHTML, text, cjk: /[\u2e80-\u9fff\uff00-\uffef\u3000-\u303f]/.test(text), imgs, links, names, align,
447
+ x: Math.floor(b.x - R.x), y: Math.floor(b.y + scrollY), w: Math.ceil(b.width), h: Math.ceil(b.height), top: b.y + scrollY, mt: parseFloat(getComputedStyle(n).marginTop) || 0 };
448
+ });
449
+ });
450
+ }
451
+
452
+ async function sliceSegment(seg, from) {
453
+ const clip = { x: 20, y: Math.floor(seg.top), width: TW, height: Math.max(1, seg.h) };
454
+ const png = await doc.screenshot({ clip, fullPage: true });
455
+ const raw = rawOf(png), w = clip.width, h = clip.height;
456
+ const blank = y => { const row = raw.subarray(y * w * 3, (y + 1) * w * 3); for (let k = 0; k < row.length; k++) if (row[k] !== 255) return false; return true; };
457
+ let right = 0; for (let y = 0; y < h; y++) for (let x = w - 1; x > right; x--) { const o = (y * w + x) * 3; if (raw[o] !== 255 || raw[o + 1] !== 255 || raw[o + 2] !== 255) { right = x; break; } }
458
+ for (const l of seg.links) right = Math.max(right, l.x + l.w - 1);
459
+ const cw = Math.min(w, right + 2);
460
+ const cuts = [0];
461
+ while (h - cuts[cuts.length - 1] > SLICE) {
462
+ const start = cuts[cuts.length - 1]; let c = start + SLICE;
463
+ while (c > start + 40 && !blank(c)) c--;
464
+ if (c <= start + 40) c = start + SLICE;
465
+ cuts.push(c);
466
+ }
467
+ cuts.push(h);
468
+ const out = [];
469
+ for (let k = 0; k < cuts.length - 1; k++) {
470
+ const y0 = cuts[k], y1 = cuts[k + 1], sh = y1 - y0;
471
+ const rows = Buffer.alloc(cw * sh * 3);
472
+ for (let y = 0; y < sh; y++) raw.copy(rows, y * cw * 3, ((y0 + y) * w) * 3, ((y0 + y) * w + cw) * 3);
473
+ const gif = encodeGif(rows, cw, sh) || ffmpegGif(pngOfRaw(rows, cw, sh));
474
+ const areas = seg.links.filter(l => l.y < y1 && l.y + l.h > y0).map(l => {
475
+ const yy = Math.max(l.y, y0), yb = Math.min(l.y + l.h, y1);
476
+ return { href: l.href, alt: l.alt, x: l.x, y: yy - y0, w: l.w, h: yb - yy };
477
+ }).map(a => ({ ...a, href: resolveHref(a.href, from, "img") })).filter(a => a.href);
478
+ out.push({ url: store(gif), w: cw, h: sh, areas });
479
+ }
480
+ return out;
481
+ }
482
+
483
+ function nativeHTML(html, from, mode) {
484
+ return inlineStyleToHTML32(html)
485
+ .replace(/\s(class|id|data-seg)="[^"]*"/gi, "")
486
+ .replace(/<a\s([^>]*?)href="([^"]*)"([^>]*)>/gi, (m, a, h, b) => { const u = resolveHref(h, from, mode); return u ? `<a ${a}href="${esc(u)}"${b}${TOP}>` : `<a ${a}${b}>`; })
487
+ .replace(/<img\s([^>]*?)src="([^"]*)"([^>]*)>/gi, (m, a, s, b) => {
488
+ if (/^[a-z]+:/i.test(s)) return `<img ${a}src="${s}"${b}>`;
489
+ const ci = contentImage(posix.normalize(posix.join(posix.dirname(from), s)));
490
+ if (!ci) return "";
491
+ const rest = (a + b).replace(/\s(width|height|src)="?[^"\s>]*"?/gi, "").replace(/\/\s*$/, "");
492
+ return `<img src="${ci.url}" width=${ci.w} height=${ci.h}${rest} border=0>`;
493
+ })
494
+ .replace(/<\/img>/gi, "");
495
+ }
496
+
497
+ // ---- Convert one page --------------------------------------------------------------------------
498
+ const report = [];
499
+ const plan = new Map();
500
+ async function analyse(p) {
501
+ const buf = readFileSync(join(SRC, p)), { text, enc } = decode(buf);
502
+ const title = ((text.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || p).replace(/\s+/g, " ").trim();
503
+ const segs = await layout(p, text);
504
+ const chromeImgs = 6, overhead = 12 * 1024;
505
+ let bytes = overhead, imgs = chromeImgs, part = 0; const at = new Map();
506
+ for (const s of segs) {
507
+ const imgBytes = s.imgs.reduce((a, m) => { const ci = m.src && !/^[a-z]+:/i.test(m.src) && contentImage(posix.normalize(posix.join(posix.dirname(p), m.src))); return a + (ci ? ci.bytes : 0); }, 0);
508
+ const est = s.cjk ? Math.ceil(s.w * s.h / 10) : imgBytes + s.html.length;
509
+ const n = s.cjk ? s.h / SLICE + (s.names.length ? 1 : 0) : s.imgs.length;
510
+ if ((bytes + est > BUDGET.bytes || imgs + n > BUDGET.images) && bytes > overhead) { part++; bytes = overhead; imgs = chromeImgs; }
511
+ bytes += est; imgs += n; s.part = part;
512
+ for (const nm of s.names) at.set(nm, part);
513
+ }
514
+ anchorsAt.set(p, at); parts.set(p, Array.from({ length: part + 1 }, (_, i) => partName(p, i)));
515
+ plan.set(p, { title, enc, segs, html: text });
516
+ }
517
+
518
+ const charsetOf = enc => enc === "us-ascii" ? "iso-8859-1" : enc;
519
+ function modeBar(p, mode, enc) {
520
+ if (enc === "us-ascii") return "";
521
+ const q = STATIC_ONLY ? "" : (mode === "img" ? "?cjk=text" : "?cjk=img");
522
+ const other = mode === "img" ? `${txt(p)}${q}` : `${pic(p)}${q}`;
523
+ return mode === "img"
524
+ ? `<table border=0 cellspacing=0 cellpadding=4 width=${TW} bgcolor="#ffffcc"><tr><td>No Chinese fonts: Chinese is shown as pictures and cannot be copied. <a href="${pic("fonts.html")}"${TOP}>How to install Chinese fonts</a> | <a href="${other}"${TOP}>I have Chinese fonts: show text</a></td></tr></table>${sp(1, 8)}<br>`
525
+ : `<a href="${other}"${TOP}>Chinese text garbled? Show it as pictures</a> | <a href="${pic("fonts.html")}"${TOP}>Install Chinese fonts</a><br>${sp(1, 8)}<br>`;
526
+ }
527
+
528
+ async function emitPage(p) {
529
+ const { title, enc, segs, html: srcHTML } = plan.get(p), names = parts.get(p), cs = charsetOf(enc);
530
+ const again = await layout(p, srcHTML);
531
+ if (again.length !== segs.length || again.some((s, i) => Math.abs(s.top - segs[i].top) > 0.5)) throw new Error(`layout of ${p} is not stable`);
532
+ mapSeq = 0;
533
+ let body = segs.map(s => (s.names.map(n => `<a name="${esc(n)}"></a>`).join("")) + nativeHTML(s.html, p, "text")).join("\n");
534
+ const tHtml = await pageShell(title, indent(await windowHTML({ title, width: W, active: true, body: modeBar(p, "text", enc) + body })), cs, p, "text");
535
+ writeOut("t/" + p, encodeOut(tHtml, enc));
536
+ frameset("t/" + p, title, enc);
537
+ for (let k = 0; k < names.length; k++) {
538
+ mapSeq = 0;
539
+ const out = [];
540
+ let bytes = 0;
541
+ let group = [];
542
+ const flush = async () => {
543
+ if (!group.length) return;
544
+ const first = group[0], last = group[group.length - 1], top = first.top;
545
+ const region = { top, h: Math.ceil(last.top + last.h - top), links: group.flatMap(g => g.links.map(l => ({ ...l, y: l.y + Math.round(g.top - top) }))) };
546
+ const slices = await sliceSegment(region, p);
547
+ out.push(first.names.map(n => `<a name="${esc(n)}"></a>`).join("") + slices.map(b => img(b, group.map(g => g.text).join(" ").slice(0, 60))).join("<br>") + `<br>${sp(1, 12)}<br>`);
548
+ for (const b of slices) bytes += gifBytes.get(b.url) || 0;
549
+ group = [];
550
+ };
551
+ for (const s of segs.filter(s => s.part === k)) {
552
+ if (s.cjk) { if (s.names.length) await flush(); group.push(s); continue; }
553
+ await flush();
554
+ out.push(s.names.map(n => `<a name="${esc(n)}"></a>`).join("") + nativeHTML(s.html, p, "img"));
555
+ for (const m of s.imgs) { const ci = m.src && !/^[a-z]+:/i.test(m.src) && contentImage(posix.normalize(posix.join(posix.dirname(p), m.src))); if (ci) bytes += ci.bytes; }
556
+ }
557
+ await flush();
558
+ const nav = names.length > 1 ? `Page ${k + 1} / ${names.length}: ` + names.map((n, i) => i === k ? `<b>${i + 1}</b>` : `<a href="${pic(n)}"${TOP}>${i + 1}</a>`).join(" ") +
559
+ (k < names.length - 1 ? ` | <a href="${pic(names[k + 1])}"${TOP}>Next &gt;&gt;</a>` : "") + `<br>${sp(1, 8)}<br>` : "";
560
+ const html = await pageShell(title + (names.length > 1 ? ` (${k + 1}/${names.length})` : ""),
561
+ indent(await windowHTML({ title, width: W, active: true, body: (k === 0 ? modeBar(p, "img", enc) : "") + nav + out.join("\n") + (names.length > 1 ? `<br>${nav}` : "") })), cs, p, "img");
562
+ const file = encodeOut(html, enc);
563
+ writeOut(names[k], file); frameset(names[k], title, enc);
564
+ report.push({ page: names[k], segs: segs.filter(s => s.part === k).length, gifBytes: bytes, html: file.length, total: bytes + file.length + 3000, imgs: new Set([...html.matchAll(/<img src="([^"]+)"/g)].map(m => m[1])).size });
565
+ }
566
+ }
567
+ function writeOut(rel, buf) { const f = join(OUT, rel); mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, buf); }
568
+ function frameset(rel, title, enc) {
569
+ const frameSrc = STATIC_ONLY ? `${BASE}${rel}` : `${BASE}n/${rel}`;
570
+ const html = `<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
571
+ <html><head><meta http-equiv="Content-Type" content="text/html; charset=${charsetOf(enc)}"><title>${hEsc(title)}</title></head>
572
+ <frameset rows="100%,*" border=0 frameborder=0 framespacing=0><frame src="${frameSrc}" marginwidth=1 marginheight=1 scrolling=auto noresize><frame src="${BASE}blank.html" scrolling=no noresize></frameset></html>
573
+ `;
574
+ writeOut("f/" + rel, encodeOut(html, enc));
575
+ }
576
+
577
+ // ---- Run --------------------------------------------------------------------------------------
578
+ FRAME = await measureFrame(ERA);
579
+ ERA_MENUS = await measureMenus(ERA);
580
+ const only = arg("only");
581
+ const todo = only ? pagesSrc.filter(p => only.split(",").includes(p)) : pagesSrc;
582
+ for (const p of pagesSrc) if (!only || todo.includes(p)) { process.stdout.write(`layout ${p}\n`); await analyse(p); }
583
+ const useClassicMac = PRESET === "classicmac" || (PRESET === "auto" && (plan.get("index.html")?.html || "").includes("犄角旮旯"));
584
+ const special = useClassicMac ? await import("./special-classicmac.mjs") : null;
585
+ for (const p of todo) {
586
+ if (special?.handles?.(p)) continue;
587
+ process.stdout.write(`emit ${p}\n`); await emitPage(p);
588
+ }
589
+ { const shot = ["page.png", "page.gif"].map(f => join(SRC, f)).find(existsSync);
590
+ if (shot) writeFileSync(join(OUT, "i", "page.thumb.gif"), execFileSync("ffmpeg", ["-loglevel", "error", "-i", shot, "-vf", "scale=158:118:flags=area,split[a][b];[a]palettegen=max_colors=64[p];[b][p]paletteuse=dither=bayer:bayer_scale=3", "-f", "gif", "-"])); }
591
+ if (special) await special.emit({ SRC, OUT, BASE, ORIGIN, TW, W, STATIC_ONLY, plan, pic, txt, img, sp, esc, hEsc, windowHTML, pageShell, indent, snapHTML, store, encodeOut, writeOut, frameset, resolveHref, contentImage, report, TOP, charsetOf, setMapSeq: v => (mapSeq = v) });
592
+ await exportEras();
593
+ rmSync(renderHtmlPath, { force: true });
594
+ rmSync(docHtmlPath, { force: true });
595
+ writeFileSync(join(OUT, "report.json"), JSON.stringify(report, null, 1));
596
+ const over = report.filter(r => r.total > BUDGET.bytes * 1.15 || r.imgs > BUDGET.images + 5);
597
+ console.log(`${report.length} picture pages, ${gifBytes.size} block GIFs (${Math.round([...gifBytes.values()].reduce((a, b) => a + b, 0) / 1024)} KB), ${imgDone.size} content images`);
598
+ if (over.length) console.log("over budget:", over.map(r => `${r.page} ${Math.round(r.total / 1024)}KB ${r.imgs}img`).join(", "));
599
+ await browser.close();
600
+
601
+ if (CHECK_LINKS && !checkLinks(OUT, BASE)) process.exit(1);