@babylonjs-toolkit/agent 1.1.66 → 1.1.68

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.
@@ -0,0 +1,611 @@
1
+ /**
2
+ * bt-profile report: turns an analysis (and optionally a baseline analysis and the agent's findings file) into one
3
+ * self-contained HTML dashboard — `.agents/profile/<slug>/dashboard.html`, beside the slug's `data/` folder.
4
+ *
5
+ * Usage (from `.agents/profile/<slug>/data`):
6
+ * node ../../.tools/report.mjs --analysis runs/<run>/cold/analysis.json [--out ../dashboard.html]
7
+ * [--baseline runs/<baseline>/cold/analysis.json] [--warm runs/<run>/warm/analysis.json]
8
+ * [--findings ./findings.json] [--title "Race start"]
9
+ * [--snapshots runs/<snapshots run>/cold] [--snapshots-before <dir of earlier shots>]
10
+ * `--snapshots` shows the screenshots of a separate `--snapshots true` capture (so the measured run stays free of
11
+ * screenshot overhead); `--snapshots-before` sets them beside earlier shots of the same names (e.g. the smoke run).
12
+ *
13
+ * findings.json (written by the agent — the diagnosis in plain language):
14
+ * { "title", "summary", "findings": [{ "id", "title", "severity": "critical|major|minor", "status": "fixed|proposed|reverted|not-fixed",
15
+ * "phases": [..], "cost", "cause", "evidence": [..], "code": [{ "file", "line", "label" }], "fix", "before", "after", "diff" }] }
16
+ */
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+
20
+ import { PROGRESS_SCRIPT, PROGRESS_STYLES, progressMarkup } from "./lib/progress-panel.mjs";
21
+
22
+ /** Owner groups drawn in the charts, in fixed categorical slot order (slot colours never move between charts). */
23
+ const OWNER_GROUPS = [
24
+ { id: "babylon", label: "BabylonJS engine", owners: ["babylon"], slot: 1 },
25
+ { id: "yours", label: "Your code", owners: [], slot: 2 },
26
+ { id: "toolkit", label: "Babylon Toolkit", owners: ["toolkit"], slot: 3 },
27
+ { id: "physics", label: "Havok physics", owners: ["physics"], slot: 4 },
28
+ { id: "shader", label: "Shader translation", owners: ["shader"], slot: 5 },
29
+ { id: "gc", label: "Garbage collection", owners: ["gc"], slot: 6 },
30
+ { id: "program", label: "Browser", owners: ["program", "native"], slot: 7 },
31
+ { id: "other", label: "Other libraries", owners: ["react", "vendor"], slot: 0 },
32
+ ];
33
+
34
+ /**
35
+ * Reads `--name value` pairs from the command line.
36
+ * @param {string[]} argv - process.argv.slice(2)
37
+ * @returns {Record<string, string>} the parsed flags
38
+ */
39
+ function parseArguments(argv) {
40
+ const flags = {};
41
+ for (let i = 0; i < argv.length; i += 2) flags[argv[i].replace(/^--/, "")] = argv[i + 1];
42
+ return flags;
43
+ }
44
+
45
+ /** Reads a JSON file, or returns null when the flag is absent. */
46
+ /** Walks up from a folder to the first one holding `name`; returns the path found (the file) or null. */
47
+ function findUp(dir, name) {
48
+ for (let current = dir; current; current = path.dirname(current) === current ? null : path.dirname(current)) {
49
+ if (fs.existsSync(path.join(current, name))) return path.join(current, name);
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /** The slug folder of a run folder laid out as `<slug>/data/runs/<run>/<cold|warm>` (no config needed), else null. */
55
+ function slugDirOfRun(dir) {
56
+ for (let current = dir; current && path.dirname(current) !== current; current = path.dirname(current)) {
57
+ if (path.basename(current) === "runs" && path.basename(path.dirname(current)) === "data") return path.dirname(path.dirname(current));
58
+ }
59
+ return null;
60
+ }
61
+
62
+ const readJson = (file) => (file ? JSON.parse(fs.readFileSync(path.resolve(file), "utf8")) : null);
63
+
64
+ /** Escapes text for HTML. */
65
+ const escapeHtml = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" })[character]);
66
+
67
+ /** Maps an owner id to its chart group id, given the capture's own "yours" owners. */
68
+ function groupOf(owner, yourOwners) {
69
+ if (yourOwners.includes(owner)) return "yours";
70
+ const group = OWNER_GROUPS.find((candidate) => candidate.owners.includes(owner));
71
+ return group ? group.id : "other";
72
+ }
73
+
74
+ /**
75
+ * Reduces an analysis to what the page draws: timeline buckets grouped by owner group, phases, tables, excerpts.
76
+ * Run files are found beside the analysis file (not at the path recorded in it), so a slug folder can be moved.
77
+ * @returns {object} the page data for one run
78
+ */
79
+ function pageData(analysis, reportDir, captureDir) {
80
+ const yourOwners = analysis.yourOwners || ["project"];
81
+ const timeline = analysis.timeline.map((bucket) => {
82
+ const groups = {};
83
+ for (const [owner, ms] of Object.entries(bucket.owners || {})) {
84
+ const group = groupOf(owner, yourOwners);
85
+ groups[group] = (groups[group] || 0) + ms;
86
+ }
87
+ return { t: bucket.t, fps: bucket.fps, cpu: bucket.cpuMeanMs, busy: bucket.busyPct, worst: bucket.worstMs, shaders: bucket.newShaders, particles: bucket.particles, draws: bucket.draws, heap: bucket.heapMb, groups, top: bucket.top, topYours: bucket.topYours };
88
+ });
89
+ const relative = (file) => path.relative(reportDir, path.join(captureDir, file)).split(path.sep).join("/");
90
+ return {
91
+ capture: analysis.capture,
92
+ ownerLabels: analysis.ownerLabels,
93
+ yourOwners,
94
+ overall: analysis.overall,
95
+ phases: analysis.phases,
96
+ timeline,
97
+ marks: analysis.marks,
98
+ worstFrames: analysis.worstFrames,
99
+ hotLines: analysis.hotLines,
100
+ excerpts: analysis.excerpts,
101
+ heap: analysis.heap,
102
+ loaf: analysis.loaf,
103
+ signals: analysis.signals,
104
+ shots: (analysis.shots || []).map((name) => ({ name: name.replace(/\.png$/, ""), src: relative(path.join("shots", name)) })),
105
+ filmstrip: (analysis.filmstrip || []).map((frame) => ({ t: frame.t, src: relative(frame.file) })),
106
+ cpuprofile: path.join(captureDir, "cpu.cpuprofile"),
107
+ };
108
+ }
109
+
110
+ /** The page's stylesheet: a dark code-dashboard look, with a selected light variant. */
111
+ const STYLES = `
112
+ :root {
113
+ color-scheme: dark;
114
+ --surface-0: #111110; --surface-1: #1a1a19; --surface-2: #232321; --surface-3: #2d2d2a;
115
+ --text-primary: #f0efec; --text-secondary: #c3c2b7; --text-muted: #8f8e86;
116
+ --grid: #34342f; --accent: #3987e5;
117
+ --good: #3fae5a; --warning: #c98500; --serious: #d95926; --critical: #e66767;
118
+ --series-1: #3987e5; --series-2: #d95926; --series-3: #199e70; --series-4: #c98500;
119
+ --series-5: #d55181; --series-6: #008300; --series-7: #9085e9; --series-0: #77766f;
120
+ --code-bg: #141413; --hot: rgba(217, 89, 38, 0.22);
121
+ --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
122
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif;
123
+ }
124
+ @media (prefers-color-scheme: light) {
125
+ :root:where(:not([data-theme="dark"])) {
126
+ color-scheme: light;
127
+ --surface-0: #f4f4f2; --surface-1: #fcfcfb; --surface-2: #f0efec; --surface-3: #e4e3df;
128
+ --text-primary: #0b0b0b; --text-secondary: #52514e; --text-muted: #77766f;
129
+ --grid: #e4e3df; --accent: #2a78d6;
130
+ --series-1: #2a78d6; --series-2: #eb6834; --series-3: #1baf7a; --series-4: #eda100;
131
+ --series-5: #e87ba4; --series-6: #008300; --series-7: #6250d6; --series-0: #9a998f;
132
+ --code-bg: #f6f6f4; --hot: rgba(235, 104, 52, 0.18);
133
+ }
134
+ }
135
+ :root[data-theme="light"] {
136
+ color-scheme: light;
137
+ --surface-0: #f4f4f2; --surface-1: #fcfcfb; --surface-2: #f0efec; --surface-3: #e4e3df;
138
+ --text-primary: #0b0b0b; --text-secondary: #52514e; --text-muted: #77766f;
139
+ --grid: #e4e3df; --accent: #2a78d6;
140
+ --series-1: #2a78d6; --series-2: #eb6834; --series-3: #1baf7a; --series-4: #eda100;
141
+ --series-5: #e87ba4; --series-6: #008300; --series-7: #6250d6; --series-0: #9a998f;
142
+ --code-bg: #f6f6f4; --hot: rgba(235, 104, 52, 0.18);
143
+ }
144
+ * { box-sizing: border-box; }
145
+ body { margin: 0; background: var(--surface-0); color: var(--text-primary); font: 14px/1.5 var(--sans); }
146
+ main { max-width: 1280px; margin: 0 auto; padding: 24px 16px 64px; }
147
+ header.top { display: flex; flex-wrap: wrap; gap: 12px 24px; align-items: baseline; justify-content: space-between; margin-bottom: 8px; }
148
+ h1 { font-size: 22px; margin: 0; letter-spacing: -0.01em; }
149
+ h2 { font-size: 15px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--text-secondary); margin: 40px 0 12px; font-weight: 600; }
150
+ h3 { font-size: 15px; margin: 0 0 6px; }
151
+ .meta { color: var(--text-muted); font: 12px/1.6 var(--mono); }
152
+ .verdict.disturbed { border-left-color: var(--serious); }
153
+ .verdict { background: var(--surface-1); border: 1px solid var(--surface-3); border-left: 3px solid var(--accent); border-radius: 8px; padding: 14px 16px; margin: 16px 0; color: var(--text-primary); font-size: 15px; }
154
+ .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
155
+ .tile { background: var(--surface-1); border: 1px solid var(--surface-3); border-radius: 8px; padding: 12px 14px; }
156
+ .tile .label { color: var(--text-secondary); font-size: 12px; }
157
+ .tile .value { font-size: 26px; font-weight: 600; margin-top: 2px; font-variant-numeric: tabular-nums; }
158
+ .tile .delta { font: 12px var(--mono); margin-top: 2px; }
159
+ .delta.better { color: var(--good); } .delta.worse { color: var(--critical); } .delta.same { color: var(--text-muted); }
160
+ .panel { background: var(--surface-1); border: 1px solid var(--surface-3); border-radius: 10px; padding: 16px; overflow-x: auto; }
161
+ .finding a, .finding li { overflow-wrap: anywhere; }
162
+ main { overflow-wrap: anywhere; }
163
+ .chart { width: 100%; height: auto; display: block; }
164
+ .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 8px; font-size: 12px; color: var(--text-secondary); }
165
+ .legend span { display: inline-flex; align-items: center; gap: 6px; }
166
+ .legend i { width: 10px; height: 10px; border-radius: 2px; display: inline-block; }
167
+ .tooltip { position: fixed; pointer-events: none; z-index: 10; background: var(--surface-2); border: 1px solid var(--surface-3); border-radius: 6px; padding: 8px 10px; font: 12px/1.5 var(--mono); color: var(--text-primary); max-width: 360px; box-shadow: 0 6px 24px rgba(0,0,0,0.35); display: none; }
168
+ .tooltip b { font-family: var(--sans); }
169
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
170
+ th { text-align: left; color: var(--text-muted); font-weight: 500; font-size: 12px; padding: 6px 8px; border-bottom: 1px solid var(--surface-3); white-space: nowrap; }
171
+ td { padding: 6px 8px; border-bottom: 1px solid var(--surface-2); vertical-align: top; }
172
+ td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; font-family: var(--mono); white-space: nowrap; }
173
+ .scroll { overflow-x: auto; }
174
+ .fn { font-family: var(--mono); font-size: 12.5px; word-break: break-word; }
175
+ .where { font: 11.5px var(--mono); color: var(--text-muted); word-break: break-all; }
176
+ a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }
177
+ .owner { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; color: var(--text-secondary); }
178
+ .phase .owner { display: flex; margin-top: 2px; }
179
+ .owner i { width: 8px; height: 8px; border-radius: 2px; display: inline-block; }
180
+ .bar { height: 8px; border-radius: 0 4px 4px 0; display: block; min-width: 2px; }
181
+ .finding { background: var(--surface-1); border: 1px solid var(--surface-3); border-radius: 10px; padding: 16px; margin-bottom: 12px; }
182
+ .finding header { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; margin-bottom: 6px; }
183
+ .badge { font: 600 11px var(--sans); text-transform: uppercase; letter-spacing: 0.06em; padding: 2px 8px; border-radius: 999px; border: 1px solid currentColor; }
184
+ .badge.critical { color: var(--critical); } .badge.major { color: var(--serious); } .badge.minor { color: var(--warning); }
185
+ .badge.fixed { color: var(--good); } .badge.proposed, .badge.not-fixed { color: var(--text-muted); } .badge.reverted { color: var(--warning); }
186
+ .finding .cost { font: 600 13px var(--mono); color: var(--text-primary); }
187
+ .finding p { margin: 6px 0; color: var(--text-secondary); }
188
+ .finding p strong { color: var(--text-primary); font-weight: 600; }
189
+ .finding ul { margin: 6px 0 6px 18px; padding: 0; color: var(--text-secondary); }
190
+ .beforeafter { display: flex; flex-wrap: wrap; gap: 8px 24px; font: 12.5px var(--mono); margin-top: 8px; }
191
+ pre.code { background: var(--code-bg); border: 1px solid var(--surface-3); border-radius: 8px; margin: 8px 0 0; padding: 8px 0; overflow-x: auto; font: 12px/1.55 var(--mono); }
192
+ pre.code .row { display: flex; padding: 0 12px 0 0; white-space: pre; }
193
+ pre.code .row.hot { background: var(--hot); }
194
+ pre.code .ln { color: var(--text-muted); width: 56px; text-align: right; padding-right: 12px; flex: none; user-select: none; }
195
+ pre.code .ms { color: var(--serious); margin-left: 16px; }
196
+ pre.diff .add { color: var(--good); } pre.diff .del { color: var(--critical); }
197
+ details { margin-top: 8px; } summary { cursor: pointer; color: var(--text-secondary); font-size: 13px; }
198
+ .phases { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr)); gap: 10px; }
199
+ .phase { background: var(--surface-1); border: 1px solid var(--surface-3); border-radius: 8px; padding: 12px 14px; }
200
+ .phase .name { font: 600 13px var(--mono); }
201
+ .phase .fps { font-size: 22px; font-weight: 600; font-variant-numeric: tabular-nums; }
202
+ .phase .small { font-size: 12px; color: var(--text-secondary); }
203
+ .phase ol { margin: 6px 0 0 16px; padding: 0; font-size: 12px; color: var(--text-secondary); }
204
+ .film { display: flex; gap: 4px; overflow-x: auto; padding: 8px 0 0; }
205
+ .film figure { margin: 0; flex: none; text-align: center; }
206
+ .film img { height: 72px; border-radius: 4px; display: block; }
207
+ .film figcaption { font: 10.5px var(--mono); color: var(--text-muted); }
208
+ .shots { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
209
+ .shots figure { margin: 0; } .shots img { width: 100%; border-radius: 6px; display: block; }
210
+ .shots figcaption { font: 12px var(--mono); color: var(--text-muted); margin-top: 4px; }
211
+ .signals li { margin: 4px 0; color: var(--text-secondary); }
212
+ .two { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); gap: 12px; }
213
+ @media (max-width: 520px) { .two { grid-template-columns: 1fr; } .tile .value { font-size: 22px; } }
214
+ .toggle { background: var(--surface-2); color: var(--text-secondary); border: 1px solid var(--surface-3); border-radius: 6px; font-size: 12px; padding: 4px 10px; cursor: pointer; }
215
+ `;
216
+
217
+ /** The page's script: renders every section from the embedded JSON. Kept dependency-free. */
218
+ const SCRIPT = String.raw`
219
+ const DATA = JSON.parse(document.getElementById("bt-data").textContent);
220
+ const run = DATA.run, base = DATA.baseline, warm = DATA.warm, findings = DATA.findings;
221
+ const GROUPS = DATA.groups;
222
+ const $ = (selector) => document.querySelector(selector);
223
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
224
+ const fmt = (value, digits = 1) => value == null || Number.isNaN(value) ? "–" : Number(value).toLocaleString(undefined, { maximumFractionDigits: digits, minimumFractionDigits: 0 });
225
+ const seriesVar = (slot) => "var(--series-" + slot + ")";
226
+ const groupOf = (owner) => {
227
+ if (run.yourOwners.includes(owner)) return GROUPS.find((g) => g.id === "yours");
228
+ return GROUPS.find((g) => g.owners.includes(owner)) || GROUPS.find((g) => g.id === "other");
229
+ };
230
+ const ownerChip = (owner) => { const g = groupOf(owner); return '<span class="owner"><i style="background:' + seriesVar(g.slot) + '"></i>' + esc(run.ownerLabels[owner] || owner) + '</span>'; };
231
+ const shortPath = (file) => !file ? "" : file.replace(/^.*\/node_modules\//, "node_modules/").replace(/^\/Users\/[^/]+\//, "~/");
232
+ const link = (file, line, text) => file ? '<a href="vscode://file/' + encodeURI(file) + (line ? ":" + line : "") + '">' + esc(text || (shortPath(file) + (line ? ":" + line : ""))) + '</a>' : '<span class="where">' + esc(text || "") + '</span>';
233
+ const tooltip = $("#tooltip");
234
+ const showTip = (event, html) => { tooltip.innerHTML = html; tooltip.style.display = "block"; const x = Math.min(event.clientX + 14, innerWidth - tooltip.offsetWidth - 8); const y = Math.min(event.clientY + 14, innerHeight - tooltip.offsetHeight - 8); tooltip.style.left = x + "px"; tooltip.style.top = y + "px"; };
235
+ const hideTip = () => { tooltip.style.display = "none"; };
236
+
237
+ function delta(now, before, lowerIsBetter, unit = "", digits = 1) {
238
+ if (before == null || now == null) return "";
239
+ const change = now - before;
240
+ if (Math.abs(change) < Math.pow(10, -digits)) return '<div class="delta same">= baseline</div>';
241
+ const better = lowerIsBetter ? change < 0 : change > 0;
242
+ return '<div class="delta ' + (better ? "better" : "worse") + '">' + (change > 0 ? "+" : "") + fmt(change, digits) + unit + " vs " + fmt(before, digits) + unit + '</div>';
243
+ }
244
+
245
+ function settledPhase(analysis) {
246
+ const racing = analysis.phases.filter((p) => /^race/.test(p.name));
247
+ return racing.length ? racing[racing.length - 1] : analysis.phases[analysis.phases.length - 1];
248
+ }
249
+
250
+ function renderTiles() {
251
+ const settled = settledPhase(run), settledBase = base ? settledPhase(base) : null;
252
+ const worstPhase = [...run.phases].filter((p) => p.frames.fps != null && p.durationSeconds >= 1).sort((a, b) => a.frames.fps - b.frames.fps)[0];
253
+ const worstBase = base && worstPhase ? base.phases.find((p) => p.name === worstPhase.name) : null;
254
+ const gc = (a) => (a.overall.lists.owners.find((o) => o.owner === "gc") || { pctBusy: 0 }).pctBusy;
255
+ const shaders = (a) => a.timeline.reduce((sum, b) => sum + (b.shaders || 0), 0);
256
+ const tiles = [
257
+ { label: "FPS, worst phase (" + (worstPhase ? worstPhase.name : "–") + ")", value: worstPhase ? fmt(worstPhase.frames.fps) : "–", delta: delta(worstPhase && worstPhase.frames.fps, worstBase && worstBase.frames.fps, false) },
258
+ { label: "FPS, settled (" + settled.name + ")", value: fmt(settled.frames.fps), delta: delta(settled.frames.fps, settledBase && settledBase.frames.fps, false) },
259
+ { label: "CPU per frame, settled", value: fmt(settled.frames.cpuMeanMs) + " ms", delta: delta(settled.frames.cpuMeanMs, settledBase && settledBase.frames.cpuMeanMs, true, " ms") },
260
+ { label: "Main thread busy", value: fmt(run.overall.busyPct, 0) + "%", delta: delta(run.overall.busyPct, base && base.overall.busyPct, true, "%", 0) },
261
+ { label: "Draw calls, settled", value: fmt(settled.frames.draws, 0), delta: delta(settled.frames.draws, settledBase && settledBase.frames.draws, true, "", 0) },
262
+ { label: "Garbage collection", value: fmt(gc(run)) + "%", delta: base ? delta(gc(run), gc(base), true, "%") : "" },
263
+ { label: "Allocated", value: run.heap ? fmt(run.heap.mbPerSecond, 0) + " MB/s" : "–", delta: base && base.heap && run.heap ? delta(run.heap.mbPerSecond, base.heap.mbPerSecond, true, " MB/s", 0) : "" },
264
+ { label: "Shaders compiled in run", value: fmt(shaders(run), 0), delta: base ? delta(shaders(run), shaders(base), true, "", 0) : "" },
265
+ ];
266
+ $("#tiles").innerHTML = tiles.map((t) => '<div class="tile"><div class="label">' + esc(t.label) + '</div><div class="value">' + t.value + '</div>' + (t.delta || "") + '</div>').join("");
267
+ }
268
+
269
+ function svgEl(tag, attrs, text) {
270
+ const node = document.createElementNS("http://www.w3.org/2000/svg", tag);
271
+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
272
+ if (text != null) node.textContent = text;
273
+ return node;
274
+ }
275
+
276
+ function niceMax(value) {
277
+ if (value <= 0) return 1;
278
+ const power = Math.pow(10, Math.floor(Math.log10(value)));
279
+ for (const step of [1, 2, 2.5, 5, 10]) if (step * power >= value) return step * power;
280
+ return 10 * power;
281
+ }
282
+
283
+ function phaseBands(svg, x, top, bottom, marks, tMax) {
284
+ let lastLabelX = -1e9, row = 0;
285
+ for (const mark of marks) {
286
+ if (mark.name === "end" || mark.t > tMax) continue;
287
+ const px = x(mark.t);
288
+ svg.appendChild(svgEl("line", { x1: px, x2: px, y1: top, y2: bottom, stroke: "var(--text-muted)", "stroke-width": 1, opacity: 0.45 }));
289
+ // Labels closer than 70 px drop to a second row so they never overlap.
290
+ row = (px - lastLabelX < 70) ? (row + 1) % 2 : 0;
291
+ lastLabelX = px;
292
+ svg.appendChild(svgEl("text", { x: px + 4, y: top + 11 + row * 12, fill: "var(--text-secondary)", "font-size": 11, "font-family": "var(--mono)" }, mark.name));
293
+ }
294
+ }
295
+
296
+ function lineChart(target, series, options) {
297
+ const width = target.clientWidth || 900, height = options.height || 220;
298
+ const margin = { top: 22, right: 16, bottom: 26, left: 44 };
299
+ const svg = svgEl("svg", { viewBox: "0 0 " + width + " " + height, class: "chart", role: "img", "aria-label": options.label });
300
+ const tMax = Math.max(...series.flatMap((s) => s.points.map((p) => p.t)), 1);
301
+ const yMax = niceMax(Math.max(options.minMax || 0, ...series.flatMap((s) => s.points.map((p) => p.v || 0))));
302
+ const x = (t) => margin.left + (t / tMax) * (width - margin.left - margin.right);
303
+ const y = (v) => margin.top + (1 - v / yMax) * (height - margin.top - margin.bottom);
304
+ for (let i = 0; i <= 4; i++) {
305
+ const v = (yMax / 4) * i;
306
+ svg.appendChild(svgEl("line", { x1: margin.left, x2: width - margin.right, y1: y(v), y2: y(v), stroke: "var(--grid)", "stroke-width": 1 }));
307
+ svg.appendChild(svgEl("text", { x: margin.left - 6, y: y(v) + 4, "text-anchor": "end", fill: "var(--text-muted)", "font-size": 11 }, fmt(v, 0)));
308
+ }
309
+ for (let s = 0; s <= tMax; s += tMax > 120 ? 20 : 10) svg.appendChild(svgEl("text", { x: x(s), y: height - 8, "text-anchor": "middle", fill: "var(--text-muted)", "font-size": 11 }, s + "s"));
310
+ if (options.budget) {
311
+ svg.appendChild(svgEl("line", { x1: margin.left, x2: width - margin.right, y1: y(options.budget.value), y2: y(options.budget.value), stroke: "var(--good)", "stroke-width": 1, opacity: 0.7 }));
312
+ svg.appendChild(svgEl("text", { x: width - margin.right - 4, y: y(options.budget.value) - 4, "text-anchor": "end", fill: "var(--text-secondary)", "font-size": 11 }, options.budget.label));
313
+ }
314
+ phaseBands(svg, x, margin.top - 14, height - margin.bottom, options.marks || [], tMax);
315
+ for (const s of series) {
316
+ const d = s.points.filter((p) => p.v != null).map((p, i) => (i ? "L" : "M") + x(p.t).toFixed(1) + " " + y(p.v).toFixed(1)).join(" ");
317
+ svg.appendChild(svgEl("path", { d, fill: "none", stroke: s.color, "stroke-width": 2, "stroke-linejoin": "round", "stroke-linecap": "round", opacity: s.dim ? 0.45 : 1 }));
318
+ }
319
+ const cross = svgEl("line", { y1: margin.top, y2: height - margin.bottom, stroke: "var(--text-muted)", "stroke-width": 1, opacity: 0 });
320
+ svg.appendChild(cross);
321
+ const hit = svgEl("rect", { x: margin.left, y: margin.top, width: width - margin.left - margin.right, height: height - margin.top - margin.bottom, fill: "transparent" });
322
+ hit.addEventListener("mousemove", (event) => {
323
+ const box = svg.getBoundingClientRect();
324
+ const t = ((event.clientX - box.left) * (width / box.width) - margin.left) / (width - margin.left - margin.right) * tMax;
325
+ const index = Math.max(0, Math.round(t));
326
+ cross.setAttribute("x1", x(index)); cross.setAttribute("x2", x(index)); cross.setAttribute("opacity", 0.6);
327
+ showTip(event, options.tip(index));
328
+ });
329
+ hit.addEventListener("mouseleave", () => { cross.setAttribute("opacity", 0); hideTip(); });
330
+ svg.appendChild(hit);
331
+ target.innerHTML = "";
332
+ target.appendChild(svg);
333
+ }
334
+
335
+ function stackedColumns(target, buckets, marks) {
336
+ const width = target.clientWidth || 900, height = 240;
337
+ const margin = { top: 22, right: 16, bottom: 26, left: 44 };
338
+ const svg = svgEl("svg", { viewBox: "0 0 " + width + " " + height, class: "chart", role: "img", "aria-label": "Main-thread time per second by owner" });
339
+ const tMax = Math.max(buckets.length, 1);
340
+ const yMax = 1000;
341
+ const slotWidth = (width - margin.left - margin.right) / tMax;
342
+ const barWidth = Math.max(1, Math.min(24, slotWidth - 2));
343
+ const x = (t) => margin.left + t * slotWidth;
344
+ const y = (v) => margin.top + (1 - v / yMax) * (height - margin.top - margin.bottom);
345
+ for (let i = 0; i <= 4; i++) {
346
+ const v = (yMax / 4) * i;
347
+ svg.appendChild(svgEl("line", { x1: margin.left, x2: width - margin.right, y1: y(v), y2: y(v), stroke: "var(--grid)", "stroke-width": 1 }));
348
+ svg.appendChild(svgEl("text", { x: margin.left - 6, y: y(v) + 4, "text-anchor": "end", fill: "var(--text-muted)", "font-size": 11 }, (v / 10) + "%"));
349
+ }
350
+ for (let s = 0; s <= tMax; s += tMax > 120 ? 20 : 10) svg.appendChild(svgEl("text", { x: x(s) + slotWidth / 2, y: height - 8, "text-anchor": "middle", fill: "var(--text-muted)", "font-size": 11 }, s + "s"));
351
+ phaseBands(svg, (t) => x(t), margin.top - 14, height - margin.bottom, marks, tMax);
352
+ buckets.forEach((bucket, index) => {
353
+ let stacked = 0;
354
+ const group = svgEl("g", {});
355
+ for (const g of GROUPS) {
356
+ const ms = bucket.groups[g.id] || 0;
357
+ if (ms <= 0) continue;
358
+ const top = y(Math.min(yMax, stacked + ms)), bottom = y(stacked);
359
+ const h = Math.max(0, bottom - top - (stacked > 0 ? 1 : 0));
360
+ if (h > 0) group.appendChild(svgEl("rect", { x: x(index) + (slotWidth - barWidth) / 2, y: top, width: barWidth, height: h, fill: seriesVar(g.slot) }));
361
+ stacked += ms;
362
+ }
363
+ group.appendChild(svgEl("rect", { x: x(index), y: margin.top, width: slotWidth, height: height - margin.top - margin.bottom, fill: "transparent" }));
364
+ group.addEventListener("mousemove", (event) => {
365
+ const rows = GROUPS.filter((g) => bucket.groups[g.id] > 0).map((g) => '<div><i style="display:inline-block;width:8px;height:8px;border-radius:2px;background:' + seriesVar(g.slot) + '"></i> ' + esc(g.label) + ': ' + fmt(bucket.groups[g.id] / 10, 0) + '%</div>').join("");
366
+ showTip(event, "<b>" + bucket.t + "–" + (bucket.t + 1) + " s</b> · " + fmt(bucket.fps) + " fps<br>" + rows + (bucket.top ? '<div style="margin-top:4px">hottest: ' + esc(bucket.top.name) + " " + bucket.top.ms + " ms</div>" : "") + (bucket.shaders ? "<div>new shaders: " + bucket.shaders + "</div>" : ""));
367
+ });
368
+ group.addEventListener("mouseleave", hideTip);
369
+ svg.appendChild(group);
370
+ });
371
+ target.innerHTML = "";
372
+ target.appendChild(svg);
373
+ }
374
+
375
+ function renderTimeline() {
376
+ const tip = (index) => {
377
+ const b = run.timeline[index]; if (!b) return "";
378
+ const bb = base && base.timeline[index];
379
+ return "<b>" + b.t + " s</b><br>FPS " + fmt(b.fps) + (bb ? " (baseline " + fmt(bb.fps) + ")" : "") + "<br>CPU " + fmt(b.cpu, 2) + " ms/frame · worst frame " + fmt(b.worst) + " ms<br>busy " + fmt(b.busy, 0) + "% · particles " + fmt(b.particles, 0) + " · draws " + fmt(b.draws, 0) + (b.shaders ? "<br>new shaders " + b.shaders : "") + (b.top ? "<br>hottest: " + esc(b.top.name) : "");
380
+ };
381
+ const fpsSeries = [{ points: run.timeline.map((b) => ({ t: b.t, v: b.fps })), color: "var(--series-1)" }];
382
+ if (base) fpsSeries.unshift({ points: base.timeline.map((b) => ({ t: b.t, v: b.fps })), color: "var(--series-0)", dim: true });
383
+ lineChart($("#chart-fps"), fpsSeries, { label: "Frames per second over the run", marks: run.marks, minMax: 60, budget: { value: 60, label: "60 fps" }, tip });
384
+ $("#fps-legend").innerHTML = base ? '<span><i style="background:var(--series-1)"></i>This run</span><span><i style="background:var(--series-0)"></i>Baseline</span>' : "";
385
+ stackedColumns($("#chart-owners"), run.timeline, run.marks);
386
+ $("#owner-legend").innerHTML = GROUPS.map((g) => '<span><i style="background:' + seriesVar(g.slot) + '"></i>' + esc(g.label) + '</span>').join("");
387
+ if (run.filmstrip.length) {
388
+ $("#film").innerHTML = run.filmstrip.map((f) => '<figure><img loading="lazy" src="' + esc(f.src) + '" alt="frame at ' + f.t + ' s"><figcaption>' + fmt(f.t, 0) + 's</figcaption></figure>').join("");
389
+ } else $("#film-wrap").style.display = "none";
390
+ }
391
+
392
+ function renderFindings() {
393
+ const box = $("#findings");
394
+ if (!findings || !findings.findings || !findings.findings.length) {
395
+ box.innerHTML = '<div class="finding"><p>No diagnosis written yet — the automatic signals below point at where to look.</p><ul class="signals">' + run.signals.map((s) => "<li>" + esc(s) + "</li>").join("") + "</ul></div>";
396
+ return;
397
+ }
398
+ box.innerHTML = findings.findings.map((f) => {
399
+ const code = (f.code || []).map((c) => "<li>" + link(c.file, c.line, (c.label ? c.label + " — " : "") + shortPath(c.file) + (c.line ? ":" + c.line : "")) + "</li>").join("");
400
+ const diff = f.diff ? '<details><summary>The change</summary><pre class="code diff">' + f.diff.split("\n").map((l) => '<div class="row ' + (l.startsWith("+") && !l.startsWith("+++") ? "add" : l.startsWith("-") && !l.startsWith("---") ? "del" : "") + '"><span class="ln"></span>' + esc(l) + '</div>').join("") + '</pre></details>' : "";
401
+ return '<article class="finding" id="' + esc(f.id) + '"><header><span class="badge ' + esc(f.severity) + '">' + esc(f.severity) + '</span><span class="badge ' + esc(f.status) + '">' + esc(f.status) + '</span><h3>' + esc(f.id + " · " + f.title) + '</h3>' + (f.cost ? '<span class="cost">' + esc(f.cost) + '</span>' : "") + '</header>' +
402
+ (f.phases && f.phases.length ? '<div class="meta">phases: ' + esc(f.phases.join(", ")) + '</div>' : "") +
403
+ (f.cause ? "<p><strong>Why it is slow.</strong> " + esc(f.cause) + "</p>" : "") +
404
+ (f.evidence && f.evidence.length ? "<p><strong>Evidence.</strong></p><ul>" + f.evidence.map((e) => "<li>" + esc(e) + "</li>").join("") + "</ul>" : "") +
405
+ (code ? "<p><strong>Code.</strong></p><ul>" + code + "</ul>" : "") +
406
+ (f.fix ? "<p><strong>Fix.</strong> " + esc(f.fix) + "</p>" : "") +
407
+ (f.before || f.after ? '<div class="beforeafter">' + (f.before ? "<span>before: " + esc(f.before) + "</span>" : "") + (f.after ? "<span>after: " + esc(f.after) + "</span>" : "") + "</div>" : "") + diff + "</article>";
408
+ }).join("");
409
+ }
410
+
411
+ function renderPhases() {
412
+ $("#phases").innerHTML = run.phases.map((p) => {
413
+ const b = base && base.phases.find((q) => q.name === p.name);
414
+ const yours = p.lists.yoursTop.slice(0, 3).map((e) => "<li>" + esc(e.name) + " — " + fmt(e.msPerFrame, 2) + " ms/f</li>").join("");
415
+ const hot = p.lists.inclusiveTop.filter((e) => !e.shell && e.owner !== "program").slice(0, 3).map((e) => "<li>" + esc(e.name) + " — " + fmt(e.pctBusy) + "%</li>").join("");
416
+ const owners = p.lists.owners.slice(0, 4).map((o) => ownerChip(o.owner) + " " + fmt(o.pctBusy, 0) + "%").join(" ");
417
+ return '<div class="phase"><div class="name">' + esc(p.name) + ' <span class="meta">' + fmt(p.startSeconds) + "s · " + fmt(p.durationSeconds) + 's</span></div><div class="fps">' + fmt(p.frames.fps) + ' <span class="small">fps</span></div>' + delta(p.frames.fps, b && b.frames.fps, false) +
418
+ '<div class="small">CPU ' + fmt(p.frames.cpuMeanMs, 1) + " ms/f · p95 frame " + fmt(p.frames.intervalP95Ms) + " ms · busy " + fmt(p.busyPct, 0) + "%<br>draws " + fmt(p.frames.draws, 0) + " · particles " + fmt(p.frames.particles, 0) + (p.heap ? " · alloc " + fmt(p.heap.mbPerSecond, 0) + " MB/s" : "") + '</div><div class="small" style="margin-top:6px">' + owners + '</div>' +
419
+ (hot ? '<div class="small" style="margin-top:6px">Heaviest work</div><ol>' + hot + "</ol>" : "") + (yours ? '<div class="small" style="margin-top:6px">Your heaviest code</div><ol>' + yours + "</ol>" : "") + "</div>";
420
+ }).join("");
421
+ }
422
+
423
+ function renderOwners() {
424
+ const owners = run.overall.lists.owners.filter((o) => o.owner !== "idle");
425
+ const max = Math.max(...owners.map((o) => o.pctBusy), 1);
426
+ $("#owners").innerHTML = "<table><thead><tr><th>Who</th><th class='num'>ms</th><th class='num'>% busy</th><th class='num'>ms/frame</th><th style='width:40%'></th></tr></thead><tbody>" + owners.map((o) => {
427
+ const b = base && base.overall.lists.owners.find((q) => q.owner === o.owner);
428
+ return "<tr><td>" + ownerChip(o.owner) + "</td><td class='num'>" + fmt(o.ms, 0) + "</td><td class='num'>" + fmt(o.pctBusy) + "%</td><td class='num'>" + fmt(o.msPerFrame, 2) + (b ? " <span class='where'>(was " + fmt(b.msPerFrame, 2) + ")</span>" : "") + "</td><td><span class='bar' style='width:" + (o.pctBusy / max * 100).toFixed(1) + "%;background:" + seriesVar(groupOf(o.owner).slot) + "'></span></td></tr>";
429
+ }).join("") + "</tbody></table>";
430
+ }
431
+
432
+ function functionTable(rows, kind) {
433
+ return "<div class='scroll'><table><thead><tr><th>Function</th><th>Owner</th><th class='num'>ms</th><th class='num'>ms/frame</th><th class='num'>% busy</th>" + (kind === "self" ? "<th>Called by / your code behind it</th>" : kind === "yours" ? "<th>Spends it in</th>" : "<th class='num'>self ms</th>") + "</tr></thead><tbody>" + rows.map((r) => {
434
+ let extra = "";
435
+ if (kind === "self") extra = "<td class='where'>" + esc((r.callers || []).map((c) => c.name + " " + c.ms).join(" · ")) + ((r.yours || []).length ? "<br>yours: " + esc(r.yours.map((c) => c.name + " " + c.ms).join(" · ")) : "") + "</td>";
436
+ else if (kind === "yours") extra = "<td class='where'>own " + fmt(r.ownCodeMs) + " ms · " + esc((r.callees || []).slice(0, 4).map((c) => c.name + " " + c.ms).join(" · ")) + "</td>";
437
+ else extra = "<td class='num'>" + fmt(r.selfMs) + "</td>";
438
+ return "<tr><td><div class='fn'>" + esc(r.name) + "</div><div class='where'>" + link(r.file, r.line, r.file ? null : r.url + (r.line ? ":" + r.line : "")) + "</div></td><td>" + ownerChip(r.owner) + "</td><td class='num'>" + fmt(r.ms, 0) + "</td><td class='num'>" + fmt(r.msPerFrame, 2) + "</td><td class='num'>" + fmt(r.pctBusy) + "%</td>" + extra + "</tr>";
439
+ }).join("") + "</tbody></table></div>";
440
+ }
441
+
442
+ function renderFunctions() {
443
+ $("#yours").innerHTML = functionTable(run.overall.lists.yoursTop.slice(0, 20), "yours");
444
+ $("#self").innerHTML = functionTable(run.overall.lists.selfTop.slice(0, 25), "self");
445
+ $("#subtrees").innerHTML = functionTable(run.overall.lists.inclusiveTop.filter((r) => !r.shell && r.owner !== "program").slice(0, 25), "inclusive");
446
+ $("#excerpts").innerHTML = run.excerpts.slice(0, 12).map((x) => "<details><summary>" + esc(x.name) + " — " + link(x.file, x.from + 2) + "</summary><pre class='code'>" + x.rows.map((row) => "<div class='row" + (row.hotMs ? " hot" : "") + "'><span class='ln'>" + row.number + "</span>" + esc(row.text) + (row.hotMs ? "<span class='ms'>" + fmt(row.hotMs) + " ms</span>" : "") + "</div>").join("") + "</pre></details>").join("") || "<p class='meta'>No source excerpts (no local files resolved).</p>";
447
+ }
448
+
449
+ function renderHeap() {
450
+ if (!run.heap) { $("#heap").innerHTML = "<p class='meta'>Allocation sampling was off.</p>"; return; }
451
+ const table = (rows) => "<table><thead><tr><th>Function</th><th>Owner</th><th class='num'>MB</th><th class='num'>MB/s</th></tr></thead><tbody>" + rows.map((r) => "<tr><td><div class='fn'>" + esc(r.name) + "</div><div class='where'>" + link(r.file, r.line) + "</div></td><td>" + ownerChip(r.owner) + "</td><td class='num'>" + fmt(r.mb) + "</td><td class='num'>" + fmt(r.mbPerSecond, 2) + "</td></tr>").join("") + "</tbody></table>";
452
+ const racing = run.phases.filter((p) => p.heap && /^race|racing|takeoff|countdown/.test(p.name));
453
+ $("#heap").innerHTML = "<p class='meta'>" + fmt(run.heap.totalMb, 0) + " MB allocated over the run (" + fmt(run.heap.mbPerSecond, 0) + " MB/s, collected objects " + (run.capture.heapIncludesCollected ? "included" : "not included") + "). Per phase: " + run.phases.filter((p) => p.heap).map((p) => esc(p.name) + " " + fmt(p.heap.mbPerSecond, 0) + " MB/s").join(" · ") + "</p><div class='two'><div><h3>Allocating functions (whole run)</h3>" + table(run.heap.selfTop.slice(0, 12)) + "</div><div><h3>Your code behind the allocations</h3>" + table(run.heap.yoursTop.slice(0, 12)) + "</div></div>" +
454
+ (racing.length ? "<h3 style='margin-top:16px'>While racing (" + esc(racing.map((p) => p.name).join(", ")) + ")</h3>" + table(racing.flatMap((p) => p.heap.selfTop.slice(0, 4).map((r) => ({ ...r, name: r.name + " [" + p.name + "]" })))) : "");
455
+ }
456
+
457
+ function renderWorst() {
458
+ $("#worst").innerHTML = "<div class='scroll'><table><thead><tr><th class='num'>at</th><th>Phase</th><th class='num'>CPU ms</th><th class='num'>gap ms</th><th>Filled by</th><th>Your code in it</th></tr></thead><tbody>" + run.worstFrames.map((f) => "<tr><td class='num'>" + fmt(f.t) + "s</td><td>" + esc(f.phase || "") + "</td><td class='num'>" + fmt(f.cpuMs) + "</td><td class='num'>" + fmt(f.intervalMs) + "</td><td class='where'>" + esc(f.top.map((e) => e.name + " " + e.ms).join(" · ")) + "</td><td class='where'>" + (f.yours.map((e) => link(e.file, e.line, e.name + " " + e.ms + " ms")).join(" · ") || "–") + "</td></tr>").join("") + "</tbody></table></div>";
459
+ }
460
+
461
+ function renderShots() {
462
+ if (!run.shots.length) { $("#shots-wrap").style.display = "none"; return; }
463
+ $("#shots").innerHTML = run.shots.map((s) => {
464
+ const before = base && base.shots.find((b) => b.name === s.name);
465
+ return (before ? "<figure><img loading='lazy' src='" + esc(before.src) + "' alt=''><figcaption>baseline · " + esc(s.name) + "</figcaption></figure>" : "") + "<figure><img loading='lazy' src='" + esc(s.src) + "' alt=''><figcaption>" + (base ? "this run · " : "") + esc(s.name) + "</figcaption></figure>";
466
+ }).join("");
467
+ }
468
+
469
+ function renderWarm() {
470
+ if (!warm) { $("#warm-wrap").style.display = "none"; return; }
471
+ const rows = run.phases.map((p) => { const w = warm.phases.find((q) => q.name === p.name); return "<tr><td>" + esc(p.name) + "</td><td class='num'>" + fmt(p.frames.fps) + "</td><td class='num'>" + (w ? fmt(w.frames.fps) : "–") + "</td><td class='num'>" + fmt(p.frames.cpuMeanMs) + "</td><td class='num'>" + (w ? fmt(w.frames.cpuMeanMs) : "–") + "</td><td class='num'>" + fmt(p.durationSeconds) + "s</td><td class='num'>" + (w ? fmt(w.durationSeconds) + "s" : "–") + "</td></tr>"; }).join("");
472
+ $("#warm").innerHTML = "<p class='meta'>Same scenario, second load in the same browser: the HTTP cache, compiled shaders and JIT are warm. Phases that are much faster warm pay first-use costs (downloads, decoding, shader compiles); phases that are just as slow warm are steady per-frame work.</p><table><thead><tr><th>Phase</th><th class='num'>cold fps</th><th class='num'>warm fps</th><th class='num'>cold CPU ms/f</th><th class='num'>warm CPU ms/f</th><th class='num'>cold length</th><th class='num'>warm length</th></tr></thead><tbody>" + rows + "</tbody></table>";
473
+ }
474
+
475
+ function renderMeta() {
476
+ const c = run.capture;
477
+ const census = c.census || {};
478
+ $("#capture").innerHTML = "<table><tbody>" + [
479
+ ["Scenario", (c.scenario || "") + " — " + (c.scenarioDescription || "")],
480
+ ["URL", c.url], ["Engine", c.engine + (census.adapter ? " · " + census.adapter.slice(0, 160) : "")],
481
+ ["Browser", c.browser + " · " + c.platform], ["Viewport", c.viewport.width + "×" + c.viewport.height + " @" + c.viewport.deviceScaleFactor + "x · render " + (census.renderSize || []).join("×")],
482
+ ["Scene at end", "meshes " + (census.meshes ?? "–") + " · materials " + (census.materials ?? "–") + " · textures " + (census.textures ?? "–") + " · lights " + (census.lights ?? "–") + " · shadow generators " + (census.shadowGenerators ?? "–") + " · particle systems " + ((census.particleSystems || []).length) + " · compiled effects " + (census.compiledEffects ?? "–")],
483
+ ["Sampling", c.samplingIntervalUs + " µs CPU sampling · " + c.wallSeconds + " s recorded"],
484
+ ["CPU profile", "<span class='where'>" + esc(DATA.run.cpuprofile) + "</span> — open in Chrome DevTools › Performance › Load profile"],
485
+ ["Console errors", (c.consoleErrors || []).filter((e) => e.type !== "warning").length + " errors, " + (c.consoleErrors || []).filter((e) => e.type === "warning").length + " warnings"],
486
+ ].map(([k, v]) => "<tr><th>" + esc(k) + "</th><td>" + (k === "CPU profile" ? v : esc(v)) + "</td></tr>").join("") + "</tbody></table>";
487
+ }
488
+
489
+ $("#theme").addEventListener("click", () => {
490
+ const root = document.documentElement;
491
+ const dark = root.dataset.theme ? root.dataset.theme === "dark" : !matchMedia("(prefers-color-scheme: light)").matches;
492
+ root.dataset.theme = dark ? "light" : "dark";
493
+ });
494
+ renderTiles(); renderFindings(); renderTimeline(); renderPhases(); renderOwners(); renderFunctions(); renderHeap(); renderWorst(); renderShots(); renderWarm(); renderMeta();
495
+ let resizeTimer; addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(renderTimeline, 150); });
496
+ `;
497
+
498
+ /** Builds the HTML page. */
499
+ function buildPage({ title, verdict, data }) {
500
+ const json = JSON.stringify(data).replace(/</g, "\\u003c");
501
+ return `<!doctype html>
502
+ <html lang="en">
503
+ <head>
504
+ <meta charset="utf-8">
505
+ <meta name="viewport" content="width=device-width, initial-scale=1">
506
+ <title>${escapeHtml(title)}</title>
507
+ <style>${STYLES}${PROGRESS_STYLES}</style>
508
+ </head>
509
+ <body>
510
+ <main>
511
+ <header class="top">
512
+ <h1>${escapeHtml(title)}</h1>
513
+ <button class="toggle" id="theme" type="button">Light / dark</button>
514
+ </header>
515
+ ${progressMarkup()}
516
+ <div class="meta">${escapeHtml(data.run.capture.capturedAt)} · ${escapeHtml(data.run.capture.engine || "")} · scenario ${escapeHtml(data.run.capture.scenario || "")} · ${escapeHtml(data.run.capture.wallSeconds)} s${data.baseline ? " · compared with baseline " + escapeHtml(data.baseline.capture.capturedAt) : ""}</div>
517
+ ${verdict ? `<div class="verdict">${escapeHtml(verdict)}</div>` : ""}
518
+ ${[["This run", data.run], ["The baseline", data.baseline]].filter(([, run]) => run && run.capture.disturbed).map(([who, run]) => `<div class="verdict disturbed">${escapeHtml(who)} restarted mid-capture (${escapeHtml(run.capture.disturbed.reason)}), so its numbers are not comparable.</div>`).join("")}
519
+ <section class="tiles" id="tiles"></section>
520
+
521
+ <h2>The bottlenecks</h2>
522
+ <section id="findings"></section>
523
+
524
+ <h2>Frame rate over the run</h2>
525
+ <section class="panel"><div class="legend" id="fps-legend"></div><div id="chart-fps"></div></section>
526
+
527
+ <h2>Who uses the main thread, second by second</h2>
528
+ <section class="panel"><div class="legend" id="owner-legend"></div><div id="chart-owners"></div>
529
+ <div id="film-wrap"><div class="film" id="film"></div></div></section>
530
+
531
+ <h2>Phases</h2>
532
+ <section class="phases" id="phases"></section>
533
+
534
+ <h2>Who owns the time (whole run)</h2>
535
+ <section class="panel" id="owners"></section>
536
+
537
+ <h2>Your code — time spent, including the library work it triggers</h2>
538
+ <section class="panel" id="yours"></section>
539
+ <section id="excerpts" style="margin-top:10px"></section>
540
+
541
+ <h2>Heaviest functions — self time</h2>
542
+ <section class="panel" id="self"></section>
543
+
544
+ <h2>Heaviest subtrees — inclusive time</h2>
545
+ <section class="panel" id="subtrees"></section>
546
+
547
+ <h2>Allocations (garbage-collector pressure)</h2>
548
+ <section class="panel" id="heap"></section>
549
+
550
+ <h2>Worst frames</h2>
551
+ <section class="panel" id="worst"></section>
552
+
553
+ <div id="warm-wrap"><h2>Cold load vs warm load</h2><section class="panel" id="warm"></section></div>
554
+ <div id="shots-wrap"><h2>Snapshots</h2><section class="shots" id="shots"></section></div>
555
+
556
+ <h2>Capture</h2>
557
+ <section class="panel" id="capture"></section>
558
+ </main>
559
+ <div class="tooltip" id="tooltip" role="status"></div>
560
+ <script type="application/json" id="bt-data">${json}</script>
561
+ <script>${SCRIPT}</script>
562
+ <script>${PROGRESS_SCRIPT}</script>
563
+ </body>
564
+ </html>`;
565
+ }
566
+
567
+ /**
568
+ * The screenshots of a run directory (its `shots/`, or the directory itself), as page entries relative to the report.
569
+ * @returns {{name: string, src: string}[]}
570
+ */
571
+ function shotsFrom(dir, reportDir) {
572
+ const folder = fs.existsSync(path.join(dir, "shots")) ? path.join(dir, "shots") : dir;
573
+ if (!fs.existsSync(folder)) throw new Error(`No screenshots at ${dir}`);
574
+ return fs.readdirSync(folder).filter((name) => name.endsWith(".png")).sort().map((name) => ({
575
+ name: name.replace(/\.png$/, ""), src: path.relative(reportDir, path.join(folder, name)).split(path.sep).join("/"),
576
+ }));
577
+ }
578
+
579
+ /** Entry point. */
580
+ function main() {
581
+ const flags = parseArguments(process.argv.slice(2));
582
+ if (!flags.analysis) throw new Error("Pass --analysis <analysis.json> [--out <dashboard.html>]");
583
+ const runDir = (file) => (file ? path.dirname(path.resolve(file)) : null);
584
+ // Default: the slug's dashboard.html — next to the `data/` folder that holds the analysis's runs.
585
+ const configFile = findUp(runDir(flags.analysis), "profile.config.json"); // <slug>/data/profile.config.json
586
+ const slugDir = configFile ? path.dirname(path.dirname(configFile)) : slugDirOfRun(runDir(flags.analysis));
587
+ const outFile = path.resolve(flags.out || (slugDir ? path.join(slugDir, "dashboard.html") : "dashboard.html"));
588
+ const reportDir = path.dirname(outFile);
589
+ fs.mkdirSync(reportDir, { recursive: true });
590
+ const analysis = readJson(flags.analysis);
591
+ const baseline = readJson(flags.baseline);
592
+ const warm = readJson(flags.warm);
593
+ const findings = readJson(flags.findings);
594
+ const title = flags.title || (findings && findings.title) || `Performance report — ${analysis.capture.scenario || "scenario"}`;
595
+ const data = {
596
+ run: pageData(analysis, reportDir, runDir(flags.analysis)),
597
+ baseline: baseline ? pageData(baseline, reportDir, runDir(flags.baseline)) : null,
598
+ warm: warm ? pageData(warm, reportDir, runDir(flags.warm)) : null,
599
+ findings,
600
+ groups: OWNER_GROUPS,
601
+ };
602
+ if (flags.snapshots) data.run.shots = shotsFrom(path.resolve(flags.snapshots), reportDir);
603
+ if (flags["snapshots-before"]) {
604
+ // Shown beside this run's shots of the same names (needs --baseline, whose own shots they replace).
605
+ if (data.baseline) data.baseline.shots = shotsFrom(path.resolve(flags["snapshots-before"]), reportDir);
606
+ }
607
+ fs.writeFileSync(outFile, buildPage({ title, verdict: findings && findings.summary, data }));
608
+ process.stdout.write(`wrote ${outFile}\n`);
609
+ }
610
+
611
+ main();