sugikit 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +29 -21
  2. package/README.md +45 -0
  3. package/dist/api/browser.d.ts +5 -0
  4. package/dist/api/browser.js +5 -0
  5. package/dist/api/rules.d.ts +12 -0
  6. package/dist/api/rules.js +14 -0
  7. package/dist/auth.d.ts +156 -0
  8. package/dist/auth.js +547 -0
  9. package/dist/browser.d.ts +25 -0
  10. package/dist/browser.js +120 -0
  11. package/dist/check.d.ts +21 -0
  12. package/dist/check.js +89 -0
  13. package/dist/convert-probe.d.ts +21 -0
  14. package/dist/convert-probe.js +647 -0
  15. package/dist/fetch.d.ts +6 -0
  16. package/dist/fetch.js +22 -0
  17. package/dist/framework.d.ts +2 -0
  18. package/dist/framework.js +17 -0
  19. package/dist/gather.d.ts +48 -0
  20. package/dist/gather.js +211 -0
  21. package/dist/html.d.ts +17 -0
  22. package/dist/html.js +43 -0
  23. package/dist/http.d.ts +36 -0
  24. package/dist/http.js +57 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.js +331 -0
  27. package/dist/links.d.ts +8 -0
  28. package/dist/links.js +69 -0
  29. package/dist/polish-run.d.ts +115 -0
  30. package/dist/polish-run.js +357 -0
  31. package/dist/probe.d.ts +14 -0
  32. package/dist/probe.js +457 -0
  33. package/dist/psi-scores.d.ts +4 -0
  34. package/dist/psi-scores.js +7 -0
  35. package/dist/psi.d.ts +56 -0
  36. package/dist/psi.js +192 -0
  37. package/dist/release.d.ts +1 -0
  38. package/dist/release.js +5 -0
  39. package/dist/render.d.ts +28 -0
  40. package/dist/render.js +270 -0
  41. package/dist/report.d.ts +227 -0
  42. package/dist/report.js +69 -0
  43. package/dist/rules/convert-render.d.ts +100 -0
  44. package/dist/rules/convert-render.js +279 -0
  45. package/dist/rules/convert.d.ts +15 -0
  46. package/dist/rules/convert.js +322 -0
  47. package/dist/rules/fixes.d.ts +16 -0
  48. package/dist/rules/fixes.js +536 -0
  49. package/dist/rules/geo.d.ts +15 -0
  50. package/dist/rules/geo.js +112 -0
  51. package/dist/rules/polish.d.ts +59 -0
  52. package/dist/rules/polish.js +223 -0
  53. package/dist/rules/robots.d.ts +14 -0
  54. package/dist/rules/robots.js +69 -0
  55. package/dist/rules/seo.d.ts +31 -0
  56. package/dist/rules/seo.js +208 -0
  57. package/dist/rules/types.d.ts +55 -0
  58. package/dist/rules/types.js +78 -0
  59. package/dist/score.d.ts +6 -0
  60. package/dist/score.js +23 -0
  61. package/dist/skills.d.ts +9 -0
  62. package/dist/skills.js +22 -0
  63. package/package.json +64 -4
  64. package/skills/INSTALL_PROMPT.md +9 -0
  65. package/skills/sugikit/SKILL.md +147 -0
  66. package/skills/sugikit/references/convert.md +127 -0
  67. package/skills/sugikit/references/geo.md +97 -0
  68. package/skills/sugikit/references/next.md +254 -0
  69. package/skills/sugikit/references/pagespeed.md +94 -0
  70. package/skills/sugikit/references/polish.md +123 -0
  71. package/skills/sugikit/references/seo.md +150 -0
  72. package/skills/sugikit/references/tanstack-start.md +246 -0
