@sssb/tools 0.0.0 → 0.3.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +116 -0
  3. package/package.json +89 -5
  4. package/src/app-port.js +77 -0
  5. package/src/app.js +142 -0
  6. package/src/assembly-checks.d.ts +57 -0
  7. package/src/assembly-checks.js +259 -0
  8. package/src/commands/add-app.js +344 -0
  9. package/src/commands/check-demo-size.js +80 -0
  10. package/src/commands/check-doc-paths.js +48 -0
  11. package/src/commands/check-e2e.js +611 -0
  12. package/src/commands/check-fences.js +51 -0
  13. package/src/commands/check-real-env.js +165 -0
  14. package/src/commands/check-tmpdir-leak.js +78 -0
  15. package/src/commands/ci.js +350 -0
  16. package/src/commands/dev-tick.js +25 -0
  17. package/src/commands/doctor-checks.js +1396 -0
  18. package/src/commands/doctor-settings.js +583 -0
  19. package/src/commands/doctor-vitest.js +262 -0
  20. package/src/commands/doctor.js +1033 -0
  21. package/src/commands/e2e-profile.js +94 -0
  22. package/src/commands/guide.js +108 -0
  23. package/src/commands/launch-json.js +55 -0
  24. package/src/commands/pin.js +411 -0
  25. package/src/commands/port.js +22 -0
  26. package/src/commands/remove-items.js +191 -0
  27. package/src/commands/serve-standalone.js +78 -0
  28. package/src/commands/tick.js +27 -0
  29. package/src/doc-paths.d.ts +106 -0
  30. package/src/doc-paths.js +328 -0
  31. package/src/framework-guard.js +35 -0
  32. package/src/kit.d.ts +49 -0
  33. package/src/kit.js +216 -0
  34. package/src/next.d.ts +16 -0
  35. package/src/next.js +55 -0
  36. package/src/ports.d.ts +72 -0
  37. package/src/ports.js +307 -0
  38. package/src/prune-mantine-css.js +171 -0
  39. package/src/remove-items/code.patch +798 -0
  40. package/src/remove-items/database.patch +218 -0
  41. package/src/remove-items/exact-patch.js +122 -0
  42. package/src/testing/tmp-dir-marker.js +9 -0
  43. package/src/testing/tmp-dir-setup.d.ts +2 -0
  44. package/src/testing/tmp-dir-setup.js +9 -0
  45. package/src/testing/tmp-dir.d.ts +20 -0
  46. package/src/testing/tmp-dir.js +174 -0
  47. package/src/tick/dev-tick.js +128 -0
  48. package/src/tick/tick.js +317 -0
  49. package/src/tick/ticker-marker.d.ts +17 -0
  50. package/src/tick/ticker-marker.js +83 -0
  51. package/src/tick/ticker.d.ts +36 -0
  52. package/src/tick/ticker.js +142 -0
  53. package/src/vite.d.ts +38 -0
  54. package/src/vite.js +64 -0
  55. package/src/vitest.d.ts +38 -0
  56. package/src/vitest.js +82 -0
  57. package/tsconfig.base.json +33 -0
  58. package/README.md +0 -3
