@su-sws/synthetic-web-team 0.2.7 → 0.2.8

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,393 @@
1
+ // The brief format: one small JSON document for a reader that has to act.
2
+ //
3
+ // The full JSON report runs to about 14 KB on a clean site and lists every
4
+ // pass. A build, check, fix loop wants the opposite: the score, what is
5
+ // failing, why the rest could not be checked, what only a person can settle,
6
+ // and what to do next, in a document small enough to read on every turn.
7
+ //
8
+ // Three rules hold this together:
9
+ //
10
+ // - STABLE KEYS. Every top-level key is always present, so a reader never
11
+ // branches on whether a section exists. An empty list is an empty list.
12
+ // - A CEILING, NOT A HOPE. The document is built at decreasing levels of
13
+ // detail until it fits BRIEF_CEILING bytes. Whatever a level leaves out is
14
+ // counted in `dropped`, so a short list never reads as a complete one.
15
+ // - NO SECOND OPINION. Nothing here re-decides a finding. States, weights and
16
+ // the score come from the same run the other formats render; this only
17
+ // selects, groups and orders them.
18
+ //
19
+ // `next` is data, in the same spirit as the installer's `next[]`: each entry
20
+ // names a kind, a command or a path, and why, so the reader can pick the one it
21
+ // is able to do. The order is the order to do them in.
22
+
23
+ import { isOverdue, ACKNOWLEDGED_PATH } from './acknowledged.mjs';
24
+
25
+ export const BRIEF_SCHEMA = 1;
26
+
27
+ // Bytes of UTF-8, the whole document. Typical output is well under half this.
28
+ export const BRIEF_CEILING = 4096;
29
+
30
+ // The package that carries this CLI. `npx sws` resolves to it only when it is
31
+ // a local dependency: unscoped `sws` on the public registry is unrelated.
32
+ const PACKAGE = '@su-sws/synthetic-web-team';
33
+
34
+ // --no-install, so a project without the local dependency gets an error and
35
+ // never a stranger's package.
36
+ const SWS = 'npx --no-install sws';
37
+
38
+ const MANIFEST_PATH = '.sws/manifest.yml';
39
+
40
+ // --- manifest fields still holding placeholders ------------------------------
41
+ //
42
+ // The same six fields, names and order the installer reports as `incomplete[]`
43
+ // (packages/wizard/bin/wizard.mjs, emitJson). There the test runs on the
44
+ // answers given at install time; here it runs on the manifest those answers
45
+ // were written into, so the list stays true after the install result is gone.
46
+ // An unanswered field is written as null, and an unanswered site name as the
47
+ // installer's default.
48
+ //
49
+ // scripts/validate-brief.mjs installs a project unattended and holds the two
50
+ // lists equal, so a field added on one side cannot go missing on the other.
51
+ const DEFAULT_SITE_NAME = 'Example Unit';
52
+ const blank = (v) => v == null || String(v).trim() === '';
53
+
54
+ export function manifestIncomplete(manifest) {
55
+ const m = manifest ?? {};
56
+ const out = [];
57
+ if (blank(m.owners?.business?.email)) out.push('owners.business.email');
58
+ if (blank(m.owners?.business?.name)) out.push('owners.business.name');
59
+ if (blank(m.owners?.technical?.email)) out.push('owners.technical.email');
60
+ if (blank(m.owners?.technical?.name)) out.push('owners.technical.name');
61
+ if (m.site?.name === DEFAULT_SITE_NAME) out.push('site.name');
62
+ if (blank(m.site?.url)) out.push('site.url');
63
+ return out;
64
+ }
65
+
66
+ // --- why a finding is unknown, coarsely --------------------------------------
67
+ //
68
+ // `manual`, `unimplemented` and `crashed` come from structure. The rest are
69
+ // read from the detail text the checks write, which is the only place the
70
+ // reason exists today; anything unrecognised is `other`, never a guess.
71
+ //
72
+ // `built` guards the one guess this could inherit: a criterion that produced no
73
+ // finding says "usually means ... no build output", and repeating that as fact
74
+ // on a project that HAS a build would send the reader to rebuild for nothing.
75
+ export function unknownReason(finding, criterion = {}, { built = false } = {}) {
76
+ const d = String(finding.detail ?? '');
77
+ if (String(finding.id).endsWith('.internal-error')) return 'crashed';
78
+ if (criterion.manual) return 'manual';
79
+ if (/^no check implemented yet/.test(d)) return 'unimplemented';
80
+ if (/^no check produced a result/.test(d)) {
81
+ return !built && /no build output/.test(d) ? 'no-build' : 'no-result';
82
+ }
83
+ const status = /did not complete \(([a-z-]+)\)/.exec(d)?.[1];
84
+ if (status) {
85
+ return {
86
+ 'deps-missing': 'deps-missing',
87
+ 'browser-unavailable': 'browser-missing',
88
+ 'no-build': 'no-build',
89
+ }[status] ?? 'incomplete';
90
+ }
91
+ if (/no built HTML found|no build output/.test(d)) return 'no-build';
92
+ if (/has not been run|ha(s|ve) not been measured/.test(d)) return 'not-run';
93
+ if (/predate the current build/.test(d)) return 'stale';
94
+ if (/re-run `sws (a11y|perf)`/.test(d)) return 'incomplete';
95
+ if (/no manifest to read/.test(d)) return 'no-manifest';
96
+ if (/but not installed; run install first/.test(d)) return 'not-installed';
97
+ if (/not a git repository/.test(d)) return 'no-git';
98
+ return 'other';
99
+ }
100
+
101
+ // What each code means, for a reader of this file. The codes are the output:
102
+ //
103
+ // no-build no build output, so page checks could not run
104
+ // not-run the browser measurement (`sws a11y`, `sws perf`) has not been run
105
+ // stale browser results predate the current build
106
+ // incomplete browser results did not complete or do not cover every page
107
+ // deps-missing browser tooling is not installed in this project
108
+ // browser-missing the browser could not launch
109
+ // not-installed a dependency is declared but not installed
110
+ // no-manifest no .sws/manifest.yml to read
111
+ // no-git not a git repository, so tracked files cannot be listed
112
+ // unimplemented no check exists yet, so the points are withheld
113
+ // no-result no check produced a result
114
+ // crashed a check threw; `detail` carries the message
115
+ // other none of the above; `detail` carries the check's own words
116
+ const NEEDS_DETAIL = new Set(['crashed', 'other']);
117
+
118
+ // Reasons a browser run would clear. `sws a11y` and `sws perf` are the only
119
+ // commands that produce these results, and the id says which one.
120
+ const BROWSER_REASONS = new Set(['no-build', 'not-run', 'stale', 'incomplete', 'deps-missing', 'browser-missing']);
121
+ const browserRun = (id) => (id.startsWith('perf.') ? 'perf' : id.startsWith('a11y.') ? 'a11y' : null);
122
+
123
+ // --- the standards file to read for a criterion ------------------------------
124
+ //
125
+ // Most specific first: a `contract:` the criterion names, then the file its
126
+ // check is written against, then its policy chapter. Relative to the standards
127
+ // directory. null when nothing can be derived, which is better than pointing
128
+ // at a file that does not answer the finding.
129
+ const CHECK_DOC = {
130
+ decanter: 'patterns/decanter.md',
131
+ seo: 'patterns/discoverability.md',
132
+ security: 'hosting/capabilities.yml',
133
+ perf: 'stack/performance-budget.yml',
134
+ };
135
+ const POLICY_DOC = {
136
+ brand: 'policy/brand.md',
137
+ accessibility: 'policy/accessibility.md',
138
+ minweb: 'policy/minweb.md',
139
+ minsec: 'policy/minsec.md',
140
+ minpriv: 'policy/privacy.md',
141
+ };
142
+
143
+ export function standardFor(criterion = {}) {
144
+ if (typeof criterion.contract === 'string' && criterion.contract.trim()) {
145
+ return criterion.contract.trim().replace(/^\.?\/?standards\//, '');
146
+ }
147
+ return CHECK_DOC[criterion.check] ?? POLICY_DOC[criterion.policy] ?? null;
148
+ }
149
+
150
+ // --- helpers -----------------------------------------------------------------
151
+
152
+ const clip = (s, n) => {
153
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
154
+ return t.length <= n ? t : `${t.slice(0, Math.max(0, n - 1)).trimEnd()}…`;
155
+ };
156
+
157
+ const PM = {
158
+ npm: { install: 'npm install', build: 'npm run build', addDev: 'npm install -D' },
159
+ yarn: { install: 'yarn install', build: 'yarn build', addDev: 'yarn add -D' },
160
+ pnpm: { install: 'pnpm install', build: 'pnpm run build', addDev: 'pnpm add -D' },
161
+ };
162
+
163
+ const day = (d) => (d instanceof Date ? d.toISOString().slice(0, 10) : String(d));
164
+
165
+ // Detail levels, most generous first. The last one is counts and three short
166
+ // actions, which fits whatever the project's paths and ids look like.
167
+ const LEVELS = [
168
+ { top: 3, title: 120, fix: 140, ids: 8, reasonIds: 2, next: 12, why: 120, fixes: 1 },
169
+ { top: 3, title: 100, fix: 110, ids: 4, reasonIds: 1, next: 10, why: 110, fixes: 1 },
170
+ { top: 3, title: 80, fix: 80, ids: 0, reasonIds: 0, next: 8, why: 90, fixes: 1 },
171
+ { top: 2, title: 60, fix: 0, ids: 0, reasonIds: 0, next: 7, why: 70, fixes: 0 },
172
+ { top: 1, title: 50, fix: 0, ids: 0, reasonIds: 0, next: 6, why: 60, fixes: 0 },
173
+ { top: 0, title: 40, fix: 0, ids: 0, reasonIds: 0, next: 3, why: 40, fixes: 0 },
174
+ ];
175
+
176
+ // --- the document ------------------------------------------------------------
177
+
178
+ function assemble({ command, recipe, sc, counts, findings, blocking, criteria, facts }, lv) {
179
+ const crit = (id) => criteria?.get(id) ?? {};
180
+ const pm = PM[facts.packageManager] ?? PM.npm;
181
+ const dropped = { failing: 0, manual: 0, overdue: 0, next: 0 };
182
+
183
+ // Failing: the blocking finding first, then by weight, then by id so two runs
184
+ // on the same tree list the same things.
185
+ const fails = findings.filter((f) => f.state === 'fail')
186
+ .sort((a, b) => Number(b.blocking) - Number(a.blocking) || b.weight - a.weight || a.id.localeCompare(b.id));
187
+ const top = fails.slice(0, lv.top).map((f) => {
188
+ const rel = standardFor(crit(f.id));
189
+ const read = rel ? facts.standardPath(rel) : null;
190
+ return {
191
+ id: f.id,
192
+ title: clip(f.detail, lv.title),
193
+ weight: f.weight,
194
+ ...(f.blocking ? { blocking: true } : {}),
195
+ ...(f.policy ? { policy: f.policy } : {}),
196
+ ...(f.fix && lv.fix ? { fix: clip(f.fix, lv.fix) } : {}),
197
+ ...(read ? { read } : {}),
198
+ ...(f.locations?.length
199
+ ? { locations: f.locations.slice(0, 3).map((l) => `${l.path}${l.line ? `:${l.line}` : ''}`) }
200
+ : {}),
201
+ };
202
+ });
203
+ dropped.failing = fails.length - top.length;
204
+
205
+ // Unknown: manual items apart, the rest grouped by reason.
206
+ const unknowns = findings.filter((f) => f.state === 'unknown')
207
+ .map((f) => ({ f, reason: unknownReason(f, crit(f.id), { built: facts.builtPages > 0 }) }));
208
+ const manual = unknowns.filter((u) => u.reason === 'manual').map((u) => u.f.id);
209
+ const actionable = unknowns.filter((u) => u.reason !== 'manual');
210
+ const byReason = new Map();
211
+ for (const u of actionable) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.f]);
212
+ const reasons = [...byReason.entries()]
213
+ .sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
214
+ .map(([reason, fs]) => ({
215
+ reason,
216
+ count: fs.length,
217
+ ...(lv.reasonIds ? { ids: fs.slice(0, lv.reasonIds).map((f) => f.id) } : {}),
218
+ ...(NEEDS_DETAIL.has(reason) ? { detail: clip(fs[0].detail, lv.title) } : {}),
219
+ }));
220
+ dropped.manual = manual.length - Math.min(manual.length, lv.ids);
221
+
222
+ // Accepted risks past their review date, from the file rather than from the
223
+ // findings: an entry whose check passes today is still due a look.
224
+ const entries = facts.ackEntries ?? [];
225
+ const overdueAll = entries.filter((a) => isOverdue(a, facts.now))
226
+ .sort((a, b) => day(a.review_by).localeCompare(day(b.review_by)));
227
+ const overdue = overdueAll.slice(0, Math.max(1, lv.ids)).map((a) => ({
228
+ check: String(a.check ?? 'unknown'),
229
+ review_by: day(a.review_by),
230
+ ...(a.path ? { path: String(a.path) } : {}),
231
+ }));
232
+ dropped.overdue = overdueAll.length - overdue.length;
233
+
234
+ const incomplete = facts.manifestPresent ? manifestIncomplete(facts.manifest) : [];
235
+ const skew = Boolean(facts.projectVersion && facts.tool && facts.projectVersion !== facts.tool);
236
+
237
+ // --- next, in the order to do it ------------------------------------------
238
+ const next = [];
239
+ // The recipe is the contract every criterion comes from, so it is where to
240
+ // look when nothing more specific can be named.
241
+ const recipeDoc = facts.standardPath(`recipes/${recipe}/RECIPE.md`);
242
+ const has = (reason, run) => actionable.some((u) => u.reason === reason && (!run || browserRun(u.f.id) === run));
243
+ const wants = (run) => actionable.some((u) => BROWSER_REASONS.has(u.reason) && browserRun(u.f.id) === run);
244
+
245
+ for (const b of blocking) {
246
+ const loc = b.locations?.[0];
247
+ next.push({
248
+ kind: 'rotate-credential', id: b.id,
249
+ path: loc ? `${loc.path}${loc.line ? `:${loc.line}` : ''}` : '.',
250
+ why: 'The one finding that fails CI. Rotate the credential, then remove it. Never accept a real one as a risk.',
251
+ });
252
+ }
253
+ if (!facts.manifestPresent) {
254
+ next.push({
255
+ kind: 'create-manifest', command: `npx ${PACKAGE} add .`,
256
+ why: `No ${MANIFEST_PATH}, so owners, hosting and divergences cannot be checked.`,
257
+ });
258
+ }
259
+ if (incomplete.length) {
260
+ next.push({
261
+ kind: 'complete-manifest', path: MANIFEST_PATH, fields: incomplete,
262
+ why: 'Placeholders, not answers. Ask the user; never invent an owner name or email.',
263
+ });
264
+ }
265
+ if (has('not-installed')) {
266
+ next.push({
267
+ kind: 'install-dependencies', command: pm.install,
268
+ why: 'Dependencies are declared but not installed, so their checks could not run.',
269
+ });
270
+ }
271
+ if (has('no-build')) {
272
+ const n = byReason.get('no-build').length;
273
+ next.push(facts.buildScript
274
+ ? { kind: 'build', command: pm.build, why: `No build output, so ${n} check(s) could not run.` }
275
+ : {
276
+ kind: 'build', ...(recipeDoc ? { path: recipeDoc } : { command: pm.build }),
277
+ why: `No build output and no build script, so ${n} check(s) could not run. The recipe says what to build.`,
278
+ });
279
+ }
280
+
281
+ const runs = ['a11y', 'perf'].filter(wants);
282
+ if (runs.length && !facts.localCli) {
283
+ next.push(facts.declaresPackage
284
+ ? {
285
+ kind: 'install-dependencies', command: pm.install,
286
+ why: `${PACKAGE} is declared but not installed, and the sws commands below need it.`,
287
+ }
288
+ : {
289
+ kind: 'add-dependency', command: `${pm.addDev} ${PACKAGE}`,
290
+ why: '`npx sws` must resolve to this package; unscoped `sws` on the public registry is unrelated.',
291
+ });
292
+ }
293
+ const tooling = runs.filter((r) => has('deps-missing', r) || has('browser-missing', r));
294
+ if (tooling.length) {
295
+ const packages = ['@playwright/test', ...(tooling.includes('a11y') ? ['@axe-core/playwright'] : [])];
296
+ const install = tooling.some((r) => has('deps-missing', r)) ? `${pm.addDev} ${packages.join(' ')} && ` : '';
297
+ next.push({
298
+ kind: 'install-browser-tooling', command: `${install}npx playwright install chromium`,
299
+ why: 'The last browser run could not start. It needs Playwright and Chromium in this project.',
300
+ });
301
+ }
302
+ if (runs.includes('a11y')) {
303
+ next.push({
304
+ kind: 'run-a11y', command: `${SWS} a11y`,
305
+ why: 'axe and the hover and focus audit have no current results. Slow: a real browser visits every page.',
306
+ });
307
+ }
308
+ if (runs.includes('perf')) {
309
+ next.push({
310
+ kind: 'run-perf', command: `${SWS} perf`,
311
+ why: 'The performance budget has no current measurement.',
312
+ });
313
+ }
314
+ // A failure an earlier step already answers is not listed a second time.
315
+ const answered = new Set([
316
+ ...(!facts.manifestPresent ? ['manifest.present'] : []),
317
+ ...(incomplete.some((x) => x.endsWith('.email')) ? ['minweb.ownership'] : []),
318
+ ]);
319
+ // The path is the standards file for the finding, or the recipe when the
320
+ // criterion names none.
321
+ for (const f of top.filter((t) => !t.blocking && !answered.has(t.id)).slice(0, lv.fixes)) {
322
+ const path = f.read ?? recipeDoc;
323
+ next.push({ kind: 'fix', id: f.id, ...(path ? { path } : { command: `${SWS} doctor --no-history` }), why: f.title });
324
+ }
325
+ if (overdueAll.length) {
326
+ next.push({
327
+ kind: 'review-acknowledgement', path: ACKNOWLEDGED_PATH.split('\\').join('/'),
328
+ why: `${overdueAll.length} accepted risk(s) past review. Ask whoever accepted them; do not move the date yourself.`,
329
+ });
330
+ }
331
+ if (skew) {
332
+ next.push({
333
+ kind: 'update-standards', command: `npx ${PACKAGE} add .`,
334
+ why: `Standards in this project are v${facts.projectVersion}; this tool carries v${facts.tool}.`,
335
+ });
336
+ }
337
+ const acted = next.length > 0;
338
+ if (manual.length) {
339
+ next.push({
340
+ kind: 'confirm-manual', command: `${SWS} doctor --no-history`,
341
+ why: `${manual.length} item(s) only a person can confirm. A passing run is a floor, not a conformance claim.`,
342
+ });
343
+ }
344
+ if (acted) {
345
+ next.push({
346
+ kind: 'verify', command: `${SWS} doctor --format brief --no-history`,
347
+ why: 'Run again after each change. Always exits 0.',
348
+ });
349
+ }
350
+
351
+ // Trim to the level. `verify` survives the cut: it is the step that closes
352
+ // the loop, and it is always last.
353
+ let shown = next;
354
+ if (next.length > lv.next) {
355
+ const last = next[next.length - 1];
356
+ shown = last.kind === 'verify' ? [...next.slice(0, lv.next - 1), last] : next.slice(0, lv.next);
357
+ }
358
+ dropped.next = next.length - shown.length;
359
+
360
+ return {
361
+ schema: BRIEF_SCHEMA,
362
+ command,
363
+ recipe,
364
+ standards: facts.standards,
365
+ versions: { tool: facts.tool ?? null, project: facts.projectVersion ?? null },
366
+ score: sc,
367
+ counts,
368
+ blocking: blocking.map((b) => b.id),
369
+ failing: { count: fails.length, top },
370
+ unknown: { count: unknowns.length, manual: manual.length, actionable: actionable.length, reasons },
371
+ manual: { count: manual.length, ids: manual.slice(0, lv.ids) },
372
+ manifest: { present: Boolean(facts.manifestPresent), incomplete },
373
+ acknowledgements: { entries: entries.length, overdue },
374
+ next: shown.map((n) => ({ ...n, why: clip(n.why, lv.why) })),
375
+ dropped,
376
+ };
377
+ }
378
+
379
+ /**
380
+ * The brief document as text: one line of JSON, at most BRIEF_CEILING bytes.
381
+ *
382
+ * `input` is the payload the other renderers take, plus `counts` (by state,
383
+ * the same object the JSON format prints), `criteria` (a Map of criterion by
384
+ * id) and `facts` about the project that are not findings.
385
+ */
386
+ export function briefText(input) {
387
+ let text = '';
388
+ for (const lv of LEVELS) {
389
+ text = JSON.stringify(assemble(input, lv));
390
+ if (Buffer.byteLength(text, 'utf8') <= BRIEF_CEILING) return text;
391
+ }
392
+ return text;
393
+ }
@@ -53,7 +53,7 @@ function probe(cmd) {
53
53
  }
54
54
  }
55
55
 
56
- function whichPackageManager(root) {
56
+ export function whichPackageManager(root) {
57
57
  if (existsSync(join(root, 'yarn.lock'))) return 'yarn';
58
58
  if (existsSync(join(root, 'pnpm-lock.yaml'))) return 'pnpm';
59
59
  return 'npm';