package/dist/psi.js ADDED
@@ -0,0 +1,192 @@
1
+ import { isIP } from "node:net";
2
+ import { STRATEGIES } from "./psi-scores.js";
3
+ import { auditFix } from "./rules/fixes.js";
4
+ import { result } from "./rules/types.js";
5
+ export { STRATEGIES, minScore } from "./psi-scores.js";
6
+ export const PSI_ENDPOINT = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
7
+ // The v5 API docs list only these four categories (no agentic browsing category as of 2026-11).
8
+ export const PSI_CATEGORIES = ["performance", "accessibility", "best-practices", "seo"];
9
+ export const DEFAULT_RUNS = 3;
10
+ export const MAX_AUDIT_FINDINGS = 25;
11
+ const TIMEOUT_MS = 60_000;
12
+ const RETRY_DELAY_MS = 2_000;
13
+ const SKIPPED_MODES = new Set(["informative", "notApplicable", "manual"]);
14
+ function isPrivateIp(host) {
15
+ const version = isIP(host);
16
+ if (version === 4) {
17
+ const [a = 0, b = 0] = host.split(".").map(Number);
18
+ return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || a === 0;
19
+ }
20
+ if (version === 6) {
21
+ const lower = host.toLowerCase();
22
+ return lower === "::1" || lower === "::" || /^f[cd]/.test(lower) || /^fe[89ab]/.test(lower);
23
+ }
24
+ return false;
25
+ }
26
+ export function isPrivateUrl(url) {
27
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
28
+ return (host === "localhost" ||
29
+ host.endsWith(".localhost") ||
30
+ host.endsWith(".local") ||
31
+ isPrivateIp(host));
32
+ }
33
+ export function redact(text, key) {
34
+ const withoutParam = text.replace(/([?&]key=)[^&\s"']*/g, "$1REDACTED");
35
+ return key ? withoutParam.split(key).join("REDACTED") : withoutParam;
36
+ }
37
+ function requestUrl(url, strategy, key) {
38
+ const params = new URLSearchParams({ url, strategy });
39
+ for (const category of PSI_CATEGORIES)
40
+ params.append("category", category);
41
+ params.set("key", key);
42
+ return `${PSI_ENDPOINT}?${params.toString()}`;
43
+ }
44
+ function toScore(value) {
45
+ return typeof value === "number" ? Math.round(value * 100) : undefined;
46
+ }
47
+ function parseRun(body) {
48
+ const lighthouse = body?.lighthouseResult;
49
+ const categories = lighthouse?.categories ?? {};
50
+ const performance = toScore(categories.performance?.score);
51
+ const accessibility = toScore(categories.accessibility?.score);
52
+ const bestPractices = toScore(categories["best-practices"]?.score);
53
+ const seo = toScore(categories.seo?.score);
54
+ if (!lighthouse || performance === undefined || accessibility === undefined || bestPractices === undefined || seo === undefined) {
55
+ throw new Error("PageSpeed response has no Lighthouse category scores");
56
+ }
57
+ const field = body
58
+ .loadingExperience?.metrics?.LARGEST_CONTENTFUL_PAINT_MS?.percentile;
59
+ return {
60
+ scores: { performance, accessibility, bestPractices, seo },
61
+ lighthouse,
62
+ ...(typeof field === "number" ? { fieldLcpMs: field } : {}),
63
+ };
64
+ }
65
+ function wait(ms) {
66
+ return new Promise((resolve) => setTimeout(resolve, ms));
67
+ }
68
+ async function callOnce(fetcher, url) {
69
+ const response = await fetcher(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
70
+ if (response.status === 429 || response.status >= 500)
71
+ return { retry: true, error: `HTTP ${response.status}` };
72
+ if (response.status < 200 || response.status >= 300) {
73
+ const body = (await response.json().catch(() => undefined));
74
+ return { retry: false, error: `HTTP ${response.status}${body?.error?.message ? `: ${body.error.message}` : ""}` };
75
+ }
76
+ return { retry: false, run: parseRun(await response.json()) };
77
+ }
78
+ async function callPsi(fetcher, url, retryDelayMs) {
79
+ let attempt = await callOnce(fetcher, url);
80
+ if (attempt.retry) {
81
+ await wait(retryDelayMs);
82
+ attempt = await callOnce(fetcher, url);
83
+ }
84
+ if (!attempt.run)
85
+ throw new Error(attempt.error ?? "no response");
86
+ return attempt.run;
87
+ }
88
+ async function runStrategy(target, strategy, runs, key, fetcher, retryDelayMs) {
89
+ const done = [];
90
+ const errors = [];
91
+ for (let i = 0; i < runs; i += 1) {
92
+ try {
93
+ done.push(await callPsi(fetcher, requestUrl(target, strategy, key), retryDelayMs));
94
+ }
95
+ catch (error) {
96
+ errors.push(redact(error.message, key));
97
+ }
98
+ }
99
+ return { runs: done, errors };
100
+ }
101
+ export function bestScores(runs) {
102
+ const best = (pick) => Math.max(...runs.map((run) => pick(run.scores)));
103
+ return {
104
+ performance: best((s) => s.performance),
105
+ accessibility: best((s) => s.accessibility),
106
+ bestPractices: best((s) => s.bestPractices),
107
+ seo: best((s) => s.seo),
108
+ };
109
+ }
110
+ function bestRun(runs) {
111
+ const total = (run) => run.scores.performance + run.scores.accessibility + run.scores.bestPractices + run.scores.seo;
112
+ return runs.reduce((top, run) => (top === undefined || total(run) > total(top) ? run : top), undefined);
113
+ }
114
+ export function auditResults(lighthouseRuns, target, framework) {
115
+ const seen = new Set();
116
+ const found = [];
117
+ for (const lighthouse of lighthouseRuns) {
118
+ for (const category of PSI_CATEGORIES) {
119
+ for (const ref of lighthouse.categories?.[category]?.auditRefs ?? []) {
120
+ const audit = lighthouse.audits?.[ref.id];
121
+ if (!audit || seen.has(ref.id))
122
+ continue;
123
+ if (typeof audit.score !== "number" || audit.score >= 0.9)
124
+ continue;
125
+ if (audit.scoreDisplayMode && SKIPPED_MODES.has(audit.scoreDisplayMode))
126
+ continue;
127
+ seen.add(ref.id);
128
+ found.push(result(`pagespeed/${ref.id}`, audit.score < 0.5 ? "error" : "warn", false, audit.title ?? ref.id, {
129
+ url: target,
130
+ ...(audit.displayValue ? { evidence: audit.displayValue } : {}),
131
+ fix: auditFix(ref.id, audit.description ?? "", framework),
132
+ }));
133
+ }
134
+ }
135
+ }
136
+ const rank = { error: 0, warn: 1, info: 2 };
137
+ return found.sort((a, b) => rank[a.severity] - rank[b.severity]).slice(0, MAX_AUDIT_FINDINGS);
138
+ }
139
+ const defaultFetcher = (url, init) => fetch(url, init);
140
+ export async function runPsi(target, options = {}) {
141
+ const runs = Math.max(1, Math.floor(options.runs ?? DEFAULT_RUNS));
142
+ const framework = options.framework ?? "unknown";
143
+ if (isPrivateUrl(target)) {
144
+ return {
145
+ results: [
146
+ result("pagespeed/local-url", "info", false, "PageSpeed needs a public URL; deploy a preview and run `sugikit psi <url>`", {
147
+ url: target,
148
+ }),
149
+ ],
150
+ };
151
+ }
152
+ const key = options.key ?? process.env.PSI_API_KEY;
153
+ if (!key) {
154
+ return {
155
+ results: [
156
+ result("pagespeed/no-key", "info", false, "PageSpeed skipped: no PSI_API_KEY. Get a free key at https://developers.google.com/speed/docs/insights/v5/get-started and set PSI_API_KEY", { url: target }),
157
+ ],
158
+ };
159
+ }
160
+ const fetcher = options.fetcher ?? defaultFetcher;
161
+ const retryDelayMs = options.retryDelayMs ?? RETRY_DELAY_MS;
162
+ const [mobile, desktop] = await Promise.all(STRATEGIES.map((strategy) => runStrategy(target, strategy, runs, key, fetcher, retryDelayMs)));
163
+ if (!mobile || !desktop || mobile.runs.length === 0 || desktop.runs.length === 0) {
164
+ const errors = [...(mobile?.errors ?? []), ...(desktop?.errors ?? [])];
165
+ return {
166
+ results: [
167
+ result("pagespeed/api-error", "warn", false, `PageSpeed Insights returned no result for ${mobile?.runs.length ? "desktop" : "mobile"}`, {
168
+ url: target,
169
+ ...(errors.length ? { evidence: [...new Set(errors)].join("; ") } : {}),
170
+ }),
171
+ ],
172
+ };
173
+ }
174
+ const bestMobile = bestRun(mobile.runs);
175
+ const lighthouseRuns = [bestMobile, bestRun(desktop.runs)].flatMap((run) => (run ? [run.lighthouse] : []));
176
+ const labLcp = bestMobile?.lighthouse.audits?.["largest-contentful-paint"]?.numericValue;
177
+ const fieldLcp = mobile.runs.find((run) => run.fieldLcpMs !== undefined)?.fieldLcpMs;
178
+ const lcp = {
179
+ ...(fieldLcp !== undefined ? { fieldMs: fieldLcp } : {}),
180
+ ...(typeof labLcp === "number" ? { labMs: Math.round(labLcp) } : {}),
181
+ };
182
+ return {
183
+ ...(lcp.fieldMs !== undefined || lcp.labMs !== undefined ? { lcp } : {}),
184
+ results: auditResults(lighthouseRuns, target, framework),
185
+ pagespeed: {
186
+ mobile: bestScores(mobile.runs),
187
+ desktop: bestScores(desktop.runs),
188
+ runs,
189
+ method: `best of ${runs}`,
190
+ },
191
+ };
192
+ }
@@ -0,0 +1 @@
1
+ export declare const RELEASE_DATE: string | undefined;
@@ -0,0 +1,5 @@
1
+ // The CLI release date (YYYY-MM-DD). The build replaces the placeholder in dist/release.js
2
+ // (scripts/stamp-release.mjs, from SUGIKIT_RELEASE_DATE or the build day in UTC).
3
+ // An unstamped source run (tests, local dev) has no release date and skips the updates check.
4
+ const STAMP = "2026-11-21";
5
+ export const RELEASE_DATE = /^\d{4}-\d{2}-\d{2}$/.test(STAMP) ? STAMP : undefined;
@@ -0,0 +1,28 @@
1
+ import type { Finding, Report } from "./report.js";
2
+ export interface ImageRef {
3
+ src: string;
4
+ width: number;
5
+ height: number;
6
+ }
7
+ export interface RenderRun {
8
+ report: Report;
9
+ psi?: Report;
10
+ images?: Record<string, ImageRef | undefined>;
11
+ }
12
+ export interface RenderInput {
13
+ before?: RenderRun;
14
+ after: RenderRun;
15
+ }
16
+ export interface FindingSplit {
17
+ fixed: Finding[];
18
+ open: Finding[];
19
+ added: Finding[];
20
+ }
21
+ export declare function escapeHtml(text: string): string;
22
+ export declare function pngSizeFromBytes(bytes: Uint8Array): {
23
+ width: number;
24
+ height: number;
25
+ } | undefined;
26
+ export declare function polishRan(report: Report): boolean;
27
+ export declare function splitFindings(before: Finding[], after: Finding[]): FindingSplit;
28
+ export declare function renderHtml(input: RenderInput): string;
package/dist/render.js ADDED
@@ -0,0 +1,270 @@
1
+ // Worker-safe report page renderer: reads no files. The CLI wrapper in html.ts reads PNG sizes from disk.
2
+ import { minScore, STRATEGIES } from "./psi-scores.js";
3
+ const PNG_SIGNATURE = "89504e470d0a1a0a";
4
+ const PSI_ROWS = [
5
+ { key: "performance", label: "Performance" },
6
+ { key: "accessibility", label: "Accessibility" },
7
+ { key: "bestPractices", label: "Best practices" },
8
+ { key: "seo", label: "SEO" },
9
+ ];
10
+ export function escapeHtml(text) {
11
+ return text
12
+ .replace(/&/g, "&amp;")
13
+ .replace(/</g, "&lt;")
14
+ .replace(/>/g, "&gt;")
15
+ .replace(/"/g, "&quot;")
16
+ .replace(/'/g, "&#39;");
17
+ }
18
+ // Reads width and height from the IHDR chunk of PNG bytes (the first 24 bytes are enough).
19
+ export function pngSizeFromBytes(bytes) {
20
+ if (bytes.length < 24)
21
+ return undefined;
22
+ const hex = Array.from(bytes.subarray(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
23
+ const chunk = String.fromCharCode(...bytes.subarray(12, 16));
24
+ if (hex !== PNG_SIGNATURE || chunk !== "IHDR")
25
+ return undefined;
26
+ const view = new DataView(bytes.buffer, bytes.byteOffset, 24);
27
+ return { width: view.getUint32(16), height: view.getUint32(20) };
28
+ }
29
+ export function polishRan(report) {
30
+ return report.states !== undefined || report.findings.some((f) => f.category === "polish");
31
+ }
32
+ export function splitFindings(before, after) {
33
+ const afterIds = new Set(after.map((f) => f.id));
34
+ const beforeIds = new Set(before.map((f) => f.id));
35
+ return {
36
+ fixed: before.filter((f) => !afterIds.has(f.id)),
37
+ open: after.filter((f) => beforeIds.has(f.id)),
38
+ added: after.filter((f) => !beforeIds.has(f.id)),
39
+ };
40
+ }
41
+ function toRun(input) {
42
+ const ids = new Set(input.report.findings.map((f) => f.id));
43
+ const psiFindings = input.psi?.findings.filter((f) => !ids.has(f.id)) ?? [];
44
+ const pagespeed = input.psi?.scores.pagespeed ?? input.report.scores.pagespeed;
45
+ return {
46
+ report: input.report,
47
+ images: input.images ?? {},
48
+ findings: [...input.report.findings, ...psiFindings],
49
+ ...(pagespeed ? { pagespeed } : {}),
50
+ };
51
+ }
52
+ function rating(score) {
53
+ if (score >= 90)
54
+ return "good";
55
+ if (score >= 50)
56
+ return "ok";
57
+ return "bad";
58
+ }
59
+ function scoreSpan(score) {
60
+ if (score === undefined)
61
+ return `<span class="none">n/a</span>`;
62
+ return `<span class="${rating(score)}">${score}</span>`;
63
+ }
64
+ function deltaText(before, after) {
65
+ if (before === undefined || after === undefined)
66
+ return "";
67
+ const delta = after - before;
68
+ return delta === 0 ? "no change" : `${delta > 0 ? "+" : ""}${delta}`;
69
+ }
70
+ function formatDate(iso) {
71
+ return `<span class="date">${escapeHtml(`${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`)}</span>`;
72
+ }
73
+ const CARD_LABELS = {
74
+ polish: "Polish",
75
+ seo: "SEO",
76
+ geo: "GEO",
77
+ convert: "Convert",
78
+ pagespeed: "PageSpeed (lowest)",
79
+ };
80
+ function categoryScore(run, category) {
81
+ if (category === "pagespeed")
82
+ return run.pagespeed ? minScore(run.pagespeed) : undefined;
83
+ if (category === "polish" && !polishRan(run.report))
84
+ return undefined;
85
+ return run.report.scores[category];
86
+ }
87
+ function scoreCards(before, after) {
88
+ const categories = ["polish", "seo", "geo", "convert", "pagespeed"];
89
+ const cards = categories
90
+ .filter((category) => category !== "pagespeed" || after.pagespeed || before?.pagespeed)
91
+ // Reports from before the convert checks have no convert score.
92
+ .filter((category) => category !== "convert" || after.report.scores.convert !== undefined || before?.report.scores.convert !== undefined)
93
+ .map((category) => {
94
+ const now = categoryScore(after, category);
95
+ const was = before ? categoryScore(before, category) : undefined;
96
+ const label = CARD_LABELS[category];
97
+ const values = before ? `${scoreSpan(was)} <span class="arrow" aria-label="to">&#8594;</span> ${scoreSpan(now)}` : scoreSpan(now);
98
+ const delta = before ? deltaText(was, now) : "";
99
+ const note = now === undefined ? "skipped" : `${rating(now)}${delta ? `, ${delta}` : ""}`;
100
+ return `<div class="card"><h3>${label}</h3><p class="score">${values}</p><p class="note">${escapeHtml(note)}</p></div>`;
101
+ });
102
+ return `<section aria-labelledby="scores"><h2 id="scores">Scores</h2><div class="cards">${cards.join("")}</div>
103
+ <p class="legend">90 and up is good, 50 to 89 is ok, under 50 is bad.</p></section>`;
104
+ }
105
+ function psiTable(before, after) {
106
+ if (!after.pagespeed && !before?.pagespeed)
107
+ return "";
108
+ const runs = (run) => (run?.pagespeed ? escapeHtml(run.pagespeed.method) : "not run");
109
+ const cell = (run, strategy, key) => `<td>${scoreSpan(run?.pagespeed?.[strategy][key])}</td>`;
110
+ const head = before
111
+ ? `<tr><th scope="col">Category</th><th scope="col">Mobile before</th><th scope="col">Mobile after</th><th scope="col">Desktop before</th><th scope="col">Desktop after</th></tr>`
112
+ : `<tr><th scope="col">Category</th><th scope="col">Mobile</th><th scope="col">Desktop</th></tr>`;
113
+ const rows = PSI_ROWS.map(({ key, label }) => {
114
+ const cells = before
115
+ ? [cell(before, "mobile", key), cell(after, "mobile", key), cell(before, "desktop", key), cell(after, "desktop", key)]
116
+ : [cell(after, "mobile", key), cell(after, "desktop", key)];
117
+ return `<tr><th scope="row">${label}</th>${cells.join("")}</tr>`;
118
+ });
119
+ const method = before ? `Before: ${runs(before)}. After: ${runs(after)}.` : `${runs(after)}.`;
120
+ return `<section aria-labelledby="pagespeed"><h2 id="pagespeed">PageSpeed Insights</h2>
121
+ <table><thead>${head}</thead><tbody>${rows.join("")}</tbody></table>
122
+ <p class="legend">Best score per category, ${method}</p></section>`;
123
+ }
124
+ function findingItem(finding, withFix) {
125
+ const fix = withFix ? `<p class="fix">Fix: ${escapeHtml(finding.fix.summary)}</p>` : "";
126
+ const owner = withFix && finding.needsOwner ? `<p class="owner">Your turn: this needs facts only the site owner has.</p>` : "";
127
+ const source = finding.source ? `<p class="source">Source: ${escapeHtml(finding.source)}</p>` : "";
128
+ return `<li><p class="finding"><span class="sev ${finding.severity}">${finding.severity}</span> <code>${escapeHtml(finding.id)}</code></p>
129
+ <p>${escapeHtml(finding.message)}</p>${fix}${owner}${source}</li>`;
130
+ }
131
+ function findingList(id, title, findings, withFix) {
132
+ const body = findings.length === 0
133
+ ? `<p class="empty">None.</p>`
134
+ : `<ul class="findings">${findings.map((f) => findingItem(f, withFix)).join("")}</ul>`;
135
+ return `<section aria-labelledby="${id}"><h2 id="${id}">${title} (${findings.length})</h2>${body}</section>`;
136
+ }
137
+ function findingSections(before, after) {
138
+ if (!before)
139
+ return findingList("open", "Findings", after.findings, true);
140
+ const split = splitFindings(before.findings, after.findings);
141
+ return [
142
+ findingList("fixed", "Fixed", split.fixed, false),
143
+ findingList("open", "Still open", split.open, true),
144
+ findingList("new", "New", split.added, true),
145
+ ].join("\n");
146
+ }
147
+ function shotFigure(run, state, label) {
148
+ const shot = run?.report.screenshots?.find((s) => s.state === state);
149
+ if (!run || !shot)
150
+ return `<figure class="shot"><figcaption>${label}</figcaption><p class="empty">No screenshot.</p></figure>`;
151
+ const image = run.images[state];
152
+ if (!image)
153
+ return `<figure class="shot"><figcaption>${label}</figcaption><p class="empty">Screenshot file not found.</p></figure>`;
154
+ const alt = escapeHtml(`${label}, ${state}`);
155
+ return `<figure class="shot"><figcaption>${label}</figcaption>
156
+ <div class="frame" tabindex="0" role="region" aria-label="${alt}"><img src="${escapeHtml(image.src)}" width="${image.width}" height="${image.height}" alt="${alt}" loading="lazy" decoding="async"></div></figure>`;
157
+ }
158
+ function screenshotSections(before, after) {
159
+ const states = [...new Set([...(after.report.screenshots ?? []), ...(before?.report.screenshots ?? [])].map((s) => s.state))];
160
+ if (states.length === 0)
161
+ return "";
162
+ const pairs = states.map((state) => {
163
+ const kind = state.startsWith("phone") ? "phone" : "desktop";
164
+ const figures = before
165
+ ? [shotFigure(before, state, "Before"), shotFigure(after, state, "After")]
166
+ : [shotFigure(after, state, "Screenshot")];
167
+ return `<h3>${escapeHtml(state)}</h3><div class="pair ${kind}">${figures.join("")}</div>`;
168
+ });
169
+ return `<section aria-labelledby="screenshots"><h2 id="screenshots">Screenshots</h2>${pairs.join("\n")}</section>`;
170
+ }
171
+ const STYLE = `
172
+ :root {
173
+ color-scheme: light dark;
174
+ --bg: #ffffff; --fg: #111111; --muted: #57606a; --line: #d0d7de; --panel: #f6f8fa;
175
+ --accent: #0969da; --good: #116329; --ok: #7d4e00; --bad: #b3141f;
176
+ }
177
+ @media (prefers-color-scheme: dark) {
178
+ :root {
179
+ --bg: #0d1117; --fg: #f0f3f6; --muted: #9da7b3; --line: #3d444d; --panel: #161b22;
180
+ --accent: #58a6ff; --good: #56d364; --ok: #e3b341; --bad: #ff7b72;
181
+ }
182
+ }
183
+ * { box-sizing: border-box; }
184
+ html { -webkit-text-size-adjust: 100%; }
185
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
186
+ main { max-width: 1120px; margin: 0 auto; padding: 32px 16px 64px; }
187
+ main > section { margin-top: 48px; }
188
+ header p { margin: 4px 0 0; color: var(--muted); overflow-wrap: anywhere; }
189
+ h1 { font-size: 32px; line-height: 1.25; margin: 0 0 8px; }
190
+ h2 { font-size: 20px; margin: 0 0 16px; }
191
+ h3 { font-size: 16px; margin: 24px 0 8px; }
192
+ p { margin: 0; max-width: 65ch; }
193
+ code { font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }
194
+ .target { color: var(--fg); font-weight: 600; }
195
+ .date { white-space: nowrap; }
196
+ .cards { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)); }
197
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; }
198
+ .card h3 { margin: 0 0 8px; color: var(--muted); }
199
+ .score { font-size: 32px; font-weight: 700; line-height: 1.25; font-variant-numeric: tabular-nums; }
200
+ .arrow { color: var(--muted); font-weight: 400; }
201
+ .note, .legend, .empty { color: var(--muted); }
202
+ .note { margin-top: 4px; }
203
+ .legend { margin-top: 12px; font-size: 14px; }
204
+ .good { color: var(--good); }
205
+ .ok { color: var(--ok); }
206
+ .bad { color: var(--bad); }
207
+ .none { color: var(--muted); }
208
+ table { border-collapse: collapse; width: 100%; font-size: 14px; font-variant-numeric: tabular-nums; }
209
+ th, td { padding: 8px 4px; border-bottom: 1px solid var(--line); text-align: right; }
210
+ th:first-child { text-align: left; }
211
+ thead th { color: var(--muted); font-weight: 600; }
212
+ td { font-weight: 700; }
213
+ .findings { list-style: none; margin: 0; padding: 0; }
214
+ .findings li { border-top: 1px solid var(--line); padding: 12px 0; }
215
+ .findings li p + p { margin-top: 4px; }
216
+ .fix, .source { color: var(--muted); }
217
+ .source { font-size: 14px; }
218
+ .owner { font-weight: 600; }
219
+ .sev { display: inline-block; font-size: 14px; font-weight: 700; text-transform: uppercase; }
220
+ .sev.error { color: var(--bad); }
221
+ .sev.warn { color: var(--ok); }
222
+ .sev.info { color: var(--muted); }
223
+ .pair { display: grid; gap: 16px; }
224
+ .pair.desktop { grid-template-columns: repeat(auto-fit, minmax(min(100%, 720px), 1fr)); }
225
+ .pair.phone { grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 480px)); }
226
+ figure { margin: 0; }
227
+ figcaption { font-size: 14px; color: var(--muted); margin-bottom: 8px; }
228
+ .frame { max-height: 720px; overflow-y: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); }
229
+ .frame:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
230
+ img { display: block; width: 100%; height: auto; }
231
+ footer { margin-top: 48px; color: var(--muted); font-size: 14px; }
232
+ @media (prefers-reduced-motion: reduce) {
233
+ * { scroll-behavior: auto; transition: none; animation: none; }
234
+ }
235
+ `;
236
+ export function renderHtml(input) {
237
+ const after = toRun(input.after);
238
+ const before = input.before ? toRun(input.before) : undefined;
239
+ const { report } = after;
240
+ const runs = before
241
+ ? `<p>Before: ${formatDate(before.report.startedAt)}. After: ${formatDate(report.startedAt)}.</p>`
242
+ : `<p>Run: ${formatDate(report.startedAt)}.</p>`;
243
+ const title = before ? "Before and after" : "Report";
244
+ return `<!doctype html>
245
+ <html lang="en">
246
+ <head>
247
+ <meta charset="utf-8">
248
+ <meta name="viewport" content="width=device-width, initial-scale=1">
249
+ <meta name="color-scheme" content="light dark">
250
+ <title>Sugikit ${title.toLowerCase()}: ${escapeHtml(report.target)}</title>
251
+ <style>${STYLE}</style>
252
+ </head>
253
+ <body>
254
+ <main>
255
+ <header>
256
+ <h1>Sugikit ${title.toLowerCase()}</h1>
257
+ <p><span class="target">${escapeHtml(report.target)}</span></p>
258
+ <p>Framework: ${escapeHtml(report.framework)}</p>
259
+ ${report.pageType ? `<p>Page type: ${escapeHtml(report.pageType)}</p>\n` : ""}${runs}
260
+ </header>
261
+ ${scoreCards(before, after)}
262
+ ${psiTable(before, after)}
263
+ ${findingSections(before, after)}
264
+ ${screenshotSections(before, after)}
265
+ <footer><p>Made by Sugikit from local JSON reports.</p></footer>
266
+ </main>
267
+ </body>
268
+ </html>
269
+ `;
270
+ }