@syntopica/create-baseline 0.9.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -0
  3. package/baseline-versions.json +16 -0
  4. package/bin/baseline-estate.mjs +85 -0
  5. package/bin/conformance/applyFixes.mjs +101 -0
  6. package/bin/conformance/checkActionPins.mjs +43 -0
  7. package/bin/conformance/checkCiWorkflow.mjs +52 -0
  8. package/bin/conformance/checkCoverageThresholds.mjs +112 -0
  9. package/bin/conformance/checkGateCoverage.mjs +128 -0
  10. package/bin/conformance/checkHooksInstalled.mjs +43 -0
  11. package/bin/conformance/checkLintFlag.mjs +86 -0
  12. package/bin/conformance/checkTsconfigPresets.mjs +58 -0
  13. package/bin/conformance/checkTsconfigProjects.mjs +47 -0
  14. package/bin/conformance/checkVersionRanges.mjs +51 -0
  15. package/bin/conformance/ciEntrypoints.mjs +37 -0
  16. package/bin/conformance/expandScripts.mjs +76 -0
  17. package/bin/conformance/formatFindings.mjs +36 -0
  18. package/bin/conformance/loadContext.mjs +175 -0
  19. package/bin/conformance/loadExceptions.mjs +73 -0
  20. package/bin/conformance/rangeFloor.mjs +23 -0
  21. package/bin/conformance/readWorkflows.mjs +29 -0
  22. package/bin/conformance/runConformance.mjs +57 -0
  23. package/bin/create-baseline.mjs +432 -0
  24. package/bin/estate/findConsumers.mjs +46 -0
  25. package/bin/estate/findPythonConsumers.mjs +58 -0
  26. package/bin/estate/formatEstate.mjs +67 -0
  27. package/bin/estate/formatPythonEstate.mjs +37 -0
  28. package/bin/python/checkGateWorkflow.mjs +33 -0
  29. package/bin/python/checkLockPin.mjs +36 -0
  30. package/bin/python/checkQualityGroup.mjs +33 -0
  31. package/bin/python/loadPythonContext.mjs +32 -0
  32. package/bin/python/repositoryRoot.mjs +24 -0
  33. package/bin/python/runPythonConformance.mjs +25 -0
  34. package/bin/scaffold/actionPins.mjs +34 -0
  35. package/bin/scaffold/baselineScripts.mjs +44 -0
  36. package/bin/scaffold/checkPeers.mjs +87 -0
  37. package/bin/scaffold/ciWorkflow.mjs +144 -0
  38. package/bin/scaffold/collectDeps.mjs +10 -0
  39. package/bin/scaffold/composedSubpaths.mjs +41 -0
  40. package/bin/scaffold/depCruiserConfig.mjs +30 -0
  41. package/bin/scaffold/detectFramework.mjs +18 -0
  42. package/bin/scaffold/eslintSubpathPeers.mjs +60 -0
  43. package/bin/scaffold/knipConfig.mjs +9 -0
  44. package/bin/scaffold/lefthookConfig.mjs +33 -0
  45. package/bin/scaffold/oxlintConfig.mjs +19 -0
  46. package/bin/scaffold/readManifest.mjs +17 -0
  47. package/bin/scaffold/renovateConfig.mjs +11 -0
  48. package/bin/scaffold/workspaceRoots.mjs +89 -0
  49. package/bin/scaffold/writeCiWorkflow.mjs +54 -0
  50. package/bin/scaffold/writeMissing.mjs +116 -0
  51. package/package.json +59 -0
  52. package/python-versions.json +3 -0