@@ -0,0 +1,1396 @@
1
+ // @ts-check
2
+ // The checks behind `sssb doctor` (ADR-0014 part 5), apart from the command that runs and prints them, so a test can
3
+ // drive each one over a workspace built on disk or a `vitest list` sample. Each returns its problems as sentences that
4
+ // name what is wrong; empty means the check holds. Nothing here loads the framework: what it needs of `@sssb/kit` (its
5
+ // peers, its check registry, its cutover rows) is read as data from the copy the APP resolves (rule 4, ../kit.js).
6
+ import { existsSync, globSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
7
+ import path from 'node:path'
8
+ import { readJson, UsageError, workspaceApps } from '../app.js'
9
+ import { portForRoot, readPortDeclaration } from '../ports.js'
10
+
11
+ const KIT = '@sssb/kit'
12
+ const SEAM = '@sssb/app-config'
13
+
14
+ /** The dependency fields that give a package its own copy of a package (a seam declared as a peer is not its own). */
15
+ const DEPENDENCY_FIELDS = /** @type {const} */ (['dependencies', 'devDependencies', 'optionalDependencies'])
16
+
17
+ /** The fields that make a package an importer of @sssb/kit: any of them puts an instance on its lookup chain. */
18
+ const IMPORTER_FIELDS = /** @type {const} */ ([...DEPENDENCY_FIELDS, 'peerDependencies'])
19
+
20
+ /**
21
+ * The directory of package `name` as Node's lookup finds it from `start`: the first `node_modules/<name>` walking up,
22
+ * real path. Never NODE_PATH or the global folders (see kitDirOf in ../kit.js for why). Null when there is none.
23
+ * @param {string} start
24
+ * @param {string} name
25
+ * @returns {string | null}
26
+ */
27
+ export function packageDirFrom(start, name) {
28
+ for (let dir = path.resolve(start); ; dir = path.dirname(dir)) {
29
+ const candidate = path.join(dir, 'node_modules', ...name.split('/'))
30
+ if (existsSync(candidate)) return realpathSync(candidate)
31
+ if (path.dirname(dir) === dir) return null
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The two settings doctor reads from `pnpm-workspace.yaml`: its `packages` globs and `dedupePeerDependents`. A
37
+ * deliberately small reader, so @sssb/tools takes no YAML dependency. It reads the subset a pnpm-workspace.yaml uses,
38
+ * and THROWS, naming the line, on anything else, because a list it misread as empty would make every workspace-wide
39
+ * check pass over nothing:
40
+ *
41
+ * - top-level `key:` entries, plain or quoted keys; the value of any key but these two is skipped (its indented
42
+ * lines, and `- ` items at column 0, which YAML lets a block sequence use under a top-level key);
43
+ * - `packages` as a block sequence at any one indentation, column 0 included, of plain or quoted scalars, or as a
44
+ * flow sequence (`[a, 'b']`) on one line or over several (at any column, as YAML allows); comments and blank lines
45
+ * anywhere;
46
+ * - `dedupePeerDependents` as an unquoted true or false, on the key's line or alone on the indented line below it
47
+ * (anything else, a quoted 'false' too, is not the boolean);
48
+ * - a flow collection (any key's) opens only where a value starts with `[` or `{`; a bracket inside a plain scalar
49
+ * (`nodeOptions: --foo[bar`) is text.
50
+ *
51
+ * What it throws on, among others: in the two values it reads, anchors, aliases and tags (an unquoted `!glob` is a
52
+ * tag, an unquoted `*glob` an alias), nested or multi-line items and a scalar where the list belongs; anywhere at the
53
+ * top level, a duplicate key, a top-level flow mapping, a flow collection of any key still open at the end of the
54
+ * file, and a second document. Another key's value is skipped unread (an anchor there passes), but for its flow
55
+ * brackets.
56
+ * @param {string} text
57
+ * @returns {{ packages: string[], dedupePeerDependents: boolean | undefined }}
58
+ */
59
+ export function parseWorkspaceYaml(text) {
60
+ /**
61
+ * @param {number} line
62
+ * @param {string} what
63
+ * @returns {never}
64
+ */
65
+ const fail = (line, what) => {
66
+ throw new UsageError(
67
+ `sssb: pnpm-workspace.yaml line ${line}: ${what}, which sssb's reader of the file does not understand ` +
68
+ '(it reads a small subset of YAML: see parseWorkspaceYaml in @sssb/tools)',
69
+ )
70
+ }
71
+ /** @typedef {{ line: number, text: string }} Line */
72
+ /** @typedef {{ line: number, value: string, body: Line[], depth: number }} Entry depth: flow brackets still open */
73
+ /** @type {Map<string, Entry>} */
74
+ const entries = new Map()
75
+ /** @type {Entry | null} */
76
+ let current = null
77
+ let ended = false
78
+ const lines = text.replace(/^\uFEFF/, '').split(/\r?\n/)
79
+ for (let i = 0; i < lines.length; i++) {
80
+ const line = lines[i] ?? ''
81
+ const n = i + 1
82
+ if (/^\s*(#.*)?$/.test(line)) continue
83
+ // Inside an open flow collection (`key: [` ...), every line continues it, at column 0 too.
84
+ if (current !== null && current.depth > 0) {
85
+ current.body.push({ line: n, text: line })
86
+ current.depth += flowDepth(line)
87
+ continue
88
+ }
89
+ if (ended) fail(n, 'content after the end of the document (`...`)')
90
+ if (/^---[ \t]*(#.*)?$/.test(line)) {
91
+ if (entries.size > 0) fail(n, 'a second YAML document')
92
+ continue
93
+ }
94
+ if (/^\.\.\.[ \t]*(#.*)?$/.test(line)) {
95
+ ended = true
96
+ continue
97
+ }
98
+ if (/^[ \t]/.test(line) || /^-([ \t]|$)/.test(line)) {
99
+ if (current === null) fail(n, 'an indented line or list item before any key')
100
+ current.body.push({ line: n, text: line })
101
+ continue
102
+ }
103
+ const key = /^(?:([A-Za-z_][\w.-]*)|'((?:[^']|'')*)'|"((?:[^"\\]|\\.)*)")[ \t]*:(?:[ \t]+(.*))?$/.exec(line)
104
+ if (!key) fail(n, `\`${line.trim()}\``)
105
+ const name =
106
+ key[1] ?? (key[2] === undefined ? unescapeDouble(key[3] ?? '', n, fail) : key[2].replaceAll("''", "'"))
107
+ if (entries.has(name)) fail(n, `a second \`${name}\` key`)
108
+ // A flow collection opens only where the value STARTS with `[` or `{`; in a plain scalar (`--foo[bar`) a
109
+ // bracket is text.
110
+ const value = key[4] ?? ''
111
+ current = { line: n, value, body: [], depth: /^[[{]/.test(value) ? flowDepth(value) : 0 }
112
+ entries.set(name, current)
113
+ }
114
+ if (current !== null && current.depth > 0)
115
+ fail(current.line, 'a flow collection (`[` or `{`) never closed before the end of the file')
116
+
117
+ /** @param {string} raw @param {number} line @param {boolean} inFlow */
118
+ const scalar = (raw, line, inFlow) => {
119
+ if (raw.startsWith("'")) {
120
+ const quoted = /^'((?:[^']|'')*)'$/.exec(raw)
121
+ if (!quoted) fail(line, `\`${raw}\``)
122
+ return (quoted[1] ?? '').replaceAll("''", "'")
123
+ }
124
+ if (raw.startsWith('"')) {
125
+ const quoted = /^"((?:[^"\\]|\\.)*)"$/.exec(raw)
126
+ if (!quoted) fail(line, `\`${raw}\``)
127
+ return unescapeDouble(quoted[1] ?? '', line, fail)
128
+ }
129
+ if (/^[,[\]{}#&*!|>%@`]/.test(raw) || /^[-?:]([ \t]|$)/.test(raw))
130
+ fail(line, `\`${raw}\` (an anchor, alias, tag, nested collection or block scalar)`)
131
+ if (/:([ \t]|$)/.test(raw) || (inFlow && /[,[\]{}]/.test(raw))) fail(line, `\`${raw}\``)
132
+ if (/^(~|null|Null|NULL)$/.test(raw)) fail(line, `\`${raw}\` (a null where a glob belongs)`)
133
+ return raw
134
+ }
135
+
136
+ /** @type {string[]} */
137
+ let packages = []
138
+ const listed = entries.get('packages')
139
+ if (listed) {
140
+ const value = stripComment(listed.value, listed.line, fail)
141
+ if (value === '') packages = blockSequence(listed.body, scalar, fail)
142
+ else if (value.startsWith('['))
143
+ packages = flowSequence(
144
+ [
145
+ { line: listed.line, text: value },
146
+ ...listed.body.map((b) => ({ line: b.line, text: stripComment(b.text, b.line, fail) })),
147
+ ],
148
+ scalar,
149
+ fail,
150
+ )
151
+ else fail(listed.line, `\`packages: ${value}\` (a list belongs there)`)
152
+ }
153
+
154
+ // The value on the key's line, or alone on the one indented line below it (`dedupePeerDependents:\n false`); more
155
+ // lines make a multi-line scalar, which is no boolean.
156
+ const dedupe = entries.get('dedupePeerDependents')
157
+ const inline = dedupe ? stripComment(dedupe.value, dedupe.line, fail) : ''
158
+ const below = dedupe?.body.length === 1 && inline === '' ? dedupe.body[0] : undefined
159
+ const flag =
160
+ dedupe && dedupe.body.length === 0
161
+ ? inline
162
+ : below && !/^\s*-([ \t]|$)/.test(below.text)
163
+ ? stripComment(below.text, below.line, fail)
164
+ : ''
165
+ const dedupePeerDependents = /^(true|True|TRUE)$/.test(flag)
166
+ ? true
167
+ : /^(false|False|FALSE)$/.test(flag)
168
+ ? false
169
+ : undefined
170
+ return { packages, dedupePeerDependents }
171
+ }
172
+
173
+ /**
174
+ * How many flow brackets (`[`, `{`) a line opens and leaves open, its quoted text and comment aside. Never throws: it
175
+ * only decides which lines a flow value spans, and the value's own reader judges them.
176
+ * @param {string} text
177
+ */
178
+ function flowDepth(text) {
179
+ let depth = 0
180
+ /** @type {string | null} */
181
+ let quote = null
182
+ for (let i = 0; i < text.length; i++) {
183
+ const c = text[i]
184
+ if (quote !== null) {
185
+ if (quote === '"' && c === '\\') i++
186
+ else if (c === quote) quote = null
187
+ } else if (c === "'" || c === '"') quote = c
188
+ else if (c === '#' && (i === 0 || /\s/.test(text[i - 1] ?? ''))) break
189
+ else if (c === '[' || c === '{') depth++
190
+ else if (c === ']' || c === '}') depth--
191
+ }
192
+ return depth
193
+ }
194
+
195
+ /** @typedef {(line: number, what: string) => never} Fail */
196
+ /** @typedef {(raw: string, line: number, inFlow: boolean) => string} Scalar */
197
+
198
+ /**
199
+ * A line with its comment (a `#` at its start or after white space, outside quotes) cut off, trimmed.
200
+ * @param {string} text
201
+ * @param {number} line
202
+ * @param {Fail} fail
203
+ */
204
+ function stripComment(text, line, fail) {
205
+ /** @type {string | null} */
206
+ let quote = null
207
+ for (let i = 0; i < text.length; i++) {
208
+ const c = text[i]
209
+ if (quote === "'") {
210
+ if (c === "'") {
211
+ if (text[i + 1] === "'") i++
212
+ else quote = null
213
+ }
214
+ } else if (quote === '"') {
215
+ if (c === '\\') i++
216
+ else if (c === '"') quote = null
217
+ } else if (c === "'" || c === '"') quote = c
218
+ else if (c === '#' && (i === 0 || /\s/.test(text[i - 1] ?? ''))) return text.slice(0, i).trim()
219
+ }
220
+ if (quote !== null) fail(line, 'a quoted string that does not close on its line')
221
+ return text.trim()
222
+ }
223
+
224
+ /**
225
+ * A double-quoted scalar's text, with the escapes a glob needs (`\\`, `\"`, `\/`); any other escape throws.
226
+ * @param {string} text
227
+ * @param {number} line
228
+ * @param {Fail} fail
229
+ */
230
+ function unescapeDouble(text, line, fail) {
231
+ return text.replace(/\\(.)/g, (_, c) =>
232
+ c === '\\' || c === '"' || c === '/' ? c : fail(line, `the escape \\${c}`),
233
+ )
234
+ }
235
+
236
+ /**
237
+ * A block sequence's items: every line `- <scalar>`, all at one indentation.
238
+ * @param {{ line: number, text: string }[]} body
239
+ * @param {Scalar} scalar
240
+ * @param {Fail} fail
241
+ */
242
+ function blockSequence(body, scalar, fail) {
243
+ /** @type {number | null} */
244
+ let indent = null
245
+ /** @type {string[]} */
246
+ const items = []
247
+ for (const { line, text } of body) {
248
+ const item = /^( *)-(?:[ \t]+(.*))?$/.exec(text)
249
+ if (!item) fail(line, `\`${text.trim()}\` inside the packages list`)
250
+ const at = (item[1] ?? '').length
251
+ if (indent === null) indent = at
252
+ else if (at !== indent) fail(line, 'a list item at another indentation than the first')
253
+ const value = stripComment(item[2] ?? '', line, fail)
254
+ if (value === '') fail(line, 'an empty or nested list item')
255
+ items.push(scalar(value, line, false))
256
+ }
257
+ return items
258
+ }
259
+
260
+ /**
261
+ * A flow sequence's items, from its lines (comments already cut): `[` item `,` ... `]`, a trailing comma allowed.
262
+ * @param {{ line: number, text: string }[]} parts
263
+ * @param {Scalar} scalar
264
+ * @param {Fail} fail
265
+ */
266
+ function flowSequence(parts, scalar, fail) {
267
+ /** @type {{ text: string, line: number }[]} */
268
+ const items = []
269
+ let item = ''
270
+ let itemLine = parts[0]?.line ?? 1
271
+ /** @type {string | null} */
272
+ let quote = null
273
+ let closed = false
274
+ for (const [index, { line, text }] of parts.entries()) {
275
+ for (let i = index === 0 ? 1 : 0; i < text.length; i++) {
276
+ const c = text[i] ?? ''
277
+ if (closed) fail(line, `\`${text.slice(i).trim()}\` after the list's closing \`]\``)
278
+ if (quote !== null) {
279
+ item += c
280
+ if (quote === '"' && c === '\\') item += text[++i] ?? ''
281
+ else if (c === quote) {
282
+ if (quote === "'" && text[i + 1] === "'") item += text[++i]
283
+ else quote = null
284
+ }
285
+ } else if (c === "'" || c === '"') {
286
+ quote = c
287
+ item += c
288
+ } else if (c === ',' || c === ']') {
289
+ items.push({ text: item.trim(), line: itemLine })
290
+ item = ''
291
+ itemLine = line
292
+ if (c === ']') closed = true
293
+ } else if (c === '[' || c === '{' || c === '}') fail(line, 'a nested collection in the packages list')
294
+ else {
295
+ if (item.trim() === '') itemLine = line
296
+ item += c
297
+ }
298
+ }
299
+ if (!closed) item += ' '
300
+ }
301
+ if (!closed) fail(parts.at(-1)?.line ?? 1, 'a flow sequence never closed with `]`')
302
+ // `[]` and a trailing comma leave one empty item last; an empty item anywhere else is a stray comma.
303
+ if (items.at(-1)?.text === '') items.pop()
304
+ return items.map(({ text, line }) => (text === '' ? fail(line, 'an empty list item') : scalar(text, line, true)))
305
+ }
306
+
307
+ /**
308
+ * Every package of the workspace at `root` (its `pnpm-workspace.yaml` globs, `!` negations applied), as absolute
309
+ * directories holding a package.json, sorted. The root itself is not in it. Throws when the file cannot be read.
310
+ * @param {string} root
311
+ * @returns {string[]}
312
+ */
313
+ export function workspacePackages(root) {
314
+ const { packages } = parseWorkspaceYaml(readFileSync(path.join(root, 'pnpm-workspace.yaml'), 'utf8'))
315
+ const include = packages.filter((glob) => !glob.startsWith('!'))
316
+ const exclude = packages.filter((glob) => glob.startsWith('!')).map((glob) => glob.slice(1))
317
+ const found = new Set()
318
+ // Trailing slashes trimmed by a loop: `/\/+$/` backtracks quadratically on a long run of slashes followed by
319
+ // anything else.
320
+ /** @param {string} glob */
321
+ const trimSlashes = (glob) => {
322
+ let end = glob.length
323
+ while (end > 0 && glob[end - 1] === '/') end--
324
+ return glob.slice(0, end)
325
+ }
326
+ for (const glob of include) {
327
+ for (const match of globSync(trimSlashes(glob), { cwd: root })) {
328
+ const rel = match.split(path.sep).join('/')
329
+ if (rel.split('/').includes('node_modules')) continue
330
+ if (exclude.some((negated) => path.matchesGlob(rel, trimSlashes(negated)))) continue
331
+ if (existsSync(path.join(root, match, 'package.json'))) found.add(path.join(root, match))
332
+ }
333
+ }
334
+ return [...found].sort()
335
+ }
336
+
337
+ /**
338
+ * IN-REPO MODE (ADR-0014 part 1): the `@sssb/kit` the app resolves is a package of this very workspace (SSSB's own
339
+ * repository, where `workspace:*` links the apps to packages/kit's source), not a copy installed from a tarball or a
340
+ * registry. Decided by where the kit really is, never by a setting: its real directory is one of the workspace's
341
+ * package directories. There the seam goes through each app's aliases rather than a link.
342
+ * @param {string} kitDir the real directory of the app's `@sssb/kit` (kitDirOf)
343
+ * @param {string} root the workspace root
344
+ * @param {readonly string[]} [packages] the workspace's packages, when already walked (workspacePackages)
345
+ */
346
+ export function isInRepoKit(kitDir, root, packages = workspacePackages(root)) {
347
+ return packages.some((dir) => realpathSync(dir) === kitDir)
348
+ }
349
+
350
+ /**
351
+ * WHAT DOCTOR WALKS: the workspace's packages, whether the app's kit is one of them (in-repo mode), every importer of
352
+ * @sssb/kit, and the APPS, each of which gets every per-app check: in-repo, the apps the workspace's commands fan out
353
+ * over (`sssb.apps`, or apps/*, as the alias check walks them); otherwise every importer with a seam of its own
354
+ * (`src/app-config`). All real paths. Throws, as workspacePackages does, when pnpm-workspace.yaml cannot be read.
355
+ * @param {string} root real path
356
+ * @param {string} kitDir the real directory of the @sssb/kit doctor's app resolves
357
+ */
358
+ export function discoverWorkspace(root, kitDir) {
359
+ const packages = workspacePackages(root)
360
+ const inRepo = isInRepoKit(kitDir, root, packages)
361
+ const importers = kitImporters(root, packages)
362
+ const apps = inRepo
363
+ ? workspaceApps(root).map((app) => realpathSync(path.join(root, app)))
364
+ : importers.map(({ dir }) => dir).filter((dir) => existsSync(path.join(dir, 'src', 'app-config')))
365
+ return { packages, inRepo, importers, apps }
366
+ }
367
+
368
+ /** @typedef {{ id: string, runner: string, title: string, tests: string[] }} RegisteredCheck */
369
+
370
+ /**
371
+ * Every test the conformance suite registers for one runner, as `vitest list` names it: `[sssb:<id>] <title> >
372
+ * <test>`, from the kit's `checks.json`.
373
+ * @param {{ checks: RegisteredCheck[] }} registry
374
+ * @param {'unit' | 'contract'} runner
375
+ * @returns {{ id: string, name: string }[]}
376
+ */
377
+ function expectedTests(registry, runner) {
378
+ return registry.checks
379
+ .filter((check) => check.runner === runner)
380
+ .flatMap((check) =>
381
+ check.tests.map((test) => ({ id: check.id, name: `[sssb:${check.id}] ${check.title} > ${test}` })),
382
+ )
383
+ }
384
+
385
+ /**
386
+ * The checks an app opted out of, with the reason each gives, as the suite records them in what Vitest lists: a test
387
+ * named `[sssb:opt-out:<id>] <reason>` (at the file's top level, or under a describe).
388
+ * @param {readonly string[]} listed every listed test's full name
389
+ * @returns {Map<string, string>} check id -> reason
390
+ */
391
+ function optedOut(listed) {
392
+ /** @type {Map<string, string>} */
393
+ const ids = new Map()
394
+ for (const name of listed) {
395
+ for (const segment of name.split(' > ')) {
396
+ const marker = /^\[sssb:opt-out:([^\]\s]+)\]\s*(.*)$/.exec(segment)
397
+ if (marker?.[1]) ids.set(marker[1], marker[2] ?? '')
398
+ }
399
+ }
400
+ return ids
401
+ }
402
+
403
+ /**
404
+ * The tests of one runner's checks that Vitest would NOT run: every expected test that is not in the listing, unless
405
+ * its check is opted out by a listed marker. A marker is honoured only for a check of this runner (the suite refuses
406
+ * any other while collecting, so a stray one changes nothing). The listing must already be the app's own suite files
407
+ * (ownTests): a name or a marker from any other file proves nothing.
408
+ * @param {readonly string[]} listed every listed test's full name
409
+ * @param {{ checks: RegisteredCheck[] }} registry
410
+ * @param {'unit' | 'contract'} runner
411
+ * @returns {{ missing: string[], optedOut: { id: string, reason: string }[], expected: number }}
412
+ */
413
+ export function missingTests(listed, registry, runner) {
414
+ const names = new Set(listed)
415
+ const out = optedOut(listed)
416
+ const expected = expectedTests(registry, runner)
417
+ const ids = [...new Set(expected.map((test) => test.id))]
418
+ return {
419
+ missing: expected.filter((test) => !out.has(test.id) && !names.has(test.name)).map((test) => test.name),
420
+ optedOut: ids.filter((id) => out.has(id)).map((id) => ({ id, reason: out.get(id) ?? '' })),
421
+ expected: expected.filter((test) => !out.has(test.id)).length,
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Which of an app's test areas a file is in: `unit` under the app's `src/`, `contract` under its `tests/contract/`,
427
+ * null anywhere else, and null inside a workspace package nested in the app's directory (a root-level app's apps/*),
428
+ * whose tests are that package's, not the app's.
429
+ * @param {string} file
430
+ * @param {string} appDir
431
+ * @param {readonly string[]} nested the workspace packages strictly inside `appDir`
432
+ * @returns {'unit' | 'contract' | null}
433
+ */
434
+ export function areaOf(file, appDir, nested) {
435
+ const abs = path.resolve(file)
436
+ if (nested.some((dir) => abs.startsWith(dir + path.sep))) return null
437
+ if (abs.startsWith(path.join(appDir, 'src') + path.sep)) return 'unit'
438
+ if (abs.startsWith(path.join(appDir, 'tests', 'contract') + path.sep)) return 'contract'
439
+ return null
440
+ }
441
+
442
+ /**
443
+ * The names, from a `vitest list` listing, that can prove an app runs a runner's checks or opts out of one: the unit
444
+ * checks come from the app's own `src/sssb.conformance.test.ts` alone, the contract checks from the files under its own
445
+ * `tests/contract/`. A check's name or opt-out marker in any other file (another app's, a nested package's, or an
446
+ * ordinary test that happens to use the name) counts for nothing.
447
+ * @param {readonly { name: string, file: string }[]} listed
448
+ * @param {string} appDir
449
+ * @param {'unit' | 'contract'} runner
450
+ * @param {readonly string[]} nested the workspace packages strictly inside `appDir`
451
+ */
452
+ export function ownTests(listed, appDir, runner, nested) {
453
+ const suite = path.join(appDir, 'src', 'sssb.conformance.test.ts')
454
+ return listed
455
+ .filter((test) =>
456
+ runner === 'unit'
457
+ ? path.resolve(test.file) === suite && areaOf(test.file, appDir, nested) === 'unit'
458
+ : areaOf(test.file, appDir, nested) === 'contract',
459
+ )
460
+ .map((test) => test.name)
461
+ }
462
+
463
+ /**
464
+ * ONE COPY OF EACH SINGLETON (ADR-0014 part 5): for every peer the framework declares, the real directory of the
465
+ * package found from the kit's directory must be the one found from the app's. Directories, not entry points, since
466
+ * `@types/react` has none. A peer the kit cannot find fails. An OPTIONAL peer that neither side finds is not
467
+ * installed, and passes as a note; one only the kit finds is not the app's to share (a note); one only the app finds
468
+ * is a split (fails), because the kit would load another copy, or none.
469
+ * @param {{ peers: readonly string[], optional: ReadonlySet<string>, fromKit: (name: string) => string | null, fromApp: (name: string) => string | null }} input
470
+ * @returns {{ problems: string[], notes: string[], same: string[] }}
471
+ */
472
+ export function singletonProblems({ peers, optional, fromKit, fromApp }) {
473
+ /** @type {string[]} */
474
+ const problems = []
475
+ /** @type {string[]} */
476
+ const notes = []
477
+ /** @type {string[]} */
478
+ const same = []
479
+ for (const name of peers) {
480
+ const kit = fromKit(name)
481
+ const app = fromApp(name)
482
+ const isOptional = optional.has(name)
483
+ if (kit === null && app === null && isOptional) notes.push(`${name}: an optional peer neither installs`)
484
+ else if (kit === null) problems.push(`${name}: @sssb/kit cannot find it${app ? ` (the app has ${app})` : ''}`)
485
+ else if (app === null && isOptional) notes.push(`${name}: an optional peer the app does not install`)
486
+ else if (app === null) problems.push(`${name}: the app cannot find it (@sssb/kit has ${kit})`)
487
+ else if (kit !== app) problems.push(`TWO COPIES ${name}: @sssb/kit loads ${kit}, the app ${app}`)
488
+ else same.push(name)
489
+ }
490
+ return { problems, notes, same }
491
+ }
492
+
493
+ /**
494
+ * The peers of the framework at `kitDir` that doctor holds to one copy: every `peerDependencies` entry (the seam is
495
+ * declared in `peerDependenciesMeta` alone, and is never one), and which of them are optional.
496
+ * @param {string} kitDir
497
+ */
498
+ export function kitPeers(kitDir) {
499
+ const manifest = readJson(path.join(kitDir, 'package.json'))
500
+ const peers = Object.keys(manifest.peerDependencies ?? {}).filter((name) => name !== SEAM)
501
+ const meta = manifest.peerDependenciesMeta ?? {}
502
+ return { peers, optional: new Set(peers.filter((name) => meta[name]?.optional === true)) }
503
+ }
504
+
505
+ /**
506
+ * @param {Record<string, unknown>} manifest
507
+ * @param {string} name
508
+ * @param {readonly string[]} [fields]
509
+ * @returns {string | undefined}
510
+ */
511
+ function declared(manifest, name, fields = DEPENDENCY_FIELDS) {
512
+ for (const field of fields) {
513
+ const deps = /** @type {Record<string, string> | undefined} */ (manifest[field])
514
+ if (deps && typeof deps[name] === 'string') return deps[name]
515
+ }
516
+ return undefined
517
+ }
518
+
519
+ /**
520
+ * The real directory of the seam `@sssb/kit` at `kitDir` loads: `@sssb/app-config` as Node's lookup finds it from the
521
+ * framework's own directory (pnpm links it beside the instance). Null when there is none.
522
+ * @param {string} kitDir
523
+ */
524
+ export const seamOfKit = (kitDir) => packageDirFrom(kitDir, SEAM)
525
+
526
+ /**
527
+ * THE INSTALLED LAYOUT: SSSB needs pnpm's default `nodeLinker`, `isolated`. Every check doctor makes reads the layout
528
+ * it builds (each importer's own `@sssb/kit` instance in the virtual store, with its seam linked beside it, found
529
+ * through `node_modules`), and so does the shared kit resolver. Under `hoisted` one instance serves every app, so no
530
+ * two apps can each have their own seam. Under `pnp` pnpm 11 still builds that `node_modules`, but writes a
531
+ * `.pnp.cjs` at the root, and while it is there `pnpm run` loads it into every script's `NODE_OPTIONS` (removing the
532
+ * setting and reinstalling leaves it behind): Plug'n'Play then resolves inside doctor itself, and Vitest's listing
533
+ * never finishes. The layout pnpm installed is in the root's `node_modules/.modules.yaml` (JSON, which is YAML),
534
+ * whatever setting asked for it. Null when the layout is isolated with no Plug'n'Play anywhere, or when nothing is
535
+ * installed (the kit resolver then says so).
536
+ * @param {string} root
537
+ * @param {Record<string, string | undefined>} [env] doctor's own environment
538
+ * @returns {string | null} the problem
539
+ */
540
+ export function nodeLinkerProblem(root, env = process.env) {
541
+ const fix =
542
+ "SSSB needs nodeLinker isolated, pnpm's default, which gives each app its own @sssb/kit linked to its own seam " +
543
+ "with no Plug'n'Play. Remove the nodeLinker setting from pnpm-workspace.yaml (and any " +
544
+ 'pnpm_config_node_linker variable or --config.node-linker flag), delete .pnp.cjs at the workspace root if it is ' +
545
+ 'there, then run pnpm install'
546
+ const file = path.join(root, 'node_modules', '.modules.yaml')
547
+ if (existsSync(file)) {
548
+ /** @type {string} */
549
+ let text
550
+ try {
551
+ text = readFileSync(file, 'utf8')
552
+ } catch (error) {
553
+ return `node_modules/.modules.yaml, where pnpm records the layout it installed, cannot be read (${/** @type {Error} */ (error).message}). ${fix}`
554
+ }
555
+ /** @type {unknown} */
556
+ let linker
557
+ try {
558
+ linker = JSON.parse(text)?.nodeLinker
559
+ } catch {
560
+ // Not JSON (a damaged file, or a pnpm that writes YAML): a `nodeLinker` key at the start of any line,
561
+ // indented or not, quoted or not.
562
+ linker = /^\s*["']?nodeLinker["']?\s*:\s*["']?([A-Za-z-]+)/m.exec(text)?.[1]
563
+ }
564
+ if (typeof linker === 'string' && linker !== 'isolated') {
565
+ return `pnpm installed this workspace with nodeLinker ${linker} (node_modules/.modules.yaml). ${fix}`
566
+ }
567
+ }
568
+ if (existsSync(path.join(root, '.pnp.cjs'))) {
569
+ return `.pnp.cjs at the workspace root makes pnpm run every script under Plug'n'Play, whatever layout it installed. ${fix}`
570
+ }
571
+ if (/\.pnp\.c?js\b/.test(env.NODE_OPTIONS ?? '')) {
572
+ return `doctor runs under Plug'n'Play (NODE_OPTIONS loads a .pnp.cjs: ${env.NODE_OPTIONS}). ${fix}`
573
+ }
574
+ return null
575
+ }
576
+
577
+ /**
578
+ * Every package of the workspace, the root included, that takes `@sssb/kit` in any dependency field (dependencies,
579
+ * devDependencies, optionalDependencies, peerDependencies), the framework itself aside. Real paths.
580
+ * @param {string} root
581
+ * @param {readonly string[]} [packages] the workspace's packages, when already walked (workspacePackages)
582
+ * @returns {{ dir: string, manifest: Record<string, unknown> }[]}
583
+ */
584
+ export function kitImporters(root, packages = workspacePackages(root)) {
585
+ return [root, ...packages]
586
+ .map((dir) => ({ dir: realpathSync(dir), manifest: readJson(path.join(dir, 'package.json')) }))
587
+ .filter(({ manifest }) => manifest.name !== KIT && declared(manifest, KIT, IMPORTER_FIELDS) !== undefined)
588
+ }
589
+
590
+ /**
591
+ * ONE SSSB PER IMPORTER, WITH ITS OWN SEAM (ADR-0014 part 5): every package of the workspace that depends on
592
+ * `@sssb/kit` (the root included) must declare its seam link, and the instance it resolves must have that very seam
593
+ * linked, a seam no other importer has. The link must be a workspace package (`workspace:<name>@*`), not a `link:`,
594
+ * which pnpm's next `add <pkg>`, `remove` or `update <pkg>` for the importer unlinks. A package that slips is by definition not an app, so the walk
595
+ * is the whole workspace, whatever package doctor runs from. `resolveKit` is the shared resolver's kitDirOf.
596
+ * @param {string} root
597
+ * @param {(dir: string) => string} resolveKit
598
+ * @param {{ dir: string, manifest: Record<string, unknown> }[]} [found] the importers, when already walked
599
+ * @param {readonly string[]} [packages] the workspace's packages, when already walked (workspacePackages)
600
+ * @returns {{ problems: string[], importers: string[] }}
601
+ */
602
+ export function importerSeamProblems(root, resolveKit, found = kitImporters(root), packages = workspacePackages(root)) {
603
+ /** @type {string[]} */
604
+ const problems = []
605
+ /** @type {string[]} */
606
+ const importers = []
607
+ const rel = (/** @type {string} */ dir) => path.relative(root, dir) || '(the workspace root)'
608
+ /**
609
+ * Each declared seam (real path) -> its package: the importer whose own `src/app-config` it is, else the first that
610
+ * declares it. By location first, so an app that declares another's seam is the one named, whatever the walk order.
611
+ * @type {Map<string, string>}
612
+ */
613
+ const seamOwners = new Map()
614
+ for (const { dir } of found) {
615
+ const home = path.join(dir, 'src', 'app-config')
616
+ if (existsSync(home)) seamOwners.set(realpathSync(home), rel(dir))
617
+ }
618
+ for (const { dir, manifest } of found) {
619
+ const own = ownSeam(dir, declared(manifest, SEAM))
620
+ if (own && !seamOwners.has(own)) seamOwners.set(own, rel(dir))
621
+ }
622
+ for (const { dir, manifest } of found) {
623
+ importers.push(rel(dir))
624
+ const link = declared(manifest, SEAM)
625
+ const own = ownSeam(dir, link)
626
+ const kitDir = resolvesKit(resolveKit, dir)
627
+ if (kitDir === null) {
628
+ problems.push(`${rel(dir)}: depends on @sssb/kit but resolves none (is it installed?)`)
629
+ continue
630
+ }
631
+ const seam = seamOfKit(kitDir)
632
+ const where = path.relative(root, kitDir)
633
+ const runsOn =
634
+ seam === null
635
+ ? 'no seam linked'
636
+ : `${seamOwners.has(seam) ? `${seamOwners.get(seam)}'s seam` : 'the seam'} ${path.relative(root, seam)} linked`
637
+ if (link === undefined) {
638
+ problems.push(
639
+ `${rel(dir)}: takes @sssb/kit but declares no seam link (${SEAM}); the instance it resolves (${where}) has ${runsOn}`,
640
+ )
641
+ } else if (own === null) {
642
+ problems.push(`${rel(dir)}: declares ${SEAM} as ${link}, which is no directory`)
643
+ } else if (seam !== own) {
644
+ problems.push(
645
+ `${rel(dir)}: its @sssb/kit (${where}) has ${runsOn}, not its own ${path.relative(root, own)}`,
646
+ )
647
+ } else if (seamOwners.get(own) !== rel(dir)) {
648
+ problems.push(
649
+ `${rel(dir)}: declares ${SEAM} as ${link}, which is ${seamOwners.get(own)}'s seam ${path.relative(root, own)}, not one of its own`,
650
+ )
651
+ }
652
+ if (link?.startsWith('workspace:')) {
653
+ // pnpm takes two workspace packages of one name without a word and links the one it reaches last, so a
654
+ // copy of the seam left under its name (a copied app, a stray directory) silently becomes the app's seam,
655
+ // and the kit's link agrees with the app's: only the names show it.
656
+ const name = /^(@?[^@]+)@/.exec(link.slice('workspace:'.length))?.[1] ?? SEAM
657
+ const holders = [root, ...packages].filter((pkg) => {
658
+ const file = path.join(pkg, 'package.json')
659
+ return existsSync(file) && readJson(file).name === name
660
+ })
661
+ if (holders.length !== 1) {
662
+ const where = holders.map((pkg) => path.relative(root, pkg) || '(the workspace root)').join(', ')
663
+ problems.push(
664
+ holders.length === 0
665
+ ? `${rel(dir)}: declares ${SEAM} as ${link}, but no workspace package is named ${name}`
666
+ : `${rel(dir)}: declares ${SEAM} as ${link}, but ${holders.length} workspace packages are named ${name} (${where}), and pnpm links one of them: rename the copies`,
667
+ )
668
+ }
669
+ }
670
+ if (link?.startsWith('link:') && own !== null) {
671
+ // Linked today, unlinked by the next partial install: pnpm keeps a `link:` dependency as the provider of
672
+ // @sssb/kit's peer only when it re-resolves every dependency of the app (a fresh install, a bare
673
+ // `pnpm update`), never on a partial install for the app, `add <pkg>`, `remove` or `update <pkg>`, which
674
+ // leave it unresolved (ADR-0014's 2026-11-18 addendum).
675
+ const name = `${typeof manifest.name === 'string' ? manifest.name : path.basename(dir)}-app-config`
676
+ problems.push(
677
+ `${rel(dir)}: declares ${SEAM} as ${link}, which the next \`pnpm add <pkg>\`, \`remove\` or \`update <pkg>\` for it unlinks from its @sssb/kit. ` +
678
+ `Make the seam a workspace package: list ${path.relative(root, path.join(dir, 'src', 'app-config'))} in pnpm-workspace.yaml's packages, name it ${name} in its package.json, ` +
679
+ `declare "${SEAM}": "workspace:${name}@*", and run pnpm install`,
680
+ )
681
+ }
682
+ }
683
+ return { problems, importers }
684
+ }
685
+
686
+ /**
687
+ * @param {(dir: string) => string} resolveKit
688
+ * @param {string} dir
689
+ * @returns {string | null}
690
+ */
691
+ function resolvesKit(resolveKit, dir) {
692
+ try {
693
+ return resolveKit(dir)
694
+ } catch {
695
+ return null
696
+ }
697
+ }
698
+
699
+ /**
700
+ * A package's own seam: the target of its `link:` dependency, or what its node_modules links (a `workspace:`
701
+ * dependency, the seam package of the package's own name), real path.
702
+ * @param {string} dir
703
+ * @param {string | undefined} spec
704
+ */
705
+ function ownSeam(dir, spec) {
706
+ if (spec === undefined) return null
707
+ const target = spec.startsWith('link:')
708
+ ? path.resolve(dir, spec.slice('link:'.length))
709
+ : path.join(dir, 'node_modules', ...SEAM.split('/'))
710
+ return existsSync(target) ? realpathSync(target) : null
711
+ }
712
+
713
+ /**
714
+ * A path as far as it exists made real, the rest appended: where a target that names a file not (yet) there lands.
715
+ * A bare specifier (no absolute path) is returned as it is.
716
+ * @param {string} target
717
+ */
718
+ export function realish(target) {
719
+ if (!path.isAbsolute(target)) return target
720
+ let dir = path.resolve(target)
721
+ /** @type {string[]} */
722
+ const rest = []
723
+ while (!existsSync(dir)) {
724
+ const parent = path.dirname(dir)
725
+ if (parent === dir) return target
726
+ rest.unshift(path.basename(dir))
727
+ dir = parent
728
+ }
729
+ return path.join(realpathSync(dir), ...rest)
730
+ }
731
+
732
+ /** A subpath no seam has, so a probe through it shows where a wildcard mapping sends any subpath. */
733
+ export const PROBE = '__sssb_doctor_probe__'
734
+
735
+ /**
736
+ * The specifiers doctor sends through a Vitest project's aliases to see where each sends the seam: the bare seam, a
737
+ * subpath no seam has, and one subpath per entry of the app's own seam directory (so an alias for one subpath, such as
738
+ * a RegExp for `@sssb/app-config/registrations`, is exercised too).
739
+ * @param {string} own the app's own seam directory
740
+ */
741
+ function seamProbes(own) {
742
+ const entries = existsSync(own) ? readdirSync(own).map((name) => name.replace(/\.[^.]+$/, '')) : []
743
+ return [...new Set([SEAM, `${SEAM}/${PROBE}`, ...entries.map((name) => `${SEAM}/${name}`)])]
744
+ }
745
+
746
+ /**
747
+ * Whether a Vite alias's `find` matches a specifier, exactly as Vite decides (a RegExp tests it; a string matches
748
+ * itself and anything under it).
749
+ * @param {string | RegExp} find
750
+ * @param {string} specifier
751
+ */
752
+ function aliasMatches(find, specifier) {
753
+ if (find instanceof RegExp) return new RegExp(find.source, find.flags.replace('g', '')).test(specifier)
754
+ return specifier === find || specifier.startsWith(find.endsWith('/') ? find : `${find}/`)
755
+ }
756
+
757
+ /** @typedef {{ find: string, to: string, resolved: string[] }} SeamRoute where one alias or `paths` entry sends the seam: `to` as written, `resolved` the real path each probe specifier lands on (a bare specifier as it is) */
758
+
759
+ /**
760
+ * Every entry of a Vitest project's resolved alias list (Vite's array form; the object form arrives as one) that
761
+ * would match any `@sssb/app-config` specifier, a string or a RegExp `find` alike, with where it sends each probe.
762
+ * Every matching entry counts, not only the first that wins today, since a reordered list would bring a later one in.
763
+ * @param {readonly { find: string | RegExp, replacement: string }[]} entries
764
+ * @param {string} own the app's own seam directory (real path)
765
+ * @returns {SeamRoute[]}
766
+ */
767
+ export function aliasRoutes(entries, own) {
768
+ const probes = seamProbes(own)
769
+ /** @type {SeamRoute[]} */
770
+ const routes = []
771
+ for (const { find, replacement } of entries) {
772
+ const matched = probes.filter((probe) => aliasMatches(find, probe))
773
+ if (matched.length === 0) continue
774
+ routes.push({
775
+ find: String(find),
776
+ to: replacement,
777
+ resolved: matched.map((probe) =>
778
+ realish(
779
+ find instanceof RegExp ? probe.replace(find, replacement) : replacement + probe.slice(find.length),
780
+ ),
781
+ ),
782
+ })
783
+ }
784
+ return routes
785
+ }
786
+
787
+ /**
788
+ * IN-REPO MODE's replacement for the per-importer seam check: inside SSSB's repository the seam goes through aliases,
789
+ * so every tsconfig `paths` key that is or starts with `@sssb/app-config` (every one of its targets), and every alias of
790
+ * each Vitest project that runs the app's files and would match an `@sssb/app-config` specifier, must send the seam
791
+ * into THAT app's own `src/app-config`.
792
+ * @param {{ app: string, own: string, tsconfig: SeamRoute[], projects: { config: string, project: string, routes: SeamRoute[] }[] }[]} apps
793
+ * `own` and every `resolved` path are real paths shown the same way (relative to the workspace root)
794
+ * @returns {string[]}
795
+ */
796
+ export function aliasProblems(apps) {
797
+ /** @type {string[]} */
798
+ const problems = []
799
+ for (const { app, own, tsconfig, projects } of apps) {
800
+ const inside = (/** @type {SeamRoute} */ route) =>
801
+ route.resolved.every((target) => target === own || target.startsWith(own + path.sep))
802
+ if (tsconfig.length === 0) problems.push(`${app}: its tsconfig maps no ${SEAM} path`)
803
+ for (const route of tsconfig.filter((r) => !inside(r)))
804
+ problems.push(`${app}: its tsconfig sends ${route.find} to ${route.to}, not its own ${own}`)
805
+ if (projects.length === 0) problems.push(`${app}: no Vitest project runs its files, so none aliases its seam`)
806
+ for (const { config, project, routes } of projects) {
807
+ const name = project === '' ? 'the root project' : `project ${project}`
808
+ if (routes.length === 0) problems.push(`${app}: Vitest ${name} (${config}) has no ${SEAM} alias`)
809
+ for (const route of routes.filter((r) => !inside(r)))
810
+ problems.push(
811
+ `${app}: Vitest ${name} (${config}) aliases ${route.find} to ${route.to}, not its own ${own}`,
812
+ )
813
+ }
814
+ }
815
+ return problems
816
+ }
817
+
818
+ /**
819
+ * Every `@sssb/*` package the app resolves, as Node's lookup finds each name from the app's directory (the nearest
820
+ * `node_modules/@sssb/<name>` wins), with its version. The seam is the app's own package, not a release, and is left
821
+ * out.
822
+ * @param {string} appDir
823
+ * @returns {Map<string, string | undefined>} package name -> version
824
+ */
825
+ export function sssbPackagesOf(appDir) {
826
+ /** @type {Map<string, string | undefined>} */
827
+ const found = new Map()
828
+ for (let dir = path.resolve(appDir); ; dir = path.dirname(dir)) {
829
+ const scope = path.join(dir, 'node_modules', '@sssb')
830
+ if (existsSync(scope)) {
831
+ for (const name of readdirSync(scope).sort()) {
832
+ const full = `@sssb/${name}`
833
+ if (full === SEAM || found.has(full)) continue
834
+ const manifest = path.join(scope, name, 'package.json')
835
+ if (!existsSync(manifest)) continue
836
+ found.set(full, readJson(manifest).version)
837
+ }
838
+ }
839
+ if (path.dirname(dir) === dir) return found
840
+ }
841
+ }
842
+
843
+ /**
844
+ * VERSIONS IN STEP (ADR-0014 part 5): every `@sssb/*` package the app resolves is the version of its `@sssb/kit`. The
845
+ * packages carry no dependency on each other that would keep them together, so nothing else does.
846
+ * @param {Map<string, string | undefined>} packages
847
+ * @returns {string[]}
848
+ */
849
+ export function versionProblems(packages) {
850
+ const kit = packages.get(KIT)
851
+ if (kit === undefined) return ['@sssb/kit: the app resolves no version of it']
852
+ return [...packages]
853
+ .filter(([name, version]) => name !== KIT && version !== kit)
854
+ .map(([name, version]) => `${name} ${version ?? '(no version)'} is not @sssb/kit's ${kit}`)
855
+ }
856
+
857
+ /** Vitest flags that take a value as the next word (so that word is no file filter). */
858
+ const VALUE_FLAGS = new Set([
859
+ '--config',
860
+ '-c',
861
+ '--project',
862
+ '--exclude',
863
+ '-t',
864
+ '--testNamePattern',
865
+ '--shard',
866
+ '--reporter',
867
+ '--outputFile',
868
+ '--root',
869
+ '-r',
870
+ '--dir',
871
+ '--environment',
872
+ '--pool',
873
+ '--maxWorkers',
874
+ '--mode',
875
+ '--testTimeout',
876
+ '--hookTimeout',
877
+ '--retry',
878
+ '--bail',
879
+ ])
880
+
881
+ /** Vitest flags that can run fewer tests than the configuration would. */
882
+ const NARROWING_FLAGS = new Set([
883
+ '--project',
884
+ '--exclude',
885
+ '-t',
886
+ '--testNamePattern',
887
+ '--changed',
888
+ '--related',
889
+ '--shard',
890
+ '--typecheck.only',
891
+ '--dir',
892
+ ])
893
+
894
+ /** Vitest subcommands that run the configuration's files (`related` narrows them, and is reported). */
895
+ const SUBCOMMANDS = new Set(['run', 'watch', 'dev', 'list', 'bench'])
896
+
897
+ /** @typedef {{ script: string, config: string | null, narrowing: string[] }} VitestInvocation */
898
+
899
+ /**
900
+ * Every place a package.json's scripts run Vitest, with the `--config` each names and every flag or positional file
901
+ * filter that can narrow what the configuration would run. Read from the script text alone: a shell's words (quotes
902
+ * honoured) split at `&&`, `||`, `;` and `|`, a quoted word holding a whole command (`sh -c '...'`) read again, the
903
+ * `vitest` word found by name or path (`vitest`, `node_modules/vitest/vitest.mjs`). A script that runs another
904
+ * script is not followed.
905
+ * @param {Record<string, unknown>} scripts
906
+ * @returns {VitestInvocation[]}
907
+ */
908
+ export function vitestInvocations(scripts) {
909
+ /** @type {VitestInvocation[]} */
910
+ const found = []
911
+ /** @param {string} script @param {string} command */
912
+ const scan = (script, command) => {
913
+ for (const segment of shellSegments(command)) {
914
+ for (const word of segment.filter((w) => /\s/.test(w))) scan(script, word)
915
+ const at = segment.findIndex((word) => /(^|\/)vitest(\.m?js)?$/.test(word))
916
+ if (at < 0) continue
917
+ const args = segment.slice(at + 1)
918
+ /** @type {string | null} */
919
+ let config = null
920
+ /** @type {string[]} */
921
+ const narrowing = []
922
+ let i = 0
923
+ if (SUBCOMMANDS.has(args[0] ?? '')) i = 1
924
+ else if (args[0] === 'related') {
925
+ narrowing.push('related')
926
+ i = 1
927
+ }
928
+ for (; i < args.length; i++) {
929
+ const arg = args[i] ?? ''
930
+ if (!arg.startsWith('-')) {
931
+ narrowing.push(arg)
932
+ continue
933
+ }
934
+ const eq = arg.indexOf('=')
935
+ const name = eq < 0 ? arg : arg.slice(0, eq)
936
+ let value = eq < 0 ? undefined : arg.slice(eq + 1)
937
+ const separate = value === undefined && VALUE_FLAGS.has(name)
938
+ if (separate) value = args[++i]
939
+ if (name === '--config' || name === '-c') config = value ?? null
940
+ if (NARROWING_FLAGS.has(name)) narrowing.push(separate ? `${name} ${value ?? ''}`.trim() : arg)
941
+ }
942
+ found.push({ script, config, narrowing })
943
+ }
944
+ }
945
+ for (const [script, command] of Object.entries(scripts)) if (typeof command === 'string') scan(script, command)
946
+ return found
947
+ }
948
+
949
+ /**
950
+ * A shell command's words, quotes removed, split into the commands that `&&`, `||`, `;`, `|` and `&` separate.
951
+ * @param {string} command
952
+ * @returns {string[][]}
953
+ */
954
+ function shellSegments(command) {
955
+ /** @type {string[][]} */
956
+ const segments = [[]]
957
+ /** @type {string | null} */
958
+ let word = null
959
+ /** @type {string | null} */
960
+ let quote = null
961
+ const end = () => {
962
+ if (word !== null) segments.at(-1)?.push(word)
963
+ word = null
964
+ }
965
+ for (const c of command) {
966
+ if (quote !== null) {
967
+ if (c === quote) quote = null
968
+ else word += c
969
+ } else if (c === "'" || c === '"') {
970
+ quote = c
971
+ word ??= ''
972
+ } else if (/\s/.test(c)) end()
973
+ else if (';&|'.includes(c)) {
974
+ end()
975
+ if ((segments.at(-1)?.length ?? 0) > 0) segments.push([])
976
+ } else word = (word ?? '') + c
977
+ }
978
+ end()
979
+ return segments.filter((segment) => segment.length > 0)
980
+ }
981
+
982
+ /**
983
+ * The framework's cutover rows (`@sssb/kit/cutover/rows.json`) the workspace's own checklist never mentions, by their
984
+ * backticked item name. A row marked `scope: 'sssb'` (`release-app`) belongs to SSSB's own repository only, is no
985
+ * adopter's to record, and is set apart instead.
986
+ * @param {{ rows: { id: string, what: string, scope?: string }[] }} rows
987
+ * @param {string | null} checklist the text of the workspace's docs/cutover-checklist.md, null when it has none
988
+ * @returns {{ unmentioned: string[], sssbOnly: string[] }}
989
+ */
990
+ export function cutoverReport(rows, checklist) {
991
+ const sssbOnly = rows.rows.filter((row) => row.scope === 'sssb').map((row) => row.id)
992
+ const unmentioned = rows.rows
993
+ .filter((row) => !sssbOnly.includes(row.id))
994
+ .filter((row) => checklist === null || !checklist.includes(`\`${row.id}\``))
995
+ .map((row) => row.id)
996
+ return { unmentioned, sssbOnly }
997
+ }
998
+
999
+ /**
1000
+ * PORT SLOTS: two apps of one workspace must not bind one port. An app declares its slot in its package.json
1001
+ * (`"sssb": { "port": "starter" }`, or a slot of its own, `{ "name": "ledger", "default": 3800 }`), the slot fixes the
1002
+ * port its dev server, its Playwright config and its ticker use, so two apps on one slot start on one port: the second
1003
+ * server fails to bind, or, under Playwright's `reuseExistingServer`, the second app's suite ADOPTS the first app's
1004
+ * server and tests the wrong app (docs/build-notes.md). Fails: a declaration that is not valid, two apps on one slot
1005
+ * name, and two apps on distinct names whose main-checkout default is one port (a worktree's derived ports differ by
1006
+ * name, so the default is the one that can still collide). An app with no declaration is not checked.
1007
+ * @param {string} root the workspace root, for the names the problems give
1008
+ * @param {readonly string[]} apps the apps' directories (absolute)
1009
+ * @returns {{ problems: string[], slots: string[] }} the problems, and one line per declaring app for the check's notes
1010
+ */
1011
+ export function portSlotProblems(root, apps) {
1012
+ /** @type {string[]} */
1013
+ const problems = []
1014
+ /** @type {string[]} */
1015
+ const slots = []
1016
+ /** @type {Map<string, string[]>} app directories by slot name */
1017
+ const byName = new Map()
1018
+ /** @type {Map<number, { app: string, name: string }[]>} */
1019
+ const byDefault = new Map()
1020
+ for (const app of apps) {
1021
+ const where = path.relative(root, app) || '(the workspace root)'
1022
+ let declared
1023
+ try {
1024
+ declared = readPortDeclaration(app)
1025
+ } catch (error) {
1026
+ problems.push(`${where}: ${error instanceof Error ? error.message.replace(/^ports: /, '') : String(error)}`)
1027
+ continue
1028
+ }
1029
+ if (declared === undefined) continue
1030
+ const name = typeof declared === 'string' ? declared : declared.name
1031
+ // A main checkout's port (the filesystem root is no worktree), whatever this workspace's own path is.
1032
+ const fallback = portForRoot(path.sep, declared, {})
1033
+ slots.push(`${where}: slot "${name}", port ${fallback} in a main checkout`)
1034
+ byName.set(name, [...(byName.get(name) ?? []), where])
1035
+ byDefault.set(fallback, [...(byDefault.get(fallback) ?? []), { app: where, name }])
1036
+ }
1037
+ for (const [name, dirs] of byName) {
1038
+ if (dirs.length < 2) continue
1039
+ problems.push(
1040
+ `${dirs.join(' and ')} declare the same port slot "${name}", so their dev servers, e2e servers and tickers ` +
1041
+ "bind one port (and the second suite adopts the first app's server). Give each its own: " +
1042
+ '"sssb": { "port": { "name": "<name>", "default": <port> } } in its package.json',
1043
+ )
1044
+ }
1045
+ for (const [port, holders] of byDefault) {
1046
+ const distinct = [...new Set(holders.map(({ name }) => name))]
1047
+ if (distinct.length < 2) continue
1048
+ problems.push(
1049
+ `${holders.map(({ app }) => app).join(' and ')} declare port slots (${distinct.map((n) => `"${n}"`).join(', ')}) ` +
1050
+ `with one default, ${port}, so in a main checkout they bind one port: give each its own default`,
1051
+ )
1052
+ }
1053
+ return { problems, slots }
1054
+ }
1055
+
1056
+ /**
1057
+ * JSONC as JSON: its comments and trailing commas taken out, strings (a `$schema` URL's `//` among them) left whole.
1058
+ * @param {string} text
1059
+ */
1060
+ function withoutJsonComments(text) {
1061
+ let out = ''
1062
+ // A comma is held until the next token: dropped before a `}` or `]` (a trailing comma), written before anything else.
1063
+ let comma = ''
1064
+ const token = (/** @type {string} */ value) => {
1065
+ out += /^[}\]]/.test(value) ? comma.slice(1) : comma
1066
+ comma = ''
1067
+ out += value
1068
+ }
1069
+ for (let i = 0; i < text.length; i++) {
1070
+ const char = /** @type {string} */ (text[i])
1071
+ if (char === '"') {
1072
+ let end = i + 1
1073
+ while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1
1074
+ token(text.slice(i, end + 1))
1075
+ i = end
1076
+ } else if (char === '/' && text[i + 1] === '/') {
1077
+ while (i + 1 < text.length && text[i + 1] !== '\n') i++
1078
+ } else if (char === '/' && text[i + 1] === '*') {
1079
+ const end = text.indexOf('*/', i + 2)
1080
+ i = end < 0 ? text.length : end + 1
1081
+ } else if (char === ',') {
1082
+ token('')
1083
+ comma = ','
1084
+ } else if (/\s/.test(char)) {
1085
+ if (comma) comma += char
1086
+ else out += char
1087
+ } else token(char)
1088
+ }
1089
+ return out + comma
1090
+ }
1091
+
1092
+ /** Where knip looks for its JSON config at a workspace root, in its own order. */
1093
+ const KNIP_JSON = ['knip.json', 'knip.jsonc', '.knip.json', '.knip.jsonc']
1094
+
1095
+ /**
1096
+ * KNIP'S WORKSPACES against the workspace's apps: a generated workspace's knip.json gives each app, and its seam, an
1097
+ * entry of its own (their entry files, and the dependencies SSSB's tools load from the app), so an app it does not name
1098
+ * is read with knip's defaults, which flag the seam's modules (the framework reads them from node_modules, which knip
1099
+ * does not follow) and the presets' dependencies as unused. Reported, never failed: knip's own run is the gate.
1100
+ * It also says when the root installs `@sssb/create` (as `sssb add-app` asks) and knip's root config does not ignore it:
1101
+ * nothing imports it (the command loads it from node_modules), so knip calls it an unused dependency.
1102
+ * Returns null when the root has no knip JSON config; `missing` is null when it has no `workspaces` (one config for
1103
+ * every package).
1104
+ * @param {string} root
1105
+ * @param {readonly string[]} apps absolute
1106
+ * @param {readonly string[]} packages the workspace's packages, absolute (workspacePackages)
1107
+ * @returns {{ file: string, missing: string[] | null, generator: boolean } | { file: string, unread: string } | null}
1108
+ */
1109
+ export function knipGaps(root, apps, packages) {
1110
+ const file = KNIP_JSON.find((name) => existsSync(path.join(root, name)))
1111
+ if (file === undefined) return null
1112
+ let config
1113
+ try {
1114
+ // As knip reads it: a byte-order mark dropped, and comments and trailing commas allowed in every one of its names
1115
+ // (it falls back to JSONC for a `.json` too). Plain JSON passes through unchanged.
1116
+ const text = readFileSync(path.join(root, file), 'utf8').replace(/^\uFEFF/, '')
1117
+ config = JSON.parse(withoutJsonComments(text))
1118
+ } catch (error) {
1119
+ return { file, unread: error instanceof Error ? error.message : String(error) }
1120
+ }
1121
+ const workspaces = config?.workspaces
1122
+ const hasWorkspaces = workspaces !== null && typeof workspaces === 'object'
1123
+ const rootConfig = hasWorkspaces ? workspaces['.'] : config
1124
+ const ignored = /** @type {unknown[]} */ (
1125
+ [config?.ignoreDependencies, rootConfig?.ignoreDependencies].flatMap((list) =>
1126
+ Array.isArray(list) ? list : [],
1127
+ )
1128
+ )
1129
+ const manifestFile = path.join(root, 'package.json')
1130
+ const rootManifest = existsSync(manifestFile) ? readJson(manifestFile) : {}
1131
+ const installs = ['dependencies', 'devDependencies'].some((field) => rootManifest?.[field]?.['@sssb/create'])
1132
+ // knip reads an entry with a regular expression's characters as one (its `toRegexOrString`).
1133
+ const ignores = (/** @type {unknown} */ entry) => {
1134
+ if (typeof entry !== 'string') return false
1135
+ if (entry === '@sssb/create') return true
1136
+ if (!/[*+\\(|{^$]/.test(entry)) return false
1137
+ try {
1138
+ return new RegExp(entry).test('@sssb/create')
1139
+ } catch {
1140
+ return false
1141
+ }
1142
+ }
1143
+ const generator = Boolean(installs) && !ignored.some(ignores)
1144
+ if (!hasWorkspaces) return { file, missing: null, generator }
1145
+ const keys = Object.keys(workspaces)
1146
+ const named = (/** @type {string} */ rel) =>
1147
+ keys.some((key) => key === rel || path.posix.matchesGlob(rel, key.replace(/\/+$/, '')))
1148
+ /** @type {string[]} */
1149
+ const missing = []
1150
+ for (const app of apps) {
1151
+ const rel = path.relative(root, app).split(path.sep).join('/')
1152
+ // An app at the root is knip's `.` workspace, which a config with workspaces always has a say over; an app that
1153
+ // is no workspace package is part of the root's for knip, and needs no key of its own.
1154
+ if (rel !== '' && packages.includes(app) && !named(rel)) missing.push(rel)
1155
+ const seam = path.join(app, 'src', 'app-config')
1156
+ const seamRel = path.relative(root, seam).split(path.sep).join('/')
1157
+ if (packages.includes(seam) && !named(seamRel)) missing.push(seamRel)
1158
+ }
1159
+ return { file, missing, generator }
1160
+ }
1161
+
1162
+ /** A full commit SHA, the only pin that cannot move. */
1163
+ const COMMIT = /^[0-9a-f]{40}$/
1164
+
1165
+ /**
1166
+ * The `owner/name` a package.json's `repository` names on GitHub, lowercased, or null.
1167
+ * @param {unknown} repository the manifest's `repository` field (a string or `{ url }`)
1168
+ */
1169
+ export function githubRepositoryOf(repository) {
1170
+ const url = typeof repository === 'string' ? repository : /** @type {{ url?: unknown }} */ (repository)?.url
1171
+ const match = typeof url === 'string' ? /github\.com[/:]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(url) : null
1172
+ return match?.[1] ? match[1].toLowerCase() : null
1173
+ }
1174
+
1175
+ /**
1176
+ * @typedef {{ where: string, ref: string | null }} Pin a place the workspace pins SSSB, and the ref it pins (null: none,
1177
+ * so it follows the default branch)
1178
+ */
1179
+
1180
+ /**
1181
+ * One `uses:` line that calls a reusable workflow (`uses: <owner>/<name>/.github/workflows/<file>@<ref>`), cut so a
1182
+ * caller can read or rewrite the ref (`sssb pin`): 1 everything up to and including the `@`, 2 the `owner/name`, 3 the
1183
+ * workflow's path, 4 the ref, 5 whatever follows it (a trailing comment, a carriage return). One regex for doctor's
1184
+ * report and the command that fixes what it reports, so they cannot disagree about what a pin is.
1185
+ */
1186
+ export const WORKFLOW_USES =
1187
+ /^(\s*(?:-\s+)?uses:\s*['"]?([\w.-]+\/[\w.-]+)\/(\.github\/workflows\/[^@\s'"]+)@)([^\s'"#]+)([\s\S]*)$/
1188
+
1189
+ /**
1190
+ * Every call of a reusable workflow of `repository` in the workspace's workflow files, the owner and name compared as
1191
+ * GitHub compares them, without case.
1192
+ * @param {string} repository `owner/name`, lowercased
1193
+ * @param {{ file: string, text: string }[]} workflows
1194
+ * @returns {Pin[]}
1195
+ */
1196
+ function workflowPins(repository, workflows) {
1197
+ /** @type {Pin[]} */
1198
+ const pins = []
1199
+ for (const { file, text } of workflows) {
1200
+ for (const line of text.split('\n')) {
1201
+ const match = WORKFLOW_USES.exec(line)
1202
+ if (match?.[2]?.toLowerCase() === repository)
1203
+ pins.push({ where: `${file} (${match[3]})`, ref: /** @type {string} */ (match[4]) })
1204
+ }
1205
+ }
1206
+ return pins
1207
+ }
1208
+
1209
+ /**
1210
+ * The `owner/name` a marketplace's `source` names on GitHub, lowercased: a `github` source's `repo`, or a `git` source's
1211
+ * `url`. Null for any other source.
1212
+ * @param {any} source an `extraKnownMarketplaces.<name>.source` value
1213
+ * @returns {string | null}
1214
+ */
1215
+ export function sourceRepository(source) {
1216
+ if (source?.source === 'github' && typeof source.repo === 'string')
1217
+ return source.repo.toLowerCase().replace(/\.git$/, '')
1218
+ return source?.source === 'git' ? githubRepositoryOf(source.url) : null
1219
+ }
1220
+
1221
+ /**
1222
+ * Every marketplace `.claude/settings.json` declares from `repository` (`extraKnownMarketplaces.<name>.source`, a
1223
+ * `github` source naming it as `repo`, or a `git` one whose `url` is it), with its `ref`; and, when there is one, a
1224
+ * line when no plugin is enabled from any of them. A pinned marketplace loads nothing by itself: only
1225
+ * `enabledPlugins["<plugin>@<marketplace>"]: true` (or a non-empty array of version constraints) loads a plugin from
1226
+ * it. The kit does not know the plugin's name,
1227
+ * and needs not: SSSB's marketplace lists only SSSB's plugins, so any plugin enabled from it is one of them, while
1228
+ * `sssb@<another marketplace>` is a copy from elsewhere (a local checkout's, say), not the pinned one.
1229
+ * @param {string} repository `owner/name`, lowercased
1230
+ * @param {string} file the settings file, as shown
1231
+ * @param {string} text its contents
1232
+ * @returns {{ pins: Pin[], error: string | null, unused: string | null }}
1233
+ */
1234
+ function marketplacePins(repository, file, text) {
1235
+ let settings
1236
+ try {
1237
+ settings = JSON.parse(text)
1238
+ } catch (error) {
1239
+ return {
1240
+ pins: [],
1241
+ error: `${file} is not JSON doctor can read (${error instanceof Error ? error.message : error})`,
1242
+ unused: null,
1243
+ }
1244
+ }
1245
+ /** @type {Pin[]} */
1246
+ const pins = []
1247
+ /** @type {string[]} */
1248
+ const names = []
1249
+ const marketplaces = settings?.extraKnownMarketplaces
1250
+ for (const [name, entry] of Object.entries(typeof marketplaces === 'object' && marketplaces ? marketplaces : {})) {
1251
+ const source = entry?.source
1252
+ if (sourceRepository(source) === repository) {
1253
+ names.push(name)
1254
+ pins.push({
1255
+ where: `${file} (marketplace ${name})`,
1256
+ ref: typeof source.ref === 'string' ? source.ref : null,
1257
+ })
1258
+ }
1259
+ }
1260
+ const plugins = settings?.enabledPlugins
1261
+ const entries = Object.entries(typeof plugins === 'object' && plugins ? plugins : {})
1262
+ const fromSssb = (/** @type {string} */ key) => names.includes(key.slice(key.lastIndexOf('@') + 1))
1263
+ // Claude Code takes `true`, or a non-empty array of version constraints, as enabled.
1264
+ const isOn = (/** @type {unknown} */ on) => on === true || (Array.isArray(on) && on.length > 0)
1265
+ if (names.length === 0 || entries.some(([key, on]) => isOn(on) && fromSssb(key)))
1266
+ return { pins, error: null, unused: null }
1267
+ const enabled = entries.filter(([, on]) => isOn(on)).map(([key]) => key)
1268
+ const off = entries
1269
+ .filter(([key, on]) => !isOn(on) && fromSssb(key))
1270
+ .map(([key, on]) => `${key}: ${JSON.stringify(on)}`)
1271
+ return {
1272
+ pins,
1273
+ error: null,
1274
+ unused:
1275
+ `${file} enables no plugin from marketplace ${names.join(', ')}, so the pin loads nothing: its enabledPlugins ` +
1276
+ `enable ${enabled.length > 0 ? enabled.join(', ') : 'none'}${off.length > 0 ? ` (and set ${off.join(', ')})` : ''}`,
1277
+ }
1278
+ }
1279
+
1280
+ /**
1281
+ * The commit a kit's release stamp (the text of its dist/release.json) names, or null for none or one unreadable.
1282
+ * @param {string | null} stamp
1283
+ */
1284
+ export function stampedCommit(stamp) {
1285
+ try {
1286
+ const parsed = stamp === null ? null : JSON.parse(stamp)
1287
+ return typeof parsed?.commit === 'string' && COMMIT.test(parsed.commit) ? parsed.commit : null
1288
+ } catch {
1289
+ return null
1290
+ }
1291
+ }
1292
+
1293
+ /**
1294
+ * THE WORKFLOW AND PLUGIN PINS (ADR-0014 part 5): the commits the workspace pins SSSB's reusable workflow at and the
1295
+ * plugin's marketplace at, against the release commit the installed `@sssb/kit` stamps into its package
1296
+ * (`dist/release.json`). Never a failure: the pins are in the workspace's own files, not installed code, and CI and
1297
+ * people not using Claude Code have no plugin. `ok` only when the kit has a stamp, the workspace has both pins, and
1298
+ * every one is that commit, with a plugin enabled from the pinned marketplace (`enabledPlugins`); otherwise a report
1299
+ * naming what is missing, which pin differs (with both commits), or which plugins are enabled instead.
1300
+ * @param {{
1301
+ * inRepo: boolean,
1302
+ * version: string,
1303
+ * stamp: string | null,
1304
+ * repository: string | null,
1305
+ * workflows: { file: string, text: string }[],
1306
+ * settings: { file: string, text: string } | null,
1307
+ * }} input `stamp`: the text of the kit's dist/release.json, null when it has none; `repository`: the `owner/name` the
1308
+ * kit's package.json names (githubRepositoryOf); `settings`: `.claude/settings.json`, null when the workspace has none
1309
+ * @returns {{ status: 'ok' | 'report', title: string, lines: string[] }}
1310
+ */
1311
+ export function pinReport({ inRepo, version, stamp, repository, workflows, settings }) {
1312
+ const label = 'workflow and plugin pins'
1313
+ if (inRepo)
1314
+ return {
1315
+ status: 'report',
1316
+ title:
1317
+ `${label}: not checked: in-repo, @sssb/kit is this workspace's own source, which carries no release ` +
1318
+ 'stamp (the commit a packed kit names in dist/release.json), so there is no release commit to compare ' +
1319
+ 'pins with',
1320
+ lines: [],
1321
+ }
1322
+ if (repository === null)
1323
+ return {
1324
+ status: 'report',
1325
+ title: `${label}: not checked: @sssb/kit ${version}'s package.json names no GitHub repository, so doctor cannot tell which pins are SSSB's`,
1326
+ lines: [],
1327
+ }
1328
+ /** @type {string[]} */
1329
+ const lines = []
1330
+ const workflowFound = workflowPins(repository, workflows)
1331
+ if (workflowFound.length === 0)
1332
+ lines.push(`no workflow under .github/workflows calls a reusable workflow of ${repository}: no workflow pin`)
1333
+ /** @type {Pin[]} */
1334
+ let marketplaceFound = []
1335
+ /** @type {string | null} */
1336
+ let unused = null
1337
+ if (settings === null)
1338
+ lines.push(
1339
+ 'no .claude/settings.json: no plugin marketplace pin (a workspace whose people do not use Claude Code has no plugin)',
1340
+ )
1341
+ else {
1342
+ const read = marketplacePins(repository, settings.file, settings.text)
1343
+ marketplaceFound = read.pins
1344
+ if (read.error !== null) lines.push(read.error)
1345
+ else if (read.pins.length === 0)
1346
+ lines.push(`${settings.file} declares no marketplace from ${repository}: no plugin marketplace pin`)
1347
+ unused = read.unused
1348
+ }
1349
+ const found = [...workflowFound, ...marketplaceFound]
1350
+
1351
+ const commit = stampedCommit(stamp)
1352
+ if (commit === null)
1353
+ return {
1354
+ status: 'report',
1355
+ title:
1356
+ `${label}: not checked: @sssb/kit ${version} ` +
1357
+ (stamp === null
1358
+ ? 'carries no release stamp (dist/release.json): it was packed before ADR-0014 P13 stamped one, or not by its own prepack'
1359
+ : 'has a release stamp (dist/release.json) that names no commit') +
1360
+ ', so there is no release commit to compare the pins with',
1361
+ lines: [
1362
+ ...found.map((pin) => `${pin.where} pins ${pin.ref ?? 'no ref'}`),
1363
+ ...lines,
1364
+ ...(unused === null ? [] : [unused]),
1365
+ ],
1366
+ }
1367
+
1368
+ const differing = found.filter((pin) => pin.ref !== commit)
1369
+ for (const pin of differing)
1370
+ lines.push(
1371
+ pin.ref === null
1372
+ ? `${pin.where} pins no ref, so it follows ${repository}'s default branch, not @sssb/kit's release commit ${commit}`
1373
+ : `${pin.where} pins ${pin.ref}${COMMIT.test(pin.ref) ? '' : ' (a branch or tag, not a commit)'}, not @sssb/kit's release commit ${commit}`,
1374
+ )
1375
+ const pinProblems = lines.length
1376
+ if (unused !== null) lines.push(unused)
1377
+ if (lines.length === 0)
1378
+ return {
1379
+ status: 'ok',
1380
+ title: `${label}: the reusable workflow and the plugin marketplace pin @sssb/kit ${version}'s release commit ${commit}`,
1381
+ lines: found.map((pin) => pin.where),
1382
+ }
1383
+ return {
1384
+ status: 'report',
1385
+ title:
1386
+ `${label}: ` +
1387
+ (pinProblems === 0
1388
+ ? `the pins are @sssb/kit ${version}'s release commit ${commit}, but no plugin is enabled from the ` +
1389
+ "pinned marketplace (reported, not failed: enable it in this workspace's .claude/settings.json)"
1390
+ : (differing.length > 0
1391
+ ? `${differing.length} pin(s) differ from @sssb/kit ${version}'s release commit ${commit}`
1392
+ : `not every pin is there to compare with @sssb/kit ${version}'s release commit ${commit}`) +
1393
+ " (reported, not failed: the pins are in this workspace's own files; `pnpm exec sssb pin` raises both to the release commit)"),
1394
+ lines,
1395
+ }
1396
+ }