@realadvisor-sites/kit-core 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +151 -148
- package/CHANGELOG.md +34 -0
- package/DESIGN.md +70 -9
- package/README.md +3 -3
- package/bin/sites-kit.mjs +5 -1
- package/lib/render-error.ts +6 -0
- package/package.json +2 -2
- package/tools/critic-calibrate.mjs +95 -0
- package/tools/critic.mjs +397 -0
- package/tools/screenshot.mjs +198 -1
- package/tools/search-map-test.mjs +8 -3
- package/tools/use-fixture.mjs +13 -8
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@ The framework-neutral core of a RealAdvisor site, shared by the Astro kit
|
|
|
6
6
|
version, and never copies it:
|
|
7
7
|
|
|
8
8
|
```json
|
|
9
|
-
"@realadvisor/sites-kit-core": "npm:@realadvisor-sites/kit-core@^0.
|
|
10
|
-
"@realadvisor/sites-kit-astro": "npm:@realadvisor-sites/kit-astro@^0.
|
|
11
|
-
"@realadvisor/sites-sdk": "npm:@realadvisor-sites/sdk@^0.
|
|
9
|
+
"@realadvisor/sites-kit-core": "npm:@realadvisor-sites/kit-core@^0.5.0",
|
|
10
|
+
"@realadvisor/sites-kit-astro": "npm:@realadvisor-sites/kit-astro@^0.5.0",
|
|
11
|
+
"@realadvisor/sites-sdk": "npm:@realadvisor-sites/sdk@^0.5.0"
|
|
12
12
|
```
|
|
13
13
|
|
|
14
14
|
In this repo the template and examples use paths instead (`file:../kit-core`).
|
package/bin/sites-kit.mjs
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* site's package scripts). Every tool lives in the package, never in the
|
|
5
5
|
* site: a site always runs the kit's current version.
|
|
6
6
|
*
|
|
7
|
-
* sites-kit fixture [name | file.json] [--if-empty] sample data into src/data/
|
|
7
|
+
* sites-kit fixture [name | file.json] [--if-empty] sample data into src/data/ (React: app/data/fixture.json)
|
|
8
8
|
* sites-kit screenshot [paths...] [options] screenshots (your eyes)
|
|
9
|
+
* sites-kit critic [path] [--anchor url | --anchor-shots a.png,b.png] inputs for the taste critic (TASTE.md)
|
|
10
|
+
* sites-kit critic calibrate prepare --url <example> | score does the critic still catch known faults
|
|
9
11
|
* sites-kit check deploy [--no-build] the deploy gate (pnpm check:deploy)
|
|
10
12
|
* sites-kit test map [--url ...] [--path ...] browser test of the listings map
|
|
11
13
|
*/
|
|
@@ -15,6 +17,8 @@ import { fileURLToPath } from 'node:url';
|
|
|
15
17
|
const TOOLS = {
|
|
16
18
|
fixture: 'use-fixture.mjs',
|
|
17
19
|
screenshot: 'screenshot.mjs',
|
|
20
|
+
critic: 'critic.mjs',
|
|
21
|
+
'critic calibrate': 'critic-calibrate.mjs',
|
|
18
22
|
'check deploy': 'check-deploy.mjs',
|
|
19
23
|
'test map': 'search-map-test.mjs',
|
|
20
24
|
};
|
package/lib/render-error.ts
CHANGED
|
@@ -21,6 +21,12 @@ const TEXT = {
|
|
|
21
21
|
en: ['Page temporarily unavailable', 'Please try again in a few minutes.', 'Back to home'],
|
|
22
22
|
} as const;
|
|
23
23
|
|
|
24
|
+
/** Title, text and home-link label of the 500 page in a language (a framework's own error page uses them too). */
|
|
25
|
+
export const serverErrorText = (l: keyof typeof TEXT = lang()) => {
|
|
26
|
+
const [title, body, home] = TEXT[l];
|
|
27
|
+
return { title, body, home };
|
|
28
|
+
};
|
|
29
|
+
|
|
24
30
|
export function renderFailed(path: string, err: unknown): Response {
|
|
25
31
|
const e = err instanceof Error ? err : new Error(String(err));
|
|
26
32
|
const msg = err instanceof SitesApiError && err.code === 'site_key' ? `page render failed: ${SITE_KEY_REJECTED}` : 'page render failed';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@realadvisor-sites/kit-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "The framework-neutral core of a RealAdvisor site, shared by the Astro kit and the React kit: data helpers over @realadvisor/sites-sdk (a peer), i18n, formatting, legal texts, SEO, search, images, security headers, the browser scripts (listing search and map, enquiry, consent), the sites-kit tools (fixture, screenshot, deploy check) and the rules the coding agent follows (AGENTS.md, DESIGN.md).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"test": "node --experimental-strip-types --no-warnings=ExperimentalWarning --test \"test/*.test.mjs\" \"test/*.test.ts\""
|
|
56
56
|
},
|
|
57
57
|
"peerDependencies": {
|
|
58
|
-
"@realadvisor/sites-sdk": "^0.
|
|
58
|
+
"@realadvisor/sites-sdk": "^0.5.0",
|
|
59
59
|
"playwright": "^1.64.1"
|
|
60
60
|
},
|
|
61
61
|
"peerDependenciesMeta": {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Calibrate the taste critic (TASTE.md section 5): does it still catch every
|
|
4
|
+
* fault a user once had to point out, and leave the clean example alone?
|
|
5
|
+
*
|
|
6
|
+
* sites-kit critic calibrate prepare --url http://localhost:4511 [--out critic-calibration]
|
|
7
|
+
* one critic-input/ folder per case in critic/calibration/cases.json,
|
|
8
|
+
* for the example running at --url (the anchor is the same page, clean)
|
|
9
|
+
* (the run harness gives each <out>/<case>/INDEX.md to the critic and saves
|
|
10
|
+
* its answer as <out>/<case>/answer.md)
|
|
11
|
+
* sites-kit critic calibrate score [--out critic-calibration]
|
|
12
|
+
* compares every answer.md with the case's expected scores; exit 1 on a miss
|
|
13
|
+
*/
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { join, resolve } from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
|
|
19
|
+
/** Scores from a critic answer: { lines: { 1: 2, ... }, total }. */
|
|
20
|
+
export function parseScores(md) {
|
|
21
|
+
const lines = {};
|
|
22
|
+
const section = md.split(/^## Scores\s*$/m)[1]?.split(/^## /m)[0] ?? md;
|
|
23
|
+
for (const m of section.matchAll(/^\s*(\d{1,2})\.\s+[^\n]*?\s([012])\s*:/gm)) lines[Number(m[1])] = Number(m[2]);
|
|
24
|
+
const t = md.match(/Total:\s*(\d+)\s*\/\s*(\d+)/);
|
|
25
|
+
const sum = Object.values(lines).reduce((a, b) => a + b, 0);
|
|
26
|
+
return { lines, total: t ? Number(t[1]) : sum, outOf: t ? Number(t[2]) : null };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Problems of one case's scores against its expectations ([] = pass). */
|
|
30
|
+
export function checkCase(scores, expect) {
|
|
31
|
+
const out = [];
|
|
32
|
+
const test = (name, v, e) => {
|
|
33
|
+
if (v === undefined) return out.push(`line ${name}: no score found`);
|
|
34
|
+
if (e.min !== undefined && v < e.min) out.push(`line ${name}: ${v}, expected at least ${e.min}`);
|
|
35
|
+
if (e.max !== undefined && v > e.max) out.push(`line ${name}: ${v}, expected at most ${e.max}`);
|
|
36
|
+
};
|
|
37
|
+
for (const [k, e] of Object.entries(expect)) {
|
|
38
|
+
if (k === 'total') {
|
|
39
|
+
if (e.min !== undefined && scores.total < e.min) out.push(`total ${scores.total}, expected at least ${e.min}`);
|
|
40
|
+
if (e.max !== undefined && scores.total > e.max) out.push(`total ${scores.total}, expected at most ${e.max}`);
|
|
41
|
+
} else if (k === 'all') {
|
|
42
|
+
for (const [n, v] of Object.entries(scores.lines)) test(n, v, e);
|
|
43
|
+
} else test(k, scores.lines[Number(k)], e);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
49
|
+
if (isMain) {
|
|
50
|
+
const args = process.argv.slice(2).filter((a) => a !== '--');
|
|
51
|
+
const opt = (name, def) => {
|
|
52
|
+
const i = args.indexOf(`--${name}`);
|
|
53
|
+
return i === -1 ? def : args.splice(i, 2)[1];
|
|
54
|
+
};
|
|
55
|
+
const OUT = resolve(opt('out', 'critic-calibration'));
|
|
56
|
+
const URL_ = opt('url', '');
|
|
57
|
+
const dir = fileURLToPath(new URL('../critic/calibration/', import.meta.url));
|
|
58
|
+
const { cases } = JSON.parse(readFileSync(join(dir, 'cases.json'), 'utf8'));
|
|
59
|
+
const cmd = args[0];
|
|
60
|
+
if (cmd === 'prepare') {
|
|
61
|
+
if (!URL_) {
|
|
62
|
+
console.error('--url: the example of the cases running (e.g. studio-vey: pnpm --dir examples/react/studio-vey dev)');
|
|
63
|
+
process.exit(2);
|
|
64
|
+
}
|
|
65
|
+
for (const c of cases) {
|
|
66
|
+
const out = join(OUT, c.id);
|
|
67
|
+
const inject = c.inject ? ['--inject', join(dir, c.inject)] : [];
|
|
68
|
+
const run = spawnSync(process.execPath, [fileURLToPath(new URL('./critic.mjs', import.meta.url)), c.path, '--url', URL_, '--anchor', URL_, '--anchor-path', c.path, '--out', out, ...inject], { stdio: 'inherit' });
|
|
69
|
+
if (run.status) process.exit(run.status);
|
|
70
|
+
}
|
|
71
|
+
console.log(`\n${cases.length} cases in ${OUT}/. Give each <case>/INDEX.md to the critic (a separate model, nothing else), save its answer as <case>/answer.md, then run: sites-kit critic calibrate score`);
|
|
72
|
+
} else if (cmd === 'score') {
|
|
73
|
+
let misses = 0;
|
|
74
|
+
const report = [];
|
|
75
|
+
for (const c of cases) {
|
|
76
|
+
const f = join(OUT, c.id, 'answer.md');
|
|
77
|
+
if (!existsSync(f)) {
|
|
78
|
+
misses++;
|
|
79
|
+
console.log(`✗ ${c.id}: no answer.md`);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const scores = parseScores(readFileSync(f, 'utf8'));
|
|
83
|
+
const problems = checkCase(scores, c.expect);
|
|
84
|
+
if (problems.length) misses++;
|
|
85
|
+
report.push({ id: c.id, fault: c.fault, scores, problems });
|
|
86
|
+
console.log(`${problems.length ? '✗' : '✓'} ${c.id} (${c.fault}): total ${scores.total}${scores.outOf ? `/${scores.outOf}` : ''}${problems.map((p) => `\n ${p}`).join('')}`);
|
|
87
|
+
}
|
|
88
|
+
writeFileSync(join(OUT, 'score.json'), JSON.stringify(report, null, 2));
|
|
89
|
+
console.log(`\n${cases.length - misses}/${cases.length} cases pass.`);
|
|
90
|
+
process.exit(misses ? 1 : 0);
|
|
91
|
+
} else {
|
|
92
|
+
console.error('Usage: sites-kit critic calibrate prepare --url <example url> | score [--out dir]');
|
|
93
|
+
process.exit(2);
|
|
94
|
+
}
|
|
95
|
+
}
|
package/tools/critic.mjs
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Collect what the taste critic needs to judge one page (TASTE.md section 4,
|
|
4
|
+
* critic/CRITIC.md), so a separate model can review it from files alone.
|
|
5
|
+
*
|
|
6
|
+
* pnpm kit critic # the home page, starts `pnpm dev` if needed
|
|
7
|
+
* pnpm kit critic -- /listings --url http://localhost:4321
|
|
8
|
+
* pnpm kit critic -- / --anchor http://localhost:4799 # the chosen example, running
|
|
9
|
+
* pnpm kit critic -- / --anchor-shots a@1440.png,a@390.png # or its screenshots
|
|
10
|
+
* pnpm kit critic -- / --anchor ... --previous critic-round1.md # round 2: the critic checks its fixes
|
|
11
|
+
*
|
|
12
|
+
* Output (default critic-input/):
|
|
13
|
+
* INDEX.md what each file is, in reading order (the critic starts here)
|
|
14
|
+
* summary.json measured facts: taste lines, fonts by role, colours, logo, images, sections
|
|
15
|
+
* page@1440.png, page@390.png full page
|
|
16
|
+
* page-first@1440.png, page-first@390.png first screen only
|
|
17
|
+
* anchor@1440.png, anchor@390.png, anchor-first@*.png the anchor (when given)
|
|
18
|
+
* logo.<ext>, type-vs-logo.png the logo file, and the logo beside every font family in use
|
|
19
|
+
* BRIEF.md, DESIGN-NOTES.md copied from the site root when present
|
|
20
|
+
* CRITIC.md the critic's instructions (from the kit)
|
|
21
|
+
*/
|
|
22
|
+
import { chromium } from 'playwright';
|
|
23
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
24
|
+
import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
25
|
+
import { existsSync } from 'node:fs';
|
|
26
|
+
import { basename, extname, join, resolve } from 'node:path';
|
|
27
|
+
import { fileURLToPath } from 'node:url';
|
|
28
|
+
|
|
29
|
+
const args = process.argv.slice(2).filter((a) => a !== '--');
|
|
30
|
+
const opt = (name, def) => {
|
|
31
|
+
const i = args.indexOf(`--${name}`);
|
|
32
|
+
if (i === -1) return def;
|
|
33
|
+
const v = args[i + 1];
|
|
34
|
+
args.splice(i, 2);
|
|
35
|
+
return v;
|
|
36
|
+
};
|
|
37
|
+
const BASE = opt('url', `http://localhost:${process.env.PORT ?? 4321}`).replace(/\/$/, '');
|
|
38
|
+
const OUT = resolve(opt('out', 'critic-input'));
|
|
39
|
+
const ANCHOR = opt('anchor', '')?.replace(/\/$/, '');
|
|
40
|
+
const ANCHOR_PATH = opt('anchor-path', '/');
|
|
41
|
+
const ANCHOR_SHOTS = opt('anchor-shots', '');
|
|
42
|
+
const PREVIOUS = opt('previous', '');
|
|
43
|
+
const INJECT = opt('inject', '');
|
|
44
|
+
const injectCss = INJECT ? await readFile(INJECT, 'utf8') : '';
|
|
45
|
+
const PATH = args.find((a) => a.startsWith('/')) ?? '/';
|
|
46
|
+
const WIDTHS = [
|
|
47
|
+
{ name: '1440', width: 1440, height: 900 },
|
|
48
|
+
{ name: '390', width: 390, height: 844, isMobile: true, hasTouch: true, deviceScaleFactor: 2 },
|
|
49
|
+
];
|
|
50
|
+
const here = (p) => fileURLToPath(new URL(p, import.meta.url));
|
|
51
|
+
|
|
52
|
+
async function up(url) {
|
|
53
|
+
try {
|
|
54
|
+
return (await fetch(url, { signal: AbortSignal.timeout(2000) })).status < 500;
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let server;
|
|
61
|
+
if (!(await up(BASE))) {
|
|
62
|
+
console.log(`Nothing on ${BASE}, starting pnpm dev…`);
|
|
63
|
+
server = spawn('pnpm', ['dev'], { stdio: 'ignore', detached: true });
|
|
64
|
+
for (let i = 0; i < 60 && !(await up(BASE)); i++) await new Promise((r) => setTimeout(r, 1000));
|
|
65
|
+
if (!(await up(BASE))) {
|
|
66
|
+
console.error('Dev server did not start. Run `pnpm dev` and read its errors.');
|
|
67
|
+
process.exit(2);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const stop = () => {
|
|
71
|
+
try {
|
|
72
|
+
if (server) process.kill(-server.pid);
|
|
73
|
+
} catch {}
|
|
74
|
+
};
|
|
75
|
+
process.on('exit', stop);
|
|
76
|
+
|
|
77
|
+
await rm(OUT, { recursive: true, force: true });
|
|
78
|
+
await mkdir(OUT, { recursive: true });
|
|
79
|
+
|
|
80
|
+
// 1. The measured checks: the screenshot tool on this one path (its taste: lines and problems).
|
|
81
|
+
const shotDir = join(OUT, '.screenshot');
|
|
82
|
+
spawnSync(process.execPath, [here('./screenshot.mjs'), '--url', BASE, '--out', shotDir, ...(INJECT ? ['--inject', INJECT] : []), PATH], { stdio: 'ignore' });
|
|
83
|
+
let problems = [];
|
|
84
|
+
try {
|
|
85
|
+
problems = JSON.parse(await readFile(join(shotDir, 'report.json'), 'utf8'))[0]?.problems ?? [];
|
|
86
|
+
} catch {
|
|
87
|
+
problems = ['(the screenshot tool did not write a report: run `pnpm screenshot` and read its errors)'];
|
|
88
|
+
}
|
|
89
|
+
await rm(shotDir, { recursive: true, force: true });
|
|
90
|
+
|
|
91
|
+
const browser = await chromium.launch().catch(() => chromium.launch({ channel: 'chrome' }));
|
|
92
|
+
|
|
93
|
+
/** Load a page fully: lazy images scrolled in, fonts ready. */
|
|
94
|
+
async function open(ctx, url, css = '') {
|
|
95
|
+
const page = await ctx.newPage();
|
|
96
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
|
|
97
|
+
await page.waitForLoadState('load', { timeout: 10000 }).catch(() => {});
|
|
98
|
+
if (css) await page.addStyleTag({ content: css }).catch(() => {});
|
|
99
|
+
await page.evaluate(async () => {
|
|
100
|
+
for (let y = 0; y < document.body.scrollHeight; y += 600) {
|
|
101
|
+
window.scrollTo(0, y);
|
|
102
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
103
|
+
}
|
|
104
|
+
window.scrollTo(0, 0);
|
|
105
|
+
await document.fonts.ready;
|
|
106
|
+
// Real file pixels (srcset descriptors lie when the image CDN never enlarges).
|
|
107
|
+
await Promise.all([...document.images].map((img) => new Promise((done) => {
|
|
108
|
+
const src = img.currentSrc || img.src;
|
|
109
|
+
if (!src) return done();
|
|
110
|
+
const probe = new Image();
|
|
111
|
+
probe.onload = () => { img.dataset.realW = String(probe.naturalWidth); img.dataset.realH = String(probe.naturalHeight); done(); };
|
|
112
|
+
probe.onerror = () => done();
|
|
113
|
+
probe.src = src;
|
|
114
|
+
setTimeout(done, 5000);
|
|
115
|
+
})));
|
|
116
|
+
});
|
|
117
|
+
await page.waitForTimeout(300);
|
|
118
|
+
return page;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function shots(url, prefix, css = '') {
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const vp of WIDTHS) {
|
|
124
|
+
const ctx = await browser.newContext({ viewport: { width: vp.width, height: vp.height }, isMobile: vp.isMobile, hasTouch: vp.hasTouch, deviceScaleFactor: vp.deviceScaleFactor ?? 1 });
|
|
125
|
+
try {
|
|
126
|
+
const page = await open(ctx, url, css);
|
|
127
|
+
const full = `${prefix}@${vp.name}.png`;
|
|
128
|
+
const first = `${prefix}-first@${vp.name}.png`;
|
|
129
|
+
const h = await page.evaluate(() => document.documentElement.scrollHeight);
|
|
130
|
+
await page.screenshot({ path: join(OUT, full), fullPage: true, clip: { x: 0, y: 0, width: vp.width, height: Math.min(h, vp.height * 12) } });
|
|
131
|
+
await page.screenshot({ path: join(OUT, first) });
|
|
132
|
+
out[vp.name] = { page, ctx, full, first };
|
|
133
|
+
} catch (e) {
|
|
134
|
+
await ctx.close();
|
|
135
|
+
throw e;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Everything measurable about taste on one loaded page. Runs in the browser. */
|
|
142
|
+
function measure() {
|
|
143
|
+
const vw = innerWidth, vh = innerHeight;
|
|
144
|
+
const rgb = (c) => (c.match(/[\d.]+/g) || []).map(Number);
|
|
145
|
+
const hex = (c) => { const v = rgb(c); return v.length >= 3 ? '#' + v.slice(0, 3).map((n) => Math.round(n).toString(16).padStart(2, '0')).join('') : c; };
|
|
146
|
+
// The ground an element sits on: its own background or the first opaque one above it.
|
|
147
|
+
const groundOf = (el) => {
|
|
148
|
+
for (let e = el; e; e = e.parentElement) {
|
|
149
|
+
const v = rgb(getComputedStyle(e).backgroundColor);
|
|
150
|
+
if (v.length >= 3 && (v.length < 4 || v[3] > 0.5)) return hex(getComputedStyle(e).backgroundColor);
|
|
151
|
+
}
|
|
152
|
+
return '#ffffff';
|
|
153
|
+
};
|
|
154
|
+
// An image CDN URL hides the file name in base64: show the original's name.
|
|
155
|
+
const fileName = (src) => {
|
|
156
|
+
const seg = (src || '').split('/').pop()?.split('?')[0] ?? '';
|
|
157
|
+
try {
|
|
158
|
+
const orig = atob(seg.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'));
|
|
159
|
+
if (/^https?:\/\//.test(orig)) return orig.split('/').pop().slice(0, 80);
|
|
160
|
+
} catch {}
|
|
161
|
+
return seg.slice(0, 80);
|
|
162
|
+
};
|
|
163
|
+
const family = (f) => f.split(',')[0].trim().replace(/^["']|["']$/g, '');
|
|
164
|
+
const visible = (el) => { const r = el.getBoundingClientRect(); const cs = getComputedStyle(el); return r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none' && !el.closest('[hidden], .sr-only'); };
|
|
165
|
+
const ownText = (el) => [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join('').trim();
|
|
166
|
+
const style = (el) => {
|
|
167
|
+
const cs = getComputedStyle(el);
|
|
168
|
+
return {
|
|
169
|
+
family: family(cs.fontFamily), size: Math.round(parseFloat(cs.fontSize) * 10) / 10, weight: cs.fontWeight, style: cs.fontStyle,
|
|
170
|
+
tracking: cs.letterSpacing === 'normal' ? 0 : Math.round((parseFloat(cs.letterSpacing) / parseFloat(cs.fontSize)) * 1000) / 1000,
|
|
171
|
+
transform: cs.textTransform, lineHeight: cs.lineHeight, color: hex(cs.color), stretch: cs.fontStretch,
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
// Text roles: what each kind of text is set in. The critic compares them with the logo.
|
|
175
|
+
const textEls = [...document.querySelectorAll('body *')].filter((el) => ownText(el) && visible(el) && !el.closest('script, style, noscript'));
|
|
176
|
+
const caps = (el) => { const cs = getComputedStyle(el); return cs.textTransform === 'uppercase' || (ownText(el) === ownText(el).toUpperCase() && /[A-Z]{3}/.test(ownText(el))); };
|
|
177
|
+
const roleOf = (el) => {
|
|
178
|
+
const cs = getComputedStyle(el), fs = parseFloat(cs.fontSize), t = ownText(el);
|
|
179
|
+
if (el.closest('[role="banner"]') || (el.closest('header') && !el.closest('main, article, section'))) return 'header / nav';
|
|
180
|
+
if (el.closest('footer')) return 'footer';
|
|
181
|
+
if (el.closest('button, .btn, [class*="button"]') || (el.closest('a') && rgb(getComputedStyle(el.closest('a')).backgroundColor)[3] !== 0 && getComputedStyle(el.closest('a')).backgroundColor !== 'rgba(0, 0, 0, 0)')) return 'button';
|
|
182
|
+
if (/^h1$/i.test(el.tagName)) return 'h1';
|
|
183
|
+
if (/^h[23]$/i.test(el.tagName) && fs >= 20) return 'section heading (h2/h3)';
|
|
184
|
+
if (/\d/.test(t) && fs >= 40) return 'big number';
|
|
185
|
+
if (/(CHF|EUR|€|Fr\.)\s?[\d'’.,]+|[\d'’.,]{5,}\s?(CHF|€)/.test(t)) return 'price';
|
|
186
|
+
if (fs <= 14 && caps(el)) return 'eyebrow / caps label';
|
|
187
|
+
if (fs <= 15) return 'small text / meta';
|
|
188
|
+
if (el.closest('form')) return 'form';
|
|
189
|
+
return 'body / lede';
|
|
190
|
+
};
|
|
191
|
+
const roles = new Map();
|
|
192
|
+
for (const el of textEls) {
|
|
193
|
+
const role = roleOf(el);
|
|
194
|
+
const s = style(el);
|
|
195
|
+
const key = `${role}|${s.family}|${s.size}|${s.weight}|${s.style}|${s.transform}`;
|
|
196
|
+
const cur = roles.get(key) ?? { role, ...s, count: 0, sample: ownText(el).slice(0, 50) };
|
|
197
|
+
cur.count++;
|
|
198
|
+
roles.set(key, cur);
|
|
199
|
+
}
|
|
200
|
+
const byRole = {};
|
|
201
|
+
for (const r of [...roles.values()].sort((a, b) => b.count - a.count)) (byRole[r.role] ??= []).length < 3 && byRole[r.role].push(r);
|
|
202
|
+
// Families by characters drawn.
|
|
203
|
+
const chars = new Map();
|
|
204
|
+
let total = 0;
|
|
205
|
+
for (const el of textEls) { const n = ownText(el).length; const f = family(getComputedStyle(el).fontFamily); chars.set(f, (chars.get(f) || 0) + n); total += n; }
|
|
206
|
+
const families = [...chars].sort((a, b) => b[1] - a[1]).map(([f, n]) => ({ family: f, share: Math.round((n / total) * 100) / 100, loaded: [...document.fonts].some((ff) => ff.family.replace(/["']/g, '') === f && ff.status === 'loaded') }));
|
|
207
|
+
// Colours: grounds by area (top-level boxes only once), text colours by characters.
|
|
208
|
+
const grounds = new Map();
|
|
209
|
+
for (const el of document.querySelectorAll('body, body *')) {
|
|
210
|
+
if (!visible(el)) continue;
|
|
211
|
+
const c = rgb(getComputedStyle(el).backgroundColor);
|
|
212
|
+
if (c.length < 3 || (c.length > 3 && c[3] < 0.5)) continue;
|
|
213
|
+
const r = el.getBoundingClientRect();
|
|
214
|
+
const h = hex(getComputedStyle(el).backgroundColor);
|
|
215
|
+
grounds.set(h, (grounds.get(h) || 0) + r.width * r.height);
|
|
216
|
+
}
|
|
217
|
+
const page = document.documentElement.scrollWidth * document.documentElement.scrollHeight;
|
|
218
|
+
const inks = new Map();
|
|
219
|
+
for (const el of textEls) { const h = hex(getComputedStyle(el).color); inks.set(h, (inks.get(h) || 0) + ownText(el).length); }
|
|
220
|
+
// Logo.
|
|
221
|
+
const logoEl = document.querySelector('img[data-logo]') || document.querySelector('header img, [role="banner"] img') || document.querySelector('header svg');
|
|
222
|
+
// No logo file: the text wordmark (the home link in the header) stands for it.
|
|
223
|
+
const wordmark = !logoEl && document.querySelector('header a[href="/"], [role="banner"] a[href="/"]');
|
|
224
|
+
let logo = null;
|
|
225
|
+
if (logoEl) {
|
|
226
|
+
const r = logoEl.getBoundingClientRect();
|
|
227
|
+
logo = { tag: logoEl.tagName.toLowerCase(), src: logoEl.currentSrc || logoEl.src || null, original: fileName(logoEl.currentSrc || logoEl.src), alt: logoEl.getAttribute('alt'), drawn: [Math.round(r.width), Math.round(r.height)], file: logoEl.naturalWidth ? [logoEl.naturalWidth, logoEl.naturalHeight] : null, shareOfHeader: null };
|
|
228
|
+
const header = logoEl.closest('header, [role="banner"]');
|
|
229
|
+
if (header) logo.shareOfHeader = Math.round((r.height / header.getBoundingClientRect().height) * 100) / 100;
|
|
230
|
+
}
|
|
231
|
+
if (wordmark) {
|
|
232
|
+
const r = wordmark.getBoundingClientRect(), s = style(wordmark.querySelector('span') || wordmark);
|
|
233
|
+
logo = { tag: 'text wordmark', text: wordmark.innerText.trim().replace(/\s+/g, ' '), drawn: [Math.round(r.width), Math.round(r.height)], font: s };
|
|
234
|
+
}
|
|
235
|
+
const header = document.querySelector('header, [role="banner"]');
|
|
236
|
+
// Images: file pixels against the box x devicePixelRatio (the photo-sharpness line).
|
|
237
|
+
const images = [...document.images].filter(visible).map((i) => {
|
|
238
|
+
const r = i.getBoundingClientRect();
|
|
239
|
+
const cs = getComputedStyle(i);
|
|
240
|
+
const realW = Number(i.dataset.realW) || i.naturalWidth, realH = Number(i.dataset.realH) || i.naturalHeight;
|
|
241
|
+
const cover = cs.objectFit !== 'contain' && cs.objectFit !== 'scale-down';
|
|
242
|
+
const fillW = realW && realH && cover ? Math.max(r.width, r.height * (realW / realH)) : r.width;
|
|
243
|
+
return {
|
|
244
|
+
file: fileName(i.currentSrc || i.src), alt: i.alt, hero: !!(i.getAttribute('fetchpriority') === 'high' || i.closest('[data-hero]')),
|
|
245
|
+
box: [Math.round(r.width), Math.round(r.height)], top: Math.round(r.top + scrollY), filePx: [realW, realH],
|
|
246
|
+
density: realW ? Math.round((realW / fillW) * 100) / 100 : null, // file pixels per CSS pixel: under devicePixelRatio is upscaled on that screen
|
|
247
|
+
};
|
|
248
|
+
}).filter((i) => i.box[0] >= 80);
|
|
249
|
+
// Section rhythm: the page's top-level bands, their grounds and inner spacing.
|
|
250
|
+
const main = document.querySelector('main') || document.body;
|
|
251
|
+
const sections = [...main.children].filter(visible).map((s) => {
|
|
252
|
+
const r = s.getBoundingClientRect(), cs = getComputedStyle(s);
|
|
253
|
+
const heading = s.querySelector('h1, h2, h3');
|
|
254
|
+
return {
|
|
255
|
+
el: `${s.tagName.toLowerCase()}${typeof s.className === 'string' && s.className ? '.' + s.className.trim().split(/\s+/).join('.') : ''}`,
|
|
256
|
+
top: Math.round(r.top + scrollY), height: Math.round(r.height), ground: groundOf(s),
|
|
257
|
+
padding: [Math.round(parseFloat(cs.paddingTop)), Math.round(parseFloat(cs.paddingBottom))],
|
|
258
|
+
heading: heading ? heading.textContent.trim().slice(0, 50) : null,
|
|
259
|
+
};
|
|
260
|
+
});
|
|
261
|
+
// Type scale: every size with text, how often, in which family (the critic judges near-duplicates).
|
|
262
|
+
const steps = new Map();
|
|
263
|
+
for (const el of textEls) { const cs = getComputedStyle(el); const k = `${Math.round(parseFloat(cs.fontSize) * 2) / 2}px ${family(cs.fontFamily)} ${cs.fontWeight}`; steps.set(k, (steps.get(k) || 0) + 1); }
|
|
264
|
+
const typeScale = [...steps].sort((x, y) => parseFloat(x[0]) - parseFloat(y[0])).map(([k, n]) => `${k} x${n}`);
|
|
265
|
+
return {
|
|
266
|
+
viewport: [vw, vh], typeScale, dpr: devicePixelRatio, pageHeight: document.documentElement.scrollHeight, title: document.title,
|
|
267
|
+
header: header ? { height: Math.round(header.getBoundingClientRect().height), share: Math.round((header.getBoundingClientRect().height / vh) * 100) / 100, position: getComputedStyle(header).position } : null,
|
|
268
|
+
logo, families, fontsByRole: byRole,
|
|
269
|
+
grounds: [...grounds].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([c, a]) => ({ color: c, share: Math.round((a / page) * 100) / 100 })),
|
|
270
|
+
textColors: [...inks].sort((a, b) => b[1] - a[1]).slice(0, 6).map(([c, n]) => ({ color: c, chars: n })),
|
|
271
|
+
images, sections,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The logo beside each family in use, drawn on the live page (its fonts are loaded there). */
|
|
276
|
+
async function typeVsLogo(page, families, logoSrc, name, file) {
|
|
277
|
+
const height = await page.evaluate(({ families, logoSrc, name }) => {
|
|
278
|
+
const box = document.createElement('div');
|
|
279
|
+
box.id = 'ra-specimen';
|
|
280
|
+
box.style.cssText = 'position:absolute;left:0;top:0;width:100%;z-index:2147483647;background:#fff;color:#111;padding:40px;display:grid;grid-template-columns:auto 1fr;gap:40px;align-items:start;overflow:hidden';
|
|
281
|
+
const l = document.createElement('div');
|
|
282
|
+
const mark = !logoSrc && document.querySelector('header a[href="/"], [role="banner"] a[href="/"]');
|
|
283
|
+
if (logoSrc) l.innerHTML = `<img src="${logoSrc}" style="height:220px;width:auto;display:block"><div style="font:12px system-ui;margin-top:8px;color:#666">logo at 220px tall</div>`;
|
|
284
|
+
else if (mark) {
|
|
285
|
+
// The text wordmark, cloned on the live page (its CSS applies), drawn three times larger.
|
|
286
|
+
const c = mark.cloneNode(true);
|
|
287
|
+
c.removeAttribute('href');
|
|
288
|
+
c.style.cssText = 'zoom:3;display:inline-flex;position:static;transform:none';
|
|
289
|
+
l.append(c);
|
|
290
|
+
l.insertAdjacentHTML('beforeend', '<div style="font:12px system-ui;margin-top:8px;color:#666">text wordmark at 3x</div>');
|
|
291
|
+
}
|
|
292
|
+
const r = document.createElement('div');
|
|
293
|
+
r.style.cssText = 'display:grid;gap:22px';
|
|
294
|
+
for (const f of families) {
|
|
295
|
+
const row = document.createElement('div');
|
|
296
|
+
row.innerHTML = `<div style="font:12px system-ui;color:#666;margin-bottom:4px">${f.family} (${Math.round(f.share * 100)}% of the text${f.loaded ? '' : ', NOT LOADED'})</div>` +
|
|
297
|
+
`<div style="font-family:'${f.family}';font-size:56px;line-height:1.05;font-weight:400">${name} 1'250'000</div>` +
|
|
298
|
+
`<div style="font-family:'${f.family}';font-size:56px;line-height:1.05;font-weight:700;text-transform:uppercase">${name.split(/\s+/)[0]} 4.5 · 96</div>`;
|
|
299
|
+
r.append(row);
|
|
300
|
+
}
|
|
301
|
+
box.append(l, r);
|
|
302
|
+
window.scrollTo(0, 0);
|
|
303
|
+
document.body.append(box);
|
|
304
|
+
return Promise.all([...box.querySelectorAll('img')].map((i) => i.decode().catch(() => {}))).then(() => box.getBoundingClientRect().height);
|
|
305
|
+
}, { families, logoSrc, name });
|
|
306
|
+
await page.waitForTimeout(200);
|
|
307
|
+
await page.screenshot({ path: file, clip: { x: 0, y: 0, width: page.viewportSize().width, height: Math.ceil(height) } });
|
|
308
|
+
await page.evaluate(() => document.getElementById('ra-specimen')?.remove());
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const summary = { page: BASE + PATH, measuredProblems: problems, taste: problems.filter((p) => p.includes('taste:')), widths: {} };
|
|
312
|
+
const files = [];
|
|
313
|
+
try {
|
|
314
|
+
const site = await shots(BASE + PATH, 'page', injectCss);
|
|
315
|
+
for (const [w, s] of Object.entries(site)) {
|
|
316
|
+
summary.widths[w] = await s.page.evaluate(measure);
|
|
317
|
+
files.push([s.first, `the page, first screen at ${w}`], [s.full, `the page, full at ${w}`]);
|
|
318
|
+
}
|
|
319
|
+
const d = summary.widths['1440'];
|
|
320
|
+
if (d.logo?.src) {
|
|
321
|
+
// An image CDN serves the logo as a raster derivative: fetch the original too (an SVG tells more).
|
|
322
|
+
const seg = new URL(d.logo.src).pathname.split('/').pop()?.split('.')[0] ?? '';
|
|
323
|
+
let original = null;
|
|
324
|
+
try {
|
|
325
|
+
const u = Buffer.from(seg.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
|
|
326
|
+
if (/^https?:\/\/[^\s]+$/.test(u)) original = u;
|
|
327
|
+
} catch {}
|
|
328
|
+
if (original) d.logo.originalUrl = original;
|
|
329
|
+
try {
|
|
330
|
+
const res = await site['1440'].page.request.get(original && /\.svg$/i.test(original) ? original : d.logo.src);
|
|
331
|
+
const ext = (extname(new URL(res.url()).pathname) || '.img').slice(0, 6);
|
|
332
|
+
await writeFile(join(OUT, `logo${ext}`), await res.body());
|
|
333
|
+
files.push([`logo${ext}`, 'the logo file as served']);
|
|
334
|
+
if (ext === '.svg') {
|
|
335
|
+
const svg = (await res.text()).slice(0, 200000);
|
|
336
|
+
d.logo.svg = { textElements: (svg.match(/<text\b/g) || []).length, fontFamilies: [...new Set((svg.match(/font-family\s*[:=]\s*["']?([^;"'>]+)/g) || []).map((m) => m.replace(/font-family\s*[:=]\s*["']?/, '').trim()))], fills: [...new Set((svg.match(/#[0-9a-f]{6}\b|#[0-9a-f]{3}\b/gi) || []).map((c) => c.toLowerCase()))] };
|
|
337
|
+
}
|
|
338
|
+
} catch {}
|
|
339
|
+
}
|
|
340
|
+
await typeVsLogo(site['1440'].page, d.families.filter((f) => f.share >= 0.02), d.logo?.src, (d.logo?.alt || d.logo?.text || 'Agency').replace(/\s+(AG|SA|GmbH|Sàrl|SARL|SRL|SL|SAS|Srl)$/i, ''), join(OUT, 'type-vs-logo.png'));
|
|
341
|
+
files.push(['type-vs-logo.png', "the logo beside every font family in use: does the type echo the logo's character, or contrast with it on purpose?"]);
|
|
342
|
+
for (const s of Object.values(site)) await s.ctx.close();
|
|
343
|
+
|
|
344
|
+
if (ANCHOR) {
|
|
345
|
+
const a = await shots(ANCHOR + ANCHOR_PATH, 'anchor');
|
|
346
|
+
summary.anchor = { url: ANCHOR + ANCHOR_PATH, widths: {} };
|
|
347
|
+
for (const [w, s] of Object.entries(a)) {
|
|
348
|
+
summary.anchor.widths[w] = await s.page.evaluate(measure);
|
|
349
|
+
files.unshift([s.first, `the anchor, first screen at ${w}`], [s.full, `the anchor, full at ${w}`]);
|
|
350
|
+
await s.ctx.close();
|
|
351
|
+
}
|
|
352
|
+
} else if (ANCHOR_SHOTS) {
|
|
353
|
+
summary.anchor = { shots: [] };
|
|
354
|
+
for (const f of ANCHOR_SHOTS.split(',').map((s) => s.trim()).filter(Boolean)) {
|
|
355
|
+
const name = `anchor-${basename(f)}`;
|
|
356
|
+
await copyFile(f, join(OUT, name));
|
|
357
|
+
summary.anchor.shots.push(name);
|
|
358
|
+
files.unshift([name, `the anchor (given): ${basename(f)}`]);
|
|
359
|
+
}
|
|
360
|
+
} else {
|
|
361
|
+
summary.anchor = null;
|
|
362
|
+
}
|
|
363
|
+
} finally {
|
|
364
|
+
await browser.close();
|
|
365
|
+
stop();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
for (const f of ['BRIEF.md', 'DESIGN-NOTES.md']) {
|
|
369
|
+
if (existsSync(f)) {
|
|
370
|
+
await copyFile(f, join(OUT, f));
|
|
371
|
+
files.unshift([f, f === 'BRIEF.md' ? 'what the agency asked for (facts and tone: never contradict it)' : 'what the builder decided and why (anything kept on purpose is named here)']);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (PREVIOUS) {
|
|
375
|
+
await copyFile(PREVIOUS, join(OUT, 'PREVIOUS-CRITIC.md'));
|
|
376
|
+
files.unshift(['PREVIOUS-CRITIC.md', 'the previous round\'s critique: this is round 2, check each of its fixes first']);
|
|
377
|
+
}
|
|
378
|
+
await copyFile(here('../critic/CRITIC.md'), join(OUT, 'CRITIC.md'));
|
|
379
|
+
await copyFile(here('../TASTE.md'), join(OUT, 'TASTE.md'));
|
|
380
|
+
await writeFile(join(OUT, 'summary.json'), JSON.stringify(summary, null, 2));
|
|
381
|
+
const index = `# Critic input: ${BASE + PATH}
|
|
382
|
+
|
|
383
|
+
Read CRITIC.md first (your instructions; the rubric is TASTE.md), then the files below in this order.
|
|
384
|
+
summary.json holds the measured facts: \`taste\` (problems the screenshot tool measured), and per width
|
|
385
|
+
the fonts by role, families in use, grounds and text colours, the logo (drawn size, file, SVG facts),
|
|
386
|
+
images (file pixels per CSS pixel: \`density\` under the width's dpr means upscaled), and the sections
|
|
387
|
+
(top, height, ground, padding) for the rhythm line.
|
|
388
|
+
${summary.anchor ? '' : '\nNo anchor was given: judge against the style named in BRIEF.md and DESIGN-NOTES.md, and say so.\n'}
|
|
389
|
+
${files.map(([f, what]) => `- ${f}: ${what}`).join('\n')}
|
|
390
|
+
- summary.json: the measured facts
|
|
391
|
+
- TASTE.md: the rubric
|
|
392
|
+
|
|
393
|
+
Measured taste lines: ${summary.taste.length ? '\n' + summary.taste.map((t) => `- ${t}`).join('\n') : 'none.'}
|
|
394
|
+
`;
|
|
395
|
+
await writeFile(join(OUT, 'INDEX.md'), index);
|
|
396
|
+
console.log(`Critic input in ${OUT}/ (${files.length + 3} files). Give the critic ${join(OUT, 'INDEX.md')} and nothing else.`);
|
|
397
|
+
if (summary.taste.length) console.log(`${summary.taste.length} measured taste line(s):\n ${summary.taste.join('\n ')}`);
|