@domandigital/create-site 0.5.1 → 0.7.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.
@@ -0,0 +1,65 @@
1
+ // Stage 06 gate: governed facts are imported, never retyped. A price, a term
2
+ // or a response target a visitor reads comes from site.facts.ts, or from a
3
+ // generated file an importer writes from the governed source before every
4
+ // build (site.programme.json facts.importer: the site's own script, run
5
+ // first). This fails on a pound sign followed by digits, a response target
6
+ // in hours or days, a minimum term or a notice period typed anywhere in the
7
+ // site's source or its copy deck, so a figure typed by hand cannot ship.
8
+ //
9
+ // Lifted from apps/site/scripts/facts.ts and tests/facts.test.mjs in
10
+ // Doman-Digital (DOM-647).
11
+
12
+ import { spawnSync } from "node:child_process";
13
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
14
+ import { join, relative } from "node:path";
15
+ import { programme, root, sitePath, stop } from "./programme.mjs";
16
+
17
+ const GATE = "facts";
18
+ const { paths, facts = {} } = programme();
19
+
20
+ if (facts.importer) {
21
+ const importer = sitePath(facts.importer);
22
+ if (!existsSync(importer)) stop(GATE, "06", `the importer ${facts.importer} named in site.programme.json does not exist.`);
23
+ const args = importer.endsWith(".ts") ? ["--import", "tsx", importer] : [importer];
24
+ const run = spawnSync(process.execPath, args, { cwd: root, stdio: "inherit" });
25
+ if (run.status !== 0) stop(GATE, "06", `the importer ${facts.importer} failed, so the generated facts are not current.`);
26
+ }
27
+
28
+ const patterns = [
29
+ { name: "a pound figure", re: /£\s?\d/ },
30
+ { name: "a response target in hours", re: /within \d+ (hours?|business hours)/i },
31
+ { name: "a response target in days", re: /within \d+ (UK )?(business |working )?days?/i },
32
+ { name: "a minimum term", re: /\d+[- ]months? minimum/i },
33
+ { name: "a notice period", re: /\d+ days['’]? notice/i },
34
+ ];
35
+ const SKIP_DIRS = new Set(["generated", "node_modules", ".next", ".astro", "dist"]);
36
+ const walk = (dir) =>
37
+ readdirSync(dir).flatMap((f) => {
38
+ const p = join(dir, f);
39
+ if (statSync(p).isDirectory()) return SKIP_DIRS.has(f) ? [] : walk(p);
40
+ return [p];
41
+ });
42
+
43
+ const files = new Set();
44
+ for (const dir of paths.source) {
45
+ const abs = sitePath(dir);
46
+ if (existsSync(abs)) for (const f of walk(abs)) if (/\.(astro|tsx?|jsx?|mjs|mdx?|css)$/.test(f)) files.add(f);
47
+ }
48
+ if (existsSync(sitePath(paths.deck))) files.add(sitePath(paths.deck));
49
+
50
+ const offenders = [];
51
+ for (const file of files) {
52
+ if (relative(root, file) === "site.facts.ts") continue;
53
+ const lines = readFileSync(file, "utf8").split("\n");
54
+ lines.forEach((line, i) => {
55
+ if (line.includes("facts-ok")) return;
56
+ for (const { name, re } of patterns) {
57
+ const m = line.match(re);
58
+ if (m) offenders.push(` ${relative(root, file)}:${i + 1}: ${name} (${m[0]})`);
59
+ }
60
+ });
61
+ }
62
+ if (offenders.length) {
63
+ stop(GATE, "06", `typed figures found. Read each from site.facts.ts (or the generated facts) instead; a genuine non-claim takes facts-ok on its line.\n${offenders.join("\n")}`);
64
+ }
65
+ console.log(`${GATE}: ${files.size} files carry no typed price, term or response target`);
@@ -0,0 +1,229 @@
1
+ // Stage 06 gate: measures the rendered pages rather than trusting the
2
+ // stylesheet, phone first (STANDARD.md section 10 in @domandigital/craft):
3
+ // 375 x 812, the floor every surface is designed at, then 390 x 844, the
4
+ // width the design is accepted at, then 1440 x 900. On every page named in
5
+ // site.programme.json measure.pages, at every width: the page answers,
6
+ // nothing scrolls sideways, no visible text is smaller than
7
+ // measure.minFontPx, and, when measure.labels names them, every label sits
8
+ // inside its container, over no other label and no copy. At the two phone
9
+ // widths, also: every link, button, field and summary a thumb has to hit is
10
+ // at least 44 x 44 CSS px (a link inside a sentence is exempt, as in WCAG
11
+ // 2.5.5; a field's label counts as its target), and every text field is set
12
+ // at 16px or more, so Safari on iOS does not zoom on focus. With --preview,
13
+ // every page must also carry a noindex robots meta, so a preview cannot be
14
+ // indexed. Writes measure/measure.json, with the hash of the direction it
15
+ // measured, and a full-page capture per page and width under measure/out,
16
+ // phone captures first. Exits 1 on any failure.
17
+ //
18
+ // --serve serves the last build itself and measures that: static output in
19
+ // dist/ is served from here the way the host serves it (no trailing slash,
20
+ // the 404 page for anything missing); a Next build runs next start.
21
+ // deploy-preview.mjs runs `--serve --preview` before every preview deploy.
22
+ // --base <url> measures a server that is already running instead.
23
+ //
24
+ // Lifted from apps/site/scripts/measure.mjs in Doman-Digital (DOM-647), with
25
+ // the redesign's own label component generalised to a selector.
26
+
27
+ import { spawn } from "node:child_process";
28
+ import { createHash } from "node:crypto";
29
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
30
+ import { createServer } from "node:http";
31
+ import { extname, join } from "node:path";
32
+ import { parseArgs } from "node:util";
33
+ import { programme, root, sitePath, stop } from "./programme.mjs";
34
+
35
+ const GATE = "measure";
36
+ const { values } = parseArgs({ options: { base: { type: "string" }, serve: { type: "boolean", default: false }, preview: { type: "boolean", default: false } } });
37
+ const { measure = {}, paths } = programme();
38
+ const port = measure.port ?? 4410;
39
+ const base = (values.base ?? `http://127.0.0.1:${port}`).replace(/\/$/, "");
40
+ const pages = measure.pages?.length ? measure.pages : ["/"];
41
+ const minFontPx = measure.minFontPx ?? 12;
42
+ // The house floors at phone width: STANDARD.md section 10. Not per-site settings.
43
+ const MIN_TARGET_PX = 44;
44
+ const MIN_FIELD_FONT_PX = 16;
45
+ const labels = measure.labels ?? null;
46
+ const outDir = join(root, "measure", "out");
47
+ mkdirSync(outDir, { recursive: true });
48
+
49
+ let chromium;
50
+ try {
51
+ ({ chromium } = await import("playwright"));
52
+ } catch {
53
+ stop(GATE, "06", "playwright is not installed. Add it as a dev dependency and run `npx playwright install chromium`.");
54
+ }
55
+
56
+ const close = values.serve ? await serveBuild() : () => {};
57
+
58
+ const hash = (p) => (existsSync(p) ? createHash("sha256").update(readFileSync(p)).digest("hex").slice(0, 16) : null);
59
+ const slug = (route) => (route === "/" ? "home" : route.replace(/^\//, "").replace(/\//g, "-"));
60
+ const VIEWPORTS = [
61
+ { name: "375x812", phone: true, viewport: { width: 375, height: 812 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true },
62
+ { name: "390x844", phone: true, viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true },
63
+ { name: "1440x900", phone: false, viewport: { width: 1440, height: 900 } },
64
+ ];
65
+
66
+ const browser = await chromium.launch();
67
+ const failures = [];
68
+ const res = { base, measuredAt: new Date().toISOString(), preview: values.preview, direction: hash(join(root, "art-direction.json")), tokens: hash(sitePath(paths.tokens)), minFontPx, minTargetPx: MIN_TARGET_PX, minFieldFontPx: MIN_FIELD_FONT_PX, pages: {} };
69
+
70
+ for (const route of pages) {
71
+ res.pages[route] = {};
72
+ for (const { name, phone, ...options } of VIEWPORTS) {
73
+ const context = await browser.newContext(options);
74
+ const page = await context.newPage();
75
+ const resp = await page.goto(base + route).catch((error) => ({ ok: () => false, status: () => error.message }));
76
+ if (!resp || !resp.ok()) {
77
+ res.pages[route][name] = { error: `HTTP ${resp?.status()}` };
78
+ failures.push(`${route} at ${name}: HTTP ${resp?.status()}`);
79
+ await context.close();
80
+ continue;
81
+ }
82
+ await page.evaluate(() => document.fonts.ready);
83
+ await settle(page);
84
+ const m = await page.evaluate(
85
+ ({ labels, minFontPx, phone, minTargetPx, minFieldFontPx }) => {
86
+ const R = (e) => {
87
+ const r = e.getBoundingClientRect();
88
+ return { l: r.left, t: r.top, r: r.right, b: r.bottom };
89
+ };
90
+ const ov = (a, b) => !(a.r <= b.l || b.r <= a.l || a.b <= b.t || b.b <= a.t);
91
+ const shown = (e) => {
92
+ const s = getComputedStyle(e);
93
+ return s.display !== "none" && s.visibility !== "hidden" && e.getClientRects().length > 0;
94
+ };
95
+ // Text an element shows itself, not text it inherits from a child.
96
+ const texty = [...document.querySelectorAll("body *")].filter(
97
+ (e) => shown(e) && [...e.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim()) && !e.closest("[aria-hidden='true'], .sr-only, .visually-hidden"),
98
+ );
99
+ const small = texty
100
+ .map((e) => ({ tag: e.tagName.toLowerCase(), cls: String(e.className || ""), px: parseFloat(getComputedStyle(e).fontSize), text: e.textContent.trim().slice(0, 40) }))
101
+ .filter((t) => t.px < minFontPx);
102
+ const out = {
103
+ horizontalScroll: document.documentElement.scrollWidth > window.innerWidth,
104
+ fontSizesUsed: [...new Set(texty.map((e) => getComputedStyle(e).fontSize))].sort((a, b) => parseFloat(a) - parseFloat(b)),
105
+ smallText: small.slice(0, 10),
106
+ noindex: /noindex/i.test(document.querySelector('meta[name="robots"]')?.getAttribute("content") ?? ""),
107
+ labels: [],
108
+ smallTargets: [],
109
+ smallFields: [],
110
+ };
111
+ if (phone) {
112
+ const name = (e) => ({ tag: e.tagName.toLowerCase(), cls: String(e.className || ""), text: (e.textContent.trim() || e.getAttribute("aria-label") || e.getAttribute("name") || "").slice(0, 40) });
113
+ // Visually hidden (an sr-only skip link) or parked off the page: not a target until it is shown.
114
+ const hidden = (e, r) => e.closest("[aria-hidden='true'], .sr-only, .visually-hidden") || r.width <= 1 || r.height <= 1 || r.right <= 0 || r.bottom <= -window.scrollY;
115
+ // WCAG 2.5.5's inline exception: a link in a sentence is sized by the line it sits in.
116
+ const inline = (e) => {
117
+ if (e.tagName !== "A" || getComputedStyle(e).display !== "inline") return false;
118
+ const block = e.parentElement?.closest("p, li, dd, td, th, blockquote, figcaption, address");
119
+ return !!block && block.textContent.trim().length > e.textContent.trim().length;
120
+ };
121
+ const targets = [...document.querySelectorAll("a[href], button, input:not([type='hidden']), select, textarea, [role='button'], summary")].filter(shown);
122
+ for (const e of targets) {
123
+ const r = e.getBoundingClientRect();
124
+ if (hidden(e, r) || inline(e)) continue;
125
+ // A field's label is a hit target too: a 20px checkbox in a 44px label passes.
126
+ const boxes = [r, ...[...(e.labels ?? [])].filter(shown).map((l) => l.getBoundingClientRect())];
127
+ const w = Math.max(...boxes.map((b) => b.width));
128
+ const h = Math.max(...boxes.map((b) => b.height));
129
+ if (Math.round(w) < minTargetPx || Math.round(h) < minTargetPx) out.smallTargets.push({ ...name(e), w: Math.round(w), h: Math.round(h) });
130
+ }
131
+ const NOT_TEXT = new Set(["checkbox", "radio", "range", "color", "file", "submit", "reset", "button", "image"]);
132
+ for (const e of document.querySelectorAll("input:not([type='hidden']), select, textarea")) {
133
+ if (!shown(e) || (e.tagName === "INPUT" && NOT_TEXT.has(e.type))) continue;
134
+ const px = parseFloat(getComputedStyle(e).fontSize);
135
+ if (px < minFieldFontPx) out.smallFields.push({ ...name(e), px: Math.round(px * 10) / 10 });
136
+ }
137
+ }
138
+ if (labels?.selector) {
139
+ const all = [...document.querySelectorAll(labels.selector)].filter(shown);
140
+ const copy = [...document.querySelectorAll("main h1, main h2, main h3, main p, main li")].filter(shown);
141
+ for (const l of all) {
142
+ const r = R(l);
143
+ const box = labels.within ? l.parentElement?.closest(labels.within) : null;
144
+ const b = box ? R(box) : null;
145
+ out.labels.push({
146
+ text: l.textContent.trim().slice(0, 40),
147
+ inside: b ? r.l >= b.l - 0.5 && r.t >= b.t - 0.5 && r.r <= b.r + 0.5 && r.b <= b.b + 0.5 : null,
148
+ overLabels: all.filter((o) => o !== l && ov(r, R(o))).length,
149
+ overCopy: copy.filter((t) => !l.contains(t) && !t.contains(l) && ov(r, R(t))).length,
150
+ fontPx: parseFloat(getComputedStyle(l).fontSize),
151
+ });
152
+ }
153
+ }
154
+ return out;
155
+ },
156
+ { labels, minFontPx, phone, minTargetPx: MIN_TARGET_PX, minFieldFontPx: MIN_FIELD_FONT_PX },
157
+ );
158
+ const at = `${route} at ${name}`;
159
+ if (m.horizontalScroll) failures.push(`${at}: the page scrolls sideways`);
160
+ for (const t of m.smallText) failures.push(`${at}: ${t.px}px text under ${minFontPx}px (<${t.tag}${t.cls ? ` class="${t.cls}"` : ""}> "${t.text}")`);
161
+ const tag = (t) => `<${t.tag}${t.cls ? ` class="${t.cls}"` : ""}>${t.text ? ` "${t.text}"` : ""}`;
162
+ for (const t of m.smallTargets.slice(0, 10)) failures.push(`${at}: a ${t.w}x${t.h}px target under ${MIN_TARGET_PX}x${MIN_TARGET_PX} (${tag(t)})`);
163
+ if (m.smallTargets.length > 10) failures.push(`${at}: ${m.smallTargets.length - 10} more targets under ${MIN_TARGET_PX}x${MIN_TARGET_PX}; measure/measure.json lists them`);
164
+ for (const t of m.smallFields) failures.push(`${at}: a field set at ${t.px}px, under ${MIN_FIELD_FONT_PX}px, so Safari on iOS zooms on focus (${tag(t)})`);
165
+ for (const l of m.labels) {
166
+ if (l.inside === false) failures.push(`${at}: label "${l.text}" leaves its ${labels.within}`);
167
+ if (l.overLabels) failures.push(`${at}: label "${l.text}" sits over another label`);
168
+ if (l.overCopy) failures.push(`${at}: label "${l.text}" sits over copy`);
169
+ }
170
+ if (values.preview && !m.noindex) failures.push(`${at}: no noindex robots meta on a preview build (read PUBLIC_PREVIEW)`);
171
+ res.pages[route][name] = m;
172
+ await page.screenshot({ path: join(outDir, `${slug(route)}-${name}.png`), fullPage: true });
173
+ await context.close();
174
+ }
175
+ }
176
+ await browser.close();
177
+ close();
178
+
179
+ res.failures = failures;
180
+ writeFileSync(join(root, "measure", "measure.json"), `${JSON.stringify(res, null, 1)}\n`);
181
+ console.log(`${GATE}: ${pages.length} page(s) at 375, 390 and 1440, phone first, against ${base}; captures in measure/out, report in measure/measure.json`);
182
+ if (failures.length) stop(GATE, "06", `${failures.length} failure(s):\n${failures.map((f) => ` ${f}`).join("\n")}`);
183
+
184
+ /** Serves the last build on measure.port and returns how to stop it. */
185
+ async function serveBuild() {
186
+ // Something already answering on the port would be measured in this build's place.
187
+ if (await fetch(base).then(() => true, () => false)) stop(GATE, "06", `something is already answering on ${base}. Stop it, or set measure.port in site.programme.json.`);
188
+ const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".mjs": "text/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".avif": "image/avif", ".woff2": "font/woff2", ".ico": "image/x-icon", ".txt": "text/plain", ".xml": "application/xml" };
189
+ const dist = join(root, "dist");
190
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
191
+ let stopServer;
192
+ if (existsSync(join(dist, "index.html"))) {
193
+ const server = createServer((req, res) => {
194
+ const path = decodeURIComponent(new URL(req.url, base).pathname).replace(/\/+$/, "").slice(1);
195
+ const candidates = path === "" ? ["index.html"] : [path, `${path}.html`, `${path}/index.html`];
196
+ const file = candidates.map((c) => join(dist, c)).find((f) => f.startsWith(dist) && existsSync(f) && statSync(f).isFile());
197
+ const notFound = join(dist, "404.html");
198
+ const body = file ?? (existsSync(notFound) ? notFound : null);
199
+ res.writeHead(file ? 200 : 404, { "content-type": TYPES[extname(body ?? ".html")] ?? "application/octet-stream" });
200
+ res.end(body ? readFileSync(body) : "Not found");
201
+ });
202
+ await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));
203
+ stopServer = () => server.close();
204
+ } else if (pkg.dependencies?.next ?? pkg.devDependencies?.next) {
205
+ const child = spawn(join(root, "node_modules", ".bin", "next"), ["start", "-p", String(port), "-H", "127.0.0.1"], { cwd: root, stdio: "ignore" });
206
+ stopServer = () => child.kill();
207
+ } else {
208
+ stop(GATE, "06", "no static build in dist/ and no next to start. Build first.");
209
+ }
210
+ for (let i = 0; i < 60; i++) {
211
+ if (await fetch(base).then((r) => r.status < 500, () => false)) return stopServer;
212
+ await new Promise((r) => setTimeout(r, 1000));
213
+ }
214
+ stopServer();
215
+ stop(GATE, "06", `the build did not answer on ${base} within a minute.`);
216
+ }
217
+
218
+ // Scroll through the page so lazy images load before the capture, then back to the top.
219
+ async function settle(p) {
220
+ await p.evaluate(async () => {
221
+ const h = document.documentElement.scrollHeight;
222
+ for (let y = 0; y < h; y += 600) {
223
+ window.scrollTo(0, y);
224
+ await new Promise((r) => setTimeout(r, 40));
225
+ }
226
+ window.scrollTo(0, 0);
227
+ });
228
+ await p.waitForTimeout(600);
229
+ }
@@ -0,0 +1,91 @@
1
+ // Stage 06 gate: the phone is the base layout (STANDARD.md section 10 in
2
+ // @domandigital/craft). Base styles are the phone; wider layouts are added
3
+ // with min-width queries. This fails on a max-width media query (`max-width:`,
4
+ // or the range syntax `width <`, `width <=`, `600px > width`) and on a
5
+ // Tailwind max-* variant (`max-sm:`, `max-md:`, `max-[40rem]:`) anywhere in
6
+ // the site's source, because a layout written desktop first and taken away
7
+ // for the phone is how a site ends up designed for the desktop.
8
+ //
9
+ // An exception is recorded, never assumed: `mobile-first-ok: <reason>` in a
10
+ // comment on the line or the line above, or the whole file in
11
+ // site.programme.json mobileFirst.exceptions as { "file", "reason" }. An
12
+ // exception with no reason fails, and so does one naming a file that is not
13
+ // there.
14
+
15
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
+ import { join, normalize, relative } from "node:path";
17
+ import { programme, root, sitePath, stop } from "./programme.mjs";
18
+
19
+ const GATE = "mobile-first";
20
+ const { paths = {}, mobileFirst = {} } = programme();
21
+
22
+ // The source paths.source names, and the usual homes of styles even when it does not.
23
+ const DIRS = [...new Set([...(paths.source ?? []), "src", "app", "components", "styles"])];
24
+ const EXTENSIONS = /\.(css|scss|sass|less|astro|tsx|jsx|ts|js|mjs|vue|svelte|mdx|html)$/;
25
+ const SKIP_DIRS = new Set(["generated", "node_modules", ".next", ".astro", "dist"]);
26
+ const walk = (dir) =>
27
+ readdirSync(dir).flatMap((f) => {
28
+ const p = join(dir, f);
29
+ if (statSync(p).isDirectory()) return SKIP_DIRS.has(f) ? [] : walk(p);
30
+ return [p];
31
+ });
32
+
33
+ const files = new Set();
34
+ for (const dir of DIRS) {
35
+ const abs = sitePath(dir);
36
+ if (existsSync(abs) && statSync(abs).isDirectory()) for (const f of walk(abs)) if (EXTENSIONS.test(f)) files.add(f);
37
+ }
38
+
39
+ const problems = [];
40
+ const excepted = new Map();
41
+ for (const [i, e] of (mobileFirst.exceptions ?? []).entries()) {
42
+ const at = `site.programme.json mobileFirst.exceptions[${i}]`;
43
+ if (typeof e?.file !== "string" || !e.file.trim()) problems.push(` ${at}: names no file`);
44
+ else if (typeof e.reason !== "string" || !e.reason.trim()) problems.push(` ${at} (${e.file}): no reason. Say why this file needs a max-width query, or remove the exception.`);
45
+ else if (!existsSync(sitePath(e.file))) problems.push(` ${at}: ${e.file} is not there. Remove the exception.`);
46
+ else excepted.set(normalize(e.file), e.reason.trim());
47
+ }
48
+
49
+ // A media query whose condition caps the width. The prelude runs to the rule's `{` (or the `;` of @custom-media).
50
+ const MEDIA = /@(?:custom-)?media\b([^{;]*)/g;
51
+ const CAPS_WIDTH = /\bmax-(?:device-)?width\s*:|\bwidth\s*<|>=?\s*(?:device-)?width\b/i;
52
+ // A Tailwind max-* variant. Single-word CSS properties and media features spelt max-* are not variants.
53
+ const VARIANT = /(?<![\w@-])max-(\[[^\]\s]+\]|[a-z0-9]+):/g;
54
+ const NOT_VARIANTS = new Set(["width", "height", "lines", "resolution", "zoom"]);
55
+ const OK = /mobile-first-ok\b:?(.*)/;
56
+ const reasonOf = (line) => {
57
+ const m = line?.match(OK);
58
+ return m ? m[1].replace(/\*\/|-->|[{}]/g, "").trim() : null;
59
+ };
60
+
61
+ let exceptions = excepted.size;
62
+ for (const file of files) {
63
+ const rel = relative(root, file);
64
+ if (excepted.has(normalize(rel))) continue;
65
+ const text = readFileSync(file, "utf8");
66
+ const lines = text.split("\n");
67
+ const lineOf = (index) => text.slice(0, index).split("\n").length;
68
+ const found = [];
69
+ for (const m of text.matchAll(MEDIA)) {
70
+ if (CAPS_WIDTH.test(m[1])) found.push({ line: lineOf(m.index), what: `a max-width media query (@media${m[1].replace(/\s+/g, " ").trimEnd()})` });
71
+ }
72
+ for (const m of text.matchAll(VARIANT)) {
73
+ if (!NOT_VARIANTS.has(m[1])) found.push({ line: lineOf(m.index), what: `a Tailwind max-* variant (${m[0]})` });
74
+ }
75
+ for (const { line, what } of found) {
76
+ const here = reasonOf(lines[line - 1]);
77
+ const above = reasonOf(lines[line - 2]);
78
+ const reason = here ?? above;
79
+ if (reason) {
80
+ exceptions++;
81
+ continue;
82
+ }
83
+ if (here === "" || above === "") problems.push(` ${rel}:${line}: mobile-first-ok with no reason, on ${what}`);
84
+ else problems.push(` ${rel}:${line}: ${what}`);
85
+ }
86
+ }
87
+
88
+ if (problems.length) {
89
+ stop(GATE, "06", `the phone is not the base layout. Write the phone as the base styles and add wider layouts with min-width (Tailwind: sm: md: lg:). A genuine exception takes mobile-first-ok: <reason> on its line, or the file in site.programme.json mobileFirst.exceptions with a reason.\n${problems.join("\n")}`);
90
+ }
91
+ console.log(`${GATE}: ${files.size} files build the phone first, with min-width only${exceptions ? ` (${exceptions} recorded exception${exceptions === 1 ? "" : "s"})` : ""}`);
@@ -0,0 +1,68 @@
1
+ // Stage 05 gate: measures both sides of the sheet the way the day side was
2
+ // measured, every text colour against its ground by WCAG 2.x relative
3
+ // luminance, from the stylesheet tokens.mjs wrote. Exits 1 when a pair that
4
+ // carries text falls under 4.5:1, so a palette change cannot ship an
5
+ // unreadable label by day or by night.
6
+ //
7
+ // Lifted from apps/site/scripts/night-contrast.mjs in Doman-Digital (DOM-647).
8
+
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { programme, sitePath, stop } from "./programme.mjs";
11
+
12
+ const GATE = "night-contrast";
13
+ const { paths } = programme();
14
+ const file = sitePath(paths.tokens);
15
+ if (!existsSync(file)) stop(GATE, "05", `no ${paths.tokens}: tokens.mjs writes it first.`);
16
+ const css = readFileSync(file, "utf8");
17
+ const block = (sel) => {
18
+ const i = css.indexOf(sel);
19
+ if (i < 0) stop(GATE, "05", `${paths.tokens} has no ${sel} block. Run tokens.mjs.`);
20
+ const body = css.slice(css.indexOf("{", i) + 1, css.indexOf("}", i));
21
+ return Object.fromEntries([...body.matchAll(/--([a-z0-9-]+):\s*(#[0-9a-f]{6})/gi)].map((m) => [m[1], m[2].toLowerCase()]));
22
+ };
23
+ const light = block(":root {");
24
+ const night = block(':root[data-theme="dark"]');
25
+
26
+ const lum = (hex) => {
27
+ const n = parseInt(hex.slice(1), 16);
28
+ const f = (v) => {
29
+ v /= 255;
30
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
31
+ };
32
+ return 0.2126 * f((n >> 16) & 255) + 0.7152 * f((n >> 8) & 255) + 0.0722 * f(n & 255);
33
+ };
34
+ const ratio = (a, b) => {
35
+ const x = lum(a);
36
+ const y = lum(b);
37
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
38
+ };
39
+
40
+ let failed = false;
41
+ for (const [name, t] of [
42
+ ["day", light],
43
+ ["night", night],
44
+ ]) {
45
+ const g = t.ground;
46
+ const pairs = [
47
+ ["ink on ground", t.ink, 4.5],
48
+ ["ink-2 on ground", t["ink-2"], 4.5],
49
+ ["ink-3 on ground", t["ink-3"], 4.5],
50
+ ["accent on ground (labels and links)", t.accent, 4.5],
51
+ ["ground on ink (primary button text)", g, 4.5, t.ink],
52
+ ["ground on accent (button hover text)", g, 4.5, t.accent],
53
+ ["rule on ground (1px rules, not text)", t.rule, 1.3],
54
+ ];
55
+ console.log(`${GATE}: ${name}, ground ${g}`);
56
+ for (const [label, fg, min, bg = g] of pairs) {
57
+ if (!fg || !bg) {
58
+ failed = true;
59
+ console.log(` FAIL missing ${label}`);
60
+ continue;
61
+ }
62
+ const r = ratio(fg, bg);
63
+ const ok = r >= min;
64
+ if (!ok) failed = true;
65
+ console.log(` ${ok ? "ok " : "FAIL"} ${r.toFixed(2)}:1 ${label} (${fg} on ${bg}, needs ${min})`);
66
+ }
67
+ }
68
+ if (failed) stop(GATE, "05", "a pair falls short. Change the value in art-direction.json or art-direction.sheets.json, not the stylesheet.");
@@ -0,0 +1,76 @@
1
+ // Stage 06 gate: reads the rendered copy deck against the null set's harvest,
2
+ // the phrases a model kept writing when it built the same brief with nobody
3
+ // deciding anything (`craft null build`, then `craft tells harvest`, saved as
4
+ // text or with --json). Every exact hit is listed with its line. A hit is not
5
+ // automatically a failure: a phrase can be the buyer's own words, kept on
6
+ // purpose, and then site.programme.json carries it under
7
+ // nullCheck.justified with the reason. An unjustified hit exits 1. The table
8
+ // is written to paths.nullCheck for the Stage 06 review. When the harvest is
9
+ // not on this machine the gate says so and passes.
10
+ //
11
+ // Lifted from apps/site/scripts/null-check.mjs in Doman-Digital (DOM-647).
12
+
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { dirname } from "node:path";
15
+ import { programme, sitePath, stop } from "./programme.mjs";
16
+
17
+ const GATE = "null-check";
18
+ const { paths, nullCheck = {} } = programme();
19
+ if (!nullCheck.harvest) {
20
+ console.log(`${GATE}: no harvest named in site.programme.json (nullCheck.harvest); skipped. Run craft null build for the brief to make one.`);
21
+ process.exit(0);
22
+ }
23
+ const harvest = sitePath(nullCheck.harvest);
24
+ if (!existsSync(harvest)) {
25
+ console.log(`${GATE}: harvest not on this machine (${nullCheck.harvest}); skipped`);
26
+ process.exit(0);
27
+ }
28
+ const deckPath = sitePath(paths.deckMarkdown);
29
+ if (!existsSync(deckPath)) stop(GATE, "06", `no ${paths.deckMarkdown}: copy-deck.mjs writes it.`);
30
+
31
+ const raw = readFileSync(harvest, "utf8");
32
+ let phrases;
33
+ if (raw.trimStart().startsWith("{")) {
34
+ phrases = (JSON.parse(raw).candidates ?? []).filter((c) => c.kind === "phrase").map((c) => ({ phrase: c.value.toLowerCase(), runs: c.runs, of: c.of }));
35
+ } else {
36
+ phrases = raw
37
+ .split("\n")
38
+ .map((l) => l.match(/^\s+phrase\s+(.+?)\s{2,}(\d+) of (\d+)/))
39
+ .filter(Boolean)
40
+ .map((m) => ({ phrase: m[1].trim().toLowerCase(), runs: +m[2], of: +m[3] }));
41
+ }
42
+ const justified = Object.fromEntries(Object.entries(nullCheck.justified ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
43
+
44
+ const deck = readFileSync(deckPath, "utf8").split("\n");
45
+ const hits = [];
46
+ for (const { phrase, runs, of } of phrases) {
47
+ deck.forEach((line, i) => {
48
+ if (line.toLowerCase().includes(phrase)) hits.push({ phrase, runs, of, line: i + 1, text: line.trim().slice(0, 120), justified: justified[phrase] ?? null });
49
+ });
50
+ }
51
+ const unjustified = hits.filter((h) => !h.justified);
52
+ const md = [
53
+ "# Null-set check · copy deck",
54
+ "",
55
+ `Run ${new Date().toISOString().slice(0, 10)} by \`scripts/gates/null-check.mjs\` against \`${nullCheck.harvest}\` (${phrases.length} phrases).`,
56
+ "",
57
+ `Hits: ${hits.length}. Unjustified: ${unjustified.length}.`,
58
+ "",
59
+ "| Phrase | Null runs | Deck line | Text | Kept because |",
60
+ "| --- | --- | --- | --- | --- |",
61
+ ...hits.map((h) => `| ${h.phrase} | ${h.runs} of ${h.of} | ${h.line} | ${h.text.replace(/\|/g, "\\|")} | ${h.justified ?? "**not justified**"} |`),
62
+ "",
63
+ `Phrases checked and absent: ${
64
+ phrases
65
+ .filter((p) => !hits.some((h) => h.phrase === p.phrase))
66
+ .map((p) => `"${p.phrase}"`)
67
+ .join(", ") || "none"
68
+ }.`,
69
+ "",
70
+ ];
71
+ const out = sitePath(paths.nullCheck);
72
+ mkdirSync(dirname(out), { recursive: true });
73
+ writeFileSync(out, md.join("\n"));
74
+ console.log(`${GATE}: ${hits.length} hits, ${unjustified.length} unjustified. Written to ${paths.nullCheck}`);
75
+ for (const h of unjustified) console.log(` line ${h.line}: "${h.phrase}" in: ${h.text}`);
76
+ if (unjustified.length) stop(GATE, "06", "rewrite each unjustified phrase, or keep it with a reason under nullCheck.justified in site.programme.json.");
@@ -0,0 +1,36 @@
1
+ // The build gates, in stage order, run before every build (the `prebuild`
2
+ // script). A gate is a script that blocks the build, never a reminder: the
3
+ // first one to fail stops the build and names its stage. The order matters:
4
+ // the direction is decided before tokens are written from it, the tokens are
5
+ // written before they are measured, and the deck is current before the null
6
+ // set reads it. The measurement at 375, 390 and 1440 (phone first) needs a
7
+ // running build, so deploy-preview.mjs runs it before every preview deploy
8
+ // instead.
9
+
10
+ import { spawnSync } from "node:child_process";
11
+ import { join } from "node:path";
12
+ import { programme, root, stop } from "./programme.mjs";
13
+
14
+ const GATES = [
15
+ ["check-direction.mjs"],
16
+ ["tokens.mjs"],
17
+ ["night-contrast.mjs"],
18
+ ["facts.mjs"],
19
+ ["copy-deck.mjs", "--check"],
20
+ ["null-check.mjs"],
21
+ ["mobile-first.mjs"],
22
+ ];
23
+
24
+ // Stage 01: the site has a programme in Linear before anything is built.
25
+ const { issue } = programme();
26
+ if (typeof issue !== "string" || !/^[A-Z]+-\d+$/.test(issue)) {
27
+ stop("programme", "01", "site.programme.json names no programme issue. Open the programme from the Site programme template in Linear and put its id (DOM-123) in issue.");
28
+ }
29
+
30
+ for (const [script, ...args] of GATES) {
31
+ const run = spawnSync(process.execPath, [join(root, "scripts", "gates", script), ...args], { cwd: root, stdio: "inherit" });
32
+ if (run.status !== 0) {
33
+ console.error(`\nThe build stops at ${script}. docs/site-programme.md says what its stage needs.`);
34
+ process.exit(run.status || 1);
35
+ }
36
+ }
@@ -0,0 +1,42 @@
1
+ // What every gate shares: the site's root, its site.programme.json (the
2
+ // site's own file, written once by create-site and never replaced), and one
3
+ // way to stop. Each gate names the programme stage it belongs to, so a
4
+ // failing build says which stage is not done. docs/site-programme.md has the
5
+ // ten stages and the gate each one owns.
6
+
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ export const root = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
13
+
14
+ /** site.programme.json, or a stop naming the file when it is missing or unreadable. */
15
+ export function programme() {
16
+ const path = join(root, "site.programme.json");
17
+ if (!existsSync(path)) stop("programme", "01", "no site.programme.json. Run create-site again: it writes the file and never replaces it.");
18
+ try {
19
+ return JSON.parse(readFileSync(path, "utf8"));
20
+ } catch (error) {
21
+ stop("programme", "01", `site.programme.json is not JSON: ${error.message}`);
22
+ }
23
+ }
24
+
25
+ /** A path from site.programme.json: `~/` is the home directory, anything else is relative to the site. */
26
+ export function sitePath(path) {
27
+ return path.startsWith("~/") ? join(homedir(), path.slice(2)) : resolve(root, path);
28
+ }
29
+
30
+ /** Exit 1 with the gate, its stage and the reason. A gate never warns its way past a failure. */
31
+ export function stop(gate, stage, message) {
32
+ console.error(`${gate} (Stage ${stage}): ${message}`);
33
+ process.exit(1);
34
+ }
35
+
36
+ /** The installed craft bin, so a gate runs the craft the site pinned, never a global one. */
37
+ export function craftBin() {
38
+ const manifest = join(root, "node_modules", "@domandigital", "craft", "package.json");
39
+ if (!existsSync(manifest)) return null;
40
+ const bin = JSON.parse(readFileSync(manifest, "utf8")).bin?.craft;
41
+ return bin ? join(dirname(manifest), bin) : null;
42
+ }