@@ -0,0 +1,23 @@
1
+ const VERSION = /(\d+)\.(\d+)\.(\d+)/
2
+
3
+ /**
4
+ * The lowest version a dependency range admits, as `[major, minor, patch]`.
5
+ *
6
+ * Comparing floors is the honest question for baseline drift. `^0.1.2` cannot
7
+ * resolve `0.2.0` at all - under semver a caret on a `0.x` line is locked to
8
+ * the minor - so a repository on `^0.1.2` will never receive the published
9
+ * `0.2.0` no matter how often Renovate runs, and its floor says so without
10
+ * needing a resolver or a network call.
11
+ *
12
+ * Returns `null` for a range with no concrete version in it (`workspace:*`,
13
+ * `*`, `latest`, a git or file specifier). Those are deliberate choices, not
14
+ * drift, and the caller skips them.
15
+ */
16
+ export function rangeFloor(range) {
17
+ if (typeof range !== 'string') return null
18
+ if (range.startsWith('workspace:')) return null
19
+ if (range.startsWith('npm:')) return rangeFloor(range.slice(4))
20
+ const match = VERSION.exec(range)
21
+ if (!match) return null
22
+ return [Number(match[1]), Number(match[2]), Number(match[3])]
23
+ }
@@ -0,0 +1,29 @@
1
+ import { readdir, readFile } from 'node:fs/promises'
2
+ import { resolve } from 'node:path'
3
+
4
+ /**
5
+ * Every workflow under `.github/workflows`, as `{ name, text }`.
6
+ *
7
+ * Shared by the JavaScript and the Python conformance passes: the questions
8
+ * they ask of a workflow differ, the way they read one does not.
9
+ */
10
+ export async function readWorkflows(root) {
11
+ const dir = resolve(root, '.github/workflows')
12
+ let names
13
+ try {
14
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
15
+ names = (await readdir(dir)).filter((name) => /\.ya?ml$/.test(name))
16
+ } catch {
17
+ return []
18
+ }
19
+ const workflows = []
20
+ for (const name of names) {
21
+ try {
22
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
23
+ workflows.push({ name, text: await readFile(resolve(dir, name), 'utf8') })
24
+ } catch {
25
+ /* unreadable file is not a workflow */
26
+ }
27
+ }
28
+ return workflows
29
+ }
@@ -0,0 +1,57 @@
1
+ import { checkActionPins } from './checkActionPins.mjs'
2
+ import { checkCiWorkflow } from './checkCiWorkflow.mjs'
3
+ import { checkCoverageThresholds } from './checkCoverageThresholds.mjs'
4
+ import { checkGateCoverage } from './checkGateCoverage.mjs'
5
+ import { checkHooksInstalled } from './checkHooksInstalled.mjs'
6
+ import { checkLintFlag } from './checkLintFlag.mjs'
7
+ import { checkTsconfigPresets } from './checkTsconfigPresets.mjs'
8
+ import { checkTsconfigProjects } from './checkTsconfigProjects.mjs'
9
+ import { checkVersionRanges } from './checkVersionRanges.mjs'
10
+ import { loadContext } from './loadContext.mjs'
11
+ import { loadExceptions } from './loadExceptions.mjs'
12
+
13
+ const CHECKS = [
14
+ checkLintFlag,
15
+ checkGateCoverage,
16
+ checkTsconfigProjects,
17
+ checkTsconfigPresets,
18
+ checkCiWorkflow,
19
+ checkActionPins,
20
+ checkCoverageThresholds,
21
+ checkHooksInstalled,
22
+ checkVersionRanges,
23
+ ]
24
+
25
+ /**
26
+ * Whether a repository's baseline gates are wired, not merely installed.
27
+ *
28
+ * The distinction is the reason this exists. `--check` used to assert that
29
+ * four packages appeared in package.json, which it did happily for a
30
+ * repository with no CI, a `lint` script that ignored warnings, and a
31
+ * `check:ci` that skipped knip, jscpd, dependency-cruiser and type-coverage.
32
+ * Adoption was measured by presence, so drift in enforcement was invisible by
33
+ * construction, and every finding in the estate sweep traced back to it.
34
+ *
35
+ * Returns `{ findings, waived, context }`. Findings are ordered as declared
36
+ * above: the wiring failures that make other gates unreachable come first.
37
+ */
38
+ export async function runConformance(root, versions, today) {
39
+ const context = await loadContext(root, versions)
40
+ const exceptions = await loadExceptions(root, today)
41
+
42
+ const raw = CHECKS.flatMap((check) => check(context))
43
+ const findings = []
44
+ const waived = []
45
+
46
+ for (const finding of raw) {
47
+ const waiver = exceptions.waived.get(finding.id)
48
+ if (waiver) waived.push({ ...finding, waiver })
49
+ else findings.push(finding)
50
+ }
51
+
52
+ return {
53
+ context,
54
+ waived,
55
+ findings: [...exceptions.findings, ...findings],
56
+ }
57
+ }
@@ -0,0 +1,432 @@
1
+ #!/usr/bin/env node
2
+ import { access, readFile } from 'node:fs/promises'
3
+ import { dirname, relative, resolve } from 'node:path'
4
+ import { cwd, exit } from 'node:process'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ import { applyFixes } from './conformance/applyFixes.mjs'
8
+ import { formatFindings } from './conformance/formatFindings.mjs'
9
+ import { runConformance } from './conformance/runConformance.mjs'
10
+ import { checkPeers } from './scaffold/checkPeers.mjs'
11
+ import { collectDeps } from './scaffold/collectDeps.mjs'
12
+ import { readManifest } from './scaffold/readManifest.mjs'
13
+ import { workspaceRoots } from './scaffold/workspaceRoots.mjs'
14
+ import { writeMissing } from './scaffold/writeMissing.mjs'
15
+
16
+ const __dirname = dirname(fileURLToPath(import.meta.url))
17
+ const PACKAGE_ROOT = resolve(__dirname, '..')
18
+
19
+ async function loadBaselineVersions() {
20
+ const path = resolve(PACKAGE_ROOT, 'baseline-versions.json')
21
+ const raw = await readFile(path, 'utf8')
22
+ return JSON.parse(raw)
23
+ }
24
+
25
+ function parseArgs(argv) {
26
+ const flags = {
27
+ check: false,
28
+ soft: false,
29
+ hard: false,
30
+ write: false,
31
+ fix: false,
32
+ }
33
+ for (const a of argv) {
34
+ if (a === '--check') flags.check = true
35
+ if (a === '--soft') flags.soft = true
36
+ if (a === '--hard') flags.hard = true
37
+ if (a === '--write') flags.write = true
38
+ if (a === '--fix') flags.fix = true
39
+ }
40
+ // --fix is --check that also repairs what it can, so it implies it. Without
41
+ // this a bare `--fix` would fall through to the default and report nothing.
42
+ if (flags.fix) flags.check = true
43
+ if (!flags.check && !flags.soft && !flags.hard && !flags.write) {
44
+ flags.soft = true
45
+ }
46
+ return flags
47
+ }
48
+
49
+ // In a monorepo the per-workspace packages - eslint-config, tsconfig,
50
+ // code-policy - are declared by each workspace, not by the root. Reading the
51
+ // root manifest alone reports every one of them missing and tells the adopter
52
+ // to install packages it already has, which is how intelifactu, a repo running
53
+ // the whole toolchain, was told it had none of it.
54
+ async function collectWorkspaceDeps(root) {
55
+ const deps = {}
56
+ for (const workspace of await workspaceRoots(root)) {
57
+ try {
58
+ Object.assign(deps, collectDeps(await readManifest(workspace)))
59
+ } catch {
60
+ /* a directory without a manifest is not a workspace */
61
+ }
62
+ }
63
+ return deps
64
+ }
65
+
66
+ function missingBaseline(deps, names) {
67
+ return names.filter((name) => deps[name] == null)
68
+ }
69
+
70
+ // Presets are consumable only by a project that owns its compiler options. A
71
+ // framework that generates them (Nuxt writes `.nuxt/tsconfig.json`, which the
72
+ // project's own tsconfig then extends) leaves this package no insertion point,
73
+ // so requiring the dependency there would only add one nothing reads - which
74
+ // the knip gate correctly reports as dead weight.
75
+ const TSCONFIG_PACKAGE = '@syntopica/tsconfig'
76
+
77
+ // A tsconfig inside a dot-directory is build output its framework regenerates,
78
+ // never a file anyone authored and never one that could extend a shared preset.
79
+ const GENERATED_TSCONFIG_PATH = /(?:^|\/)\.[^/]+\//
80
+
81
+ async function extendsGeneratedTsConfig(root) {
82
+ let raw
83
+ try {
84
+ // `root` is the directory this CLI was invoked against — reading its
85
+ // tsconfig is the tool's job, not untrusted input.
86
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
87
+ raw = await readFile(resolve(root, 'tsconfig.json'), 'utf8')
88
+ } catch {
89
+ return false
90
+ }
91
+ let parsed
92
+ try {
93
+ parsed = JSON.parse(raw)
94
+ } catch {
95
+ // JSONC (comments, trailing commas) is valid tsconfig input but not valid
96
+ // JSON. Treat an unreadable config as authored rather than generated, so
97
+ // an unparseable file never silently drops a requirement.
98
+ return false
99
+ }
100
+ const field = parsed.extends
101
+ const entries = Array.isArray(field) ? field : field == null ? [] : [field]
102
+ return entries.some((entry) => GENERATED_TSCONFIG_PATH.test(entry))
103
+ }
104
+
105
+ async function hasEslintConfig(root) {
106
+ const candidates = [
107
+ 'eslint.config.js',
108
+ 'eslint.config.mjs',
109
+ 'eslint.config.cjs',
110
+ 'eslint.config.ts',
111
+ ]
112
+ for (const f of candidates) {
113
+ try {
114
+ await access(resolve(root, f))
115
+ return true
116
+ } catch {
117
+ /* next */
118
+ }
119
+ }
120
+ return false
121
+ }
122
+
123
+ const QUALITY_CONFIG_FILES = [
124
+ 'knip.config.ts',
125
+ 'knip.config.js',
126
+ 'lefthook.yml',
127
+ 'renovate.json',
128
+ ]
129
+
130
+ async function missingQualityConfigs(root) {
131
+ const missing = []
132
+ for (const name of QUALITY_CONFIG_FILES) {
133
+ try {
134
+ await access(resolve(root, name))
135
+ } catch {
136
+ missing.push(name)
137
+ }
138
+ }
139
+ // knip.config.ts and knip.config.js are alternatives: only report the pair
140
+ // as missing if neither exists.
141
+ const hasKnipConfig =
142
+ !missing.includes('knip.config.ts') || !missing.includes('knip.config.js')
143
+ const report = missing.filter(
144
+ (name) => name !== 'knip.config.ts' && name !== 'knip.config.js',
145
+ )
146
+ if (!hasKnipConfig) report.unshift('knip.config.ts or knip.config.js')
147
+ return report
148
+ }
149
+
150
+ async function main() {
151
+ const versions = await loadBaselineVersions()
152
+ const names = Object.keys(versions)
153
+ const flags = parseArgs(process.argv.slice(2))
154
+ const root = cwd()
155
+
156
+ // pnpm refuses to add to a workspace root without -w (ERR_PNPM_ADDING_TO_ROOT),
157
+ // so a workspace repository must be handed a command that actually runs.
158
+ const isWorkspaceRoot = await access(
159
+ resolve(root, 'pnpm-workspace.yaml'),
160
+ ).then(
161
+ () => true,
162
+ () => false,
163
+ )
164
+
165
+ const printInstall = (required = names) => {
166
+ const spec = required.map((p) => `${p}@${versions[p]}`).join(' ')
167
+ console.log('pnpm (recommended):')
168
+ console.log(` pnpm add${isWorkspaceRoot ? ' -w' : ''} -D ${spec}`)
169
+ console.log('npm:')
170
+ console.log(` npm install -D ${spec}`)
171
+ }
172
+
173
+ let manifest = null
174
+ try {
175
+ manifest = await readManifest(root)
176
+ } catch {
177
+ if (flags.soft) {
178
+ console.log('@syntopica baseline — add these devDependencies:\n')
179
+ printInstall()
180
+ console.log(
181
+ '\n(No package.json in current directory; skipped dependency scan.)',
182
+ )
183
+ return
184
+ }
185
+ console.error('create-baseline: no package.json in current directory.')
186
+ exit(2)
187
+ }
188
+
189
+ // Workspace manifests first, so the root's own entry wins on a version clash
190
+ // and the report names the version the repo installs at its top level.
191
+ const deps = {
192
+ ...(await collectWorkspaceDeps(root)),
193
+ ...collectDeps(manifest),
194
+ }
195
+
196
+ // The ESLint peers the project's own config reaches for. pnpm reports a
197
+ // mismatch as one line on install; the consequence surfaces much later as a
198
+ // crash from inside ESLint that names neither the baseline nor the peer.
199
+ const reportPeers = async () => {
200
+ const peers = await checkPeers(root)
201
+ if (!peers) {
202
+ // A monorepo installs the config per workspace, not at the root, so each
203
+ // one carries its own peers and is checked on its own terms.
204
+ let checked = false
205
+ for (const workspace of await workspaceRoots(root)) {
206
+ const workspacePeers = await checkPeers(workspace)
207
+ if (!workspacePeers) continue
208
+ checked = true
209
+ printPeers(workspacePeers, relative(root, workspace))
210
+ }
211
+ if (checked) return
212
+ // The config is not installed yet, so there is nothing to compare
213
+ // against. Say so: silence here reads as "peers are fine", and the
214
+ // consequence is an opaque ESLint crash on the first lint run.
215
+ console.log(
216
+ '\nESLint peers: not verified. @syntopica/eslint-config is not ' +
217
+ 'installed here yet -- run the install above, then re-run this ' +
218
+ 'command to check them.',
219
+ )
220
+ return
221
+ }
222
+ printPeers(peers)
223
+ }
224
+
225
+ // One report per config location: the root in a single-package repo, each
226
+ // workspace in a monorepo. `where` labels which.
227
+ function printPeers({ missing, mismatched }, where) {
228
+ if (!missing.length && !mismatched.length) return
229
+ const scope = where ? ` in ${where}` : ''
230
+ console.log(`\nESLint peers this project's config needs${scope}:\n`)
231
+ for (const { name, range } of missing) {
232
+ console.log(` missing ${name} (${range})`)
233
+ }
234
+ for (const { name, range, version } of mismatched) {
235
+ console.log(` too old ${name} ${version} (needs ${range})`)
236
+ }
237
+ const spec = [...missing, ...mismatched]
238
+ .map(({ name, range }) => `${name}@${range.replace(/^>=/, '^')}`)
239
+ .join(' ')
240
+ console.log(`\n pnpm add -D ${spec}${where ? ` --filter ${where}` : ''}`)
241
+ console.log(
242
+ '\n@syntopica/eslint-config ships TypeScript source rather than a ' +
243
+ 'build, so these resolve from your project. A missing or too-old one ' +
244
+ 'fails ESLint before any rule runs.',
245
+ )
246
+ }
247
+
248
+ // --write scaffolds the wiring rather than describing it. Every adopting
249
+ // repo was hand-writing the same four files and the same ten scripts; the
250
+ // only thing that varied was the knip preset, which is read off the
251
+ // dependencies. Nothing that already exists is touched.
252
+ if (flags.write) {
253
+ const { framework, written, shadowed, scripts, workflow } =
254
+ await writeMissing(root, deps)
255
+ console.log(`create-baseline: detected framework \`${framework}\`.`)
256
+ if (written.length) console.log(` wrote: ${written.join(', ')}`)
257
+ if (scripts.length) console.log(` added scripts: ${scripts.join(', ')}`)
258
+ for (const [found, name] of shadowed) {
259
+ console.log(
260
+ `\n ${found} already configures this tool, so ${name} was not ` +
261
+ `written.\n The tool loads ${found} and would ignore ${name} ` +
262
+ 'even if both existed. Port it to the shared factory and delete ' +
263
+ `${found}.`,
264
+ )
265
+ }
266
+ if (workflow.existing) {
267
+ console.log(
268
+ `\n ${workflow.existing} already runs the baseline entrypoints, so ` +
269
+ 'no CI workflow was written.',
270
+ )
271
+ }
272
+ if (workflow.partial) {
273
+ console.log(
274
+ `\n ${workflow.partial.join(', ')} exist but none of them runs ` +
275
+ '`pnpm run check:ci`, so the gates have no trigger. No workflow was ' +
276
+ 'written: adding a second pipeline beside a working one would run ' +
277
+ 'every build twice. Add the three check:* steps to the existing ' +
278
+ 'workflow instead.',
279
+ )
280
+ }
281
+ if (!written.length && !scripts.length && !shadowed.length) {
282
+ console.log(' nothing to write; the wiring is already in place.')
283
+ }
284
+ const missingDeps = missingBaseline(deps, names)
285
+ if (missingDeps.length) {
286
+ console.log('\nStill missing from package.json:\n')
287
+ printInstall(missingDeps)
288
+ }
289
+ await reportPeers()
290
+ console.log(
291
+ '\nReview the generated files before committing: deps:graph scopes ' +
292
+ 'itself to `src`, and a project with e2e specs or hand-run scripts ' +
293
+ 'needs those declared as knip entry points.\n\n' +
294
+ (framework === 'nextjs'
295
+ ? 'If you also switch tsconfig.json to ' +
296
+ '@syntopica/tsconfig/nextjs, it sets `jsx: preserve` the way ' +
297
+ 'Next documents - SWC does the transform at build time. Vitest ' +
298
+ 'does not go through SWC, so every .tsx test fails to parse ' +
299
+ 'until its config names the runtime itself: `oxc: { jsx: { ' +
300
+ "runtime: 'automatic' } }` on Vite 8, which ignores the older " +
301
+ '`esbuild` block entirely.\n\n'
302
+ : '') +
303
+ 'If pnpm reports ERR_PNPM_IGNORED_BUILDS for lefthook, allow its ' +
304
+ 'install script - `lefthook: true` under `allowBuilds:` in ' +
305
+ 'pnpm-workspace.yaml - or the hooks never reach .git/hooks.',
306
+ )
307
+ return
308
+ }
309
+
310
+ const generatedTsConfig = await extendsGeneratedTsConfig(root)
311
+ const required = generatedTsConfig
312
+ ? names.filter((name) => name !== TSCONFIG_PACKAGE)
313
+ : names
314
+ const missing = missingBaseline(deps, required)
315
+ const eslintOk = await hasEslintConfig(root)
316
+ const missingQuality = await missingQualityConfigs(root)
317
+
318
+ if (flags.soft) {
319
+ console.log('@syntopica baseline — add these devDependencies:\n')
320
+ printInstall(required)
321
+ if (generatedTsConfig) {
322
+ console.log(
323
+ `\n(${TSCONFIG_PACKAGE} not required: this project's tsconfig extends a framework-generated config, which owns the compiler options.)`,
324
+ )
325
+ }
326
+ if (missing.length) {
327
+ console.log('\nMissing from package.json:', missing.join(', '))
328
+ } else {
329
+ console.log('\nAll baseline packages are already listed in package.json.')
330
+ }
331
+ if (!eslintOk) {
332
+ console.log(
333
+ '\nNo eslint.config.* found. Add a flat config that imports @syntopica/eslint-config (see https://github.com/BusiRocket/engineering-baseline/tree/main/docs/adoption).',
334
+ )
335
+ }
336
+ if (missingQuality.length) {
337
+ console.log(
338
+ '\nMissing quality-gate config:',
339
+ missingQuality.join(', '),
340
+ '(see @syntopica/quality-config and docs/adoption/new-repo.md).',
341
+ )
342
+ }
343
+ }
344
+
345
+ await reportPeers()
346
+
347
+ if (flags.check || flags.hard) {
348
+ let failed = false
349
+ if (missing.length) {
350
+ console.error(
351
+ 'create-baseline --check: missing packages:',
352
+ missing.join(', '),
353
+ )
354
+ failed = true
355
+ }
356
+ if (flags.hard && !eslintOk) {
357
+ console.error(
358
+ 'create-baseline --hard: expected eslint.config.js|mjs|cjs|ts in project root.',
359
+ )
360
+ failed = true
361
+ }
362
+ if (flags.hard && missingQuality.length) {
363
+ console.error(
364
+ 'create-baseline --hard: missing quality-gate config:',
365
+ missingQuality.join(', '),
366
+ )
367
+ failed = true
368
+ }
369
+ if (failed) {
370
+ // Only what is actually missing. Printing the full baseline reads as
371
+ // "you have none of this" to a project that has all but one of it, and
372
+ // pasting the line re-pins ten packages nobody asked to touch.
373
+ printInstall(missing.length ? missing : required)
374
+ exit(1)
375
+ }
376
+
377
+ // Presence was never the interesting question. This command reported
378
+ // "checks OK" for a repository with no CI, a `lint` that ignored warnings
379
+ // and a `check:ci` that skipped four gates, because all it ever asserted
380
+ // was that four packages appeared in package.json. Everything below
381
+ // asserts that the gates those packages provide are actually invoked.
382
+ const report = await runConformance(root, versions, today())
383
+
384
+ if (flags.fix) {
385
+ const applied = await applyFixes(root, report.findings)
386
+ if (applied.length) {
387
+ console.log('create-baseline --fix applied:')
388
+ for (const change of applied) console.log(` ${change}`)
389
+ console.log(
390
+ '\nRe-run `create-baseline --check` to see what is left. Anything ' +
391
+ 'still reported needs a decision this tool does not have.',
392
+ )
393
+ } else {
394
+ console.log('create-baseline --fix: nothing was mechanically fixable.')
395
+ }
396
+ // The report was computed before the edits, so it describes the state
397
+ // that has just been changed. Exiting on it would fail a run that has
398
+ // repaired everything it was asked to.
399
+ return
400
+ }
401
+
402
+ const errors = report.findings.filter((f) => f.level === 'error')
403
+ if (report.findings.length) {
404
+ console.log(
405
+ `\ncreate-baseline --check: ${errors.length} error(s), ` +
406
+ `${report.findings.length - errors.length} warning(s).\n`,
407
+ )
408
+ console.log(formatFindings(report))
409
+ console.log(
410
+ '\nWaive a finding by id in baseline.exceptions.json, with a reason ' +
411
+ 'and optionally an `expires` date:\n' +
412
+ ' { "gate:knip": { "reason": "...", "expires": "2026-12-31" } }',
413
+ )
414
+ }
415
+ if (errors.length) exit(1)
416
+ console.log('create-baseline: baseline packages and wiring OK.')
417
+ }
418
+ }
419
+
420
+ // Injected rather than read inside the exception loader so the whole
421
+ // conformance suite stays a pure function of its inputs, which is what makes
422
+ // it testable without freezing a clock.
423
+ function today() {
424
+ return new Date().toISOString().slice(0, 10)
425
+ }
426
+
427
+ try {
428
+ await main()
429
+ } catch (err) {
430
+ console.error(err)
431
+ exit(1)
432
+ }
@@ -0,0 +1,46 @@
1
+ import { readdir } from 'node:fs/promises'
2
+ import { resolve } from 'node:path'
3
+
4
+ import { collectDeps } from '../scaffold/collectDeps.mjs'
5
+ import { readManifest } from '../scaffold/readManifest.mjs'
6
+
7
+ const BASELINE_SCOPE = '@syntopica/'
8
+
9
+ /**
10
+ * Every directory under `root` that depends on a baseline package.
11
+ *
12
+ * One level deep, which is how a projects folder is actually laid out. The
13
+ * alternative - walking the tree - spends most of its time inside
14
+ * `node_modules` finding the baseline packages themselves.
15
+ *
16
+ * Returns `[{ name, path, deps }]` sorted by name, so two runs of the estate
17
+ * report are diffable.
18
+ */
19
+ export async function findConsumers(root) {
20
+ let entries
21
+ try {
22
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
23
+ entries = await readdir(root, { withFileTypes: true })
24
+ } catch {
25
+ return []
26
+ }
27
+
28
+ const consumers = []
29
+ for (const entry of entries) {
30
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue
31
+ const path = resolve(root, entry.name)
32
+ let manifest
33
+ try {
34
+ manifest = await readManifest(path)
35
+ } catch {
36
+ continue
37
+ }
38
+ const deps = collectDeps(manifest)
39
+ if (!Object.keys(deps).some((name) => name.startsWith(BASELINE_SCOPE))) {
40
+ continue
41
+ }
42
+ consumers.push({ name: entry.name, path, deps })
43
+ }
44
+
45
+ return consumers.sort((a, b) => a.name.localeCompare(b.name))
46
+ }
@@ -0,0 +1,58 @@
1
+ import { readdir, readFile } from 'node:fs/promises'
2
+ import { relative, resolve } from 'node:path'
3
+
4
+ const TOOL = 'busirocket-baseline-py'
5
+ // The tool's own pyproject names it too; a package is not its own consumer.
6
+ const IS_THE_TOOL = /^name = "busirocket-baseline-py"/m
7
+ // Directories that never hold a project of ours, and would make the walk
8
+ // slow (node_modules), circular (.venv) or pointless (a build tree).
9
+ const SKIP = new Set(['node_modules', 'build', 'dist', 'target'])
10
+ const MAX_DEPTH = 3
11
+
12
+ /**
13
+ * Every project under `root` whose pyproject.toml depends on baseline-py.
14
+ *
15
+ * Three levels deep, unlike `findConsumers`: the estate sweep proved that a
16
+ * Python project is often nested inside a repository that is about something
17
+ * else - `DMX-Fixtures/tools/qlctool`, `esp32-amoled/clawd-pet` - and a scan
18
+ * of repository roots reported those as having no Python at all.
19
+ *
20
+ * Returns `[{ name, path }]` sorted by name; `name` is the path relative to
21
+ * `root`, so a nested project is reported where it lives.
22
+ */
23
+ export async function findPythonConsumers(root) {
24
+ const consumers = []
25
+ await walk(root, root, 0, consumers)
26
+ return consumers.sort((a, b) => a.name.localeCompare(b.name))
27
+ }
28
+
29
+ async function walk(root, dir, depth, consumers) {
30
+ if (depth > MAX_DEPTH) return
31
+ let entries
32
+ try {
33
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
34
+ entries = await readdir(dir, { withFileTypes: true })
35
+ } catch {
36
+ return
37
+ }
38
+ if (depth > 0 && (await dependsOnTool(dir))) {
39
+ consumers.push({ name: relative(root, dir), path: dir })
40
+ return
41
+ }
42
+ for (const entry of entries) {
43
+ if (!entry.isDirectory()) continue
44
+ if (entry.name.startsWith('.') || entry.name.startsWith('_')) continue
45
+ if (SKIP.has(entry.name)) continue
46
+ await walk(root, resolve(dir, entry.name), depth + 1, consumers)
47
+ }
48
+ }
49
+
50
+ async function dependsOnTool(dir) {
51
+ try {
52
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
53
+ const text = await readFile(resolve(dir, 'pyproject.toml'), 'utf8')
54
+ return text.includes(TOOL) && !IS_THE_TOOL.test(text)
55
+ } catch {
56
+ return false
57
+ }
58
+ }