@dcaldeira/tooling 0.0.0-stage → 0.2.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 (56) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +33 -2
  3. package/checks/a11y.mjs +206 -0
  4. package/checks/architecture.mjs +137 -0
  5. package/checks/audit.mjs +121 -0
  6. package/checks/bundle.mjs +126 -0
  7. package/checks/dependencies.mjs +277 -0
  8. package/checks/duplication.mjs +135 -0
  9. package/checks/lint-scss.mjs +363 -0
  10. package/checks/package.mjs +30 -0
  11. package/checks/playwright-summary.mjs +53 -0
  12. package/checks/sass.mjs +67 -0
  13. package/checks/scan-secrets.mjs +58 -0
  14. package/checks/shared.mjs +86 -0
  15. package/checks/style-property-order.json +498 -0
  16. package/checks/translations.mjs +55 -0
  17. package/checks/visual-compare.mjs +148 -0
  18. package/checks/visual-report-html.mjs +470 -0
  19. package/checks/visual-report.mjs +13 -0
  20. package/config.schema.json +977 -0
  21. package/configs/eslint.mjs +27 -0
  22. package/configs/knip.json +11 -0
  23. package/configs/playwright.mjs +15 -0
  24. package/configs/prettier.mjs +1 -0
  25. package/configs/tsconfig.json +16 -0
  26. package/configs/vitest.mjs +16 -0
  27. package/package.json +103 -4
  28. package/release/evidence.mjs +62 -0
  29. package/release/finalize.mjs +65 -0
  30. package/release/gh.mjs +25 -0
  31. package/release/github.mjs +64 -0
  32. package/release/prepare.mjs +30 -0
  33. package/runner/browsers.mjs +73 -0
  34. package/runner/cache.mjs +121 -0
  35. package/runner/ci-plan.mjs +54 -0
  36. package/runner/cli.mjs +251 -0
  37. package/runner/config.mjs +148 -0
  38. package/runner/docs-install.mjs +93 -0
  39. package/runner/execute.mjs +298 -0
  40. package/runner/generate.mjs +122 -0
  41. package/runner/git.mjs +122 -0
  42. package/runner/graph.mjs +250 -0
  43. package/runner/index.mjs +4 -0
  44. package/runner/insights.mjs +313 -0
  45. package/runner/provision.mjs +53 -0
  46. package/runner/repo-standard.mjs +104 -0
  47. package/runner/report.mjs +35 -0
  48. package/runner/serve-static.mjs +76 -0
  49. package/runner/setup.mjs +241 -0
  50. package/runner/summary.mjs +112 -0
  51. package/runner/watch.mjs +82 -0
  52. package/templates/ci.yml +25 -0
  53. package/templates/dependabot-merge.yml +13 -0
  54. package/templates/dependabot.yml +26 -0
  55. package/templates/pre-push +13 -0
  56. package/templates/release.yml +23 -0
@@ -0,0 +1,54 @@
1
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { join } from 'node:path';
5
+ import { browserChecks } from './browsers.mjs';
6
+ import { inside, loadConfig } from './config.mjs';
7
+
8
+ export function planMetadata(root, selection, config, lock = {}) {
9
+ const active = Boolean(selection.checks.length || selection.excluded.length);
10
+ const browsers = browserChecks(selection).length > 0;
11
+ const versions = Object.entries(lock.packages ?? {})
12
+ .filter(([path]) => /node_modules\/(?:@playwright\/test|playwright(?:-core)?)$/.test(path))
13
+ .map(([path, entry]) => [path, entry.version]);
14
+ const paths = ['.tooling/cache/eslint/'];
15
+ for (const path of config.execution?.typeScriptBuildInfo ?? []) {
16
+ inside(root, path);
17
+ if (/[\r\n]/.test(path) || !path.endsWith('.tsbuildinfo'))
18
+ throw new Error('TypeScript cache paths must be repository-relative .tsbuildinfo patterns');
19
+ paths.push(path);
20
+ }
21
+ return {
22
+ active: String(active),
23
+ browsers: String(browsers),
24
+ history: String(config.history?.enabled !== false),
25
+ 'browser-key': createHash('sha256')
26
+ .update(JSON.stringify(versions.sort()))
27
+ .digest('hex')
28
+ .slice(0, 20),
29
+ 'tool-cache-paths': paths.join('\n'),
30
+ };
31
+ }
32
+
33
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
34
+ const root = process.cwd();
35
+ const selection = JSON.parse(readFileSync(process.argv[2], 'utf8'));
36
+ const { config } = loadConfig(root, process.env.CONFIG ?? 'tooling.config.json');
37
+ const lockPath = join(root, 'package-lock.json');
38
+ const metadata = planMetadata(
39
+ root,
40
+ selection,
41
+ config,
42
+ existsSync(lockPath) ? JSON.parse(readFileSync(lockPath, 'utf8')) : {},
43
+ );
44
+ for (const [name, value] of Object.entries(metadata)) {
45
+ const delimiter = `tooling_${randomUUID()}`;
46
+ if (process.env.GITHUB_OUTPUT)
47
+ appendFileSync(process.env.GITHUB_OUTPUT, `${name}<<${delimiter}\n${value}\n${delimiter}\n`);
48
+ }
49
+ console.log(
50
+ metadata.active === 'true'
51
+ ? 'Plan requires validation'
52
+ : 'Empty plan: installation and validation skipped',
53
+ );
54
+ }
package/runner/cli.mjs ADDED
@@ -0,0 +1,251 @@
1
+ #!/usr/bin/env node
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { watchChanges } from './watch.mjs';
5
+ import { loadConfig } from './config.mjs';
6
+ import { changedFiles, clean, git, captureSnapshot } from './git.mjs';
7
+ import { checkCache } from './cache.mjs';
8
+ import { plan } from './graph.mjs';
9
+ import { execute, invoke } from './execute.mjs';
10
+ import { writeReport } from './report.mjs';
11
+ import { setupCommand } from './setup.mjs';
12
+ import { generateCommand } from './generate.mjs';
13
+ import { collectMetrics, historyText, performanceHistory } from './insights.mjs';
14
+ import { createHash } from 'node:crypto';
15
+
16
+ const version = JSON.parse(
17
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
18
+ ).version;
19
+ const args = process.argv.slice(2);
20
+ const subcommand = ['init', 'doctor', 'generate', 'history'].includes(args[0])
21
+ ? args.shift()
22
+ : undefined;
23
+ const generator = subcommand === 'generate' ? args.shift() : undefined;
24
+ const valueFlags =
25
+ subcommand === 'generate'
26
+ ? ['cwd', 'config', 'name', 'path']
27
+ : subcommand === 'history'
28
+ ? ['cwd', 'limit']
29
+ : subcommand === 'init'
30
+ ? ['cwd', 'preset', 'app', 'tooling-sha']
31
+ : subcommand === 'doctor'
32
+ ? ['cwd', 'config']
33
+ : ['profile', 'base', 'head', 'config', 'only', 'skip', 'output', 'cwd', 'concurrency'];
34
+ const boolFlags =
35
+ subcommand === 'generate'
36
+ ? ['dry-run', 'design-system']
37
+ : subcommand === 'doctor'
38
+ ? ['repo-standard']
39
+ : subcommand
40
+ ? []
41
+ : ['changed', 'all', 'bail', 'install', 'plan', 'watch', 'committed', 'no-cache'];
42
+ const options = {};
43
+ for (let i = 0; i < args.length; i++) {
44
+ const [flag, ...tail] = args[i].replace(/^--/, '').split('=');
45
+ if (!args[i].startsWith('--') || ![...valueFlags, ...boolFlags].includes(flag))
46
+ throw new Error(`Unknown argument: ${args[i]}`);
47
+ if (boolFlags.includes(flag)) {
48
+ if (tail.length) throw new Error(`--${flag} takes no value`);
49
+ options[flag] = true;
50
+ } else {
51
+ options[flag] = tail.length ? tail.join('=') : args[++i];
52
+ if (!options[flag] || options[flag].startsWith('--'))
53
+ throw new Error(`--${flag} needs a value`);
54
+ }
55
+ }
56
+ if (options.all && options.changed) throw new Error('Choose --all or --changed');
57
+ if (options.watch && options.profile !== 'dev') throw new Error('--watch requires --profile=dev');
58
+ if (options.head && !options.committed) throw new Error('--head requires --committed');
59
+ const root = resolve(options.cwd ?? process.cwd());
60
+ const state = join(root, '.tooling', 'state');
61
+ const output = resolve(root, options.output ?? '.tooling/report');
62
+ const list = (key) => options[key]?.split(',').filter(Boolean) ?? [];
63
+ const profile = options.profile ?? 'ci';
64
+ if (
65
+ options.concurrency !== undefined &&
66
+ (!/^\d+$/.test(options.concurrency) ||
67
+ Number(options.concurrency) < 1 ||
68
+ Number(options.concurrency) > 16)
69
+ )
70
+ throw new Error('--concurrency must be an integer between 1 and 16');
71
+
72
+ async function run() {
73
+ const started = Date.now();
74
+ const { config, raw } = loadConfig(root, options.config);
75
+ let base = options.base ?? (profile === 'dev' ? 'HEAD' : undefined);
76
+ if (!base) {
77
+ try {
78
+ base = git(root, 'rev-parse', 'origin/main');
79
+ } catch {
80
+ if (options.changed) throw new Error('No origin/main: pass --base=<revision> or --all');
81
+ base = 'HEAD';
82
+ }
83
+ }
84
+ base = git(root, 'rev-parse', `${base}^{commit}`);
85
+ if (profile === 'push') {
86
+ if (options.committed || options.head)
87
+ throw new Error('Push validation must include the current worktree');
88
+ let expectedBase;
89
+ try {
90
+ expectedBase = git(root, 'rev-parse', 'origin/main^{commit}');
91
+ } catch {}
92
+ if (!options.all && (!expectedBase || expectedBase !== base))
93
+ throw new Error('Push validation must use current origin/main, or --all without a remote');
94
+ }
95
+ const files =
96
+ !options.all && (options.changed || options.base)
97
+ ? changedFiles(root, base, { committed: options.committed, head: options.head ?? 'HEAD' })
98
+ : 'all';
99
+ const selection = plan(config, { files, profile, only: list('only'), skip: list('skip') });
100
+ if (options.plan) {
101
+ console.log(JSON.stringify(selection, null, 2));
102
+ return true;
103
+ }
104
+ if (!selection.checks.length && !selection.excluded.length) {
105
+ console.log('No applicable checks; nothing to install or validate.');
106
+ if (profile === 'push' && !clean(root)) {
107
+ console.error('No pass recorded: commit all tracked and untracked files first.');
108
+ return false;
109
+ }
110
+ return true;
111
+ }
112
+ if (options.install) {
113
+ const result = await invoke(['npm', 'ci', '--ignore-scripts'], root);
114
+ if (result.status !== 'passed') throw new Error('Dependency installation failed');
115
+ }
116
+ const context = {
117
+ base,
118
+ version,
119
+ config: raw,
120
+ environment: config.environment,
121
+ inputs: [
122
+ ...new Set([
123
+ ...(config.inputs ?? []),
124
+ ...(config.a11y?.storageState ? [config.a11y.storageState] : []),
125
+ ...selection.checks
126
+ .filter((c) => c.cwd)
127
+ .map((c) => join(c.cwd, 'node_modules/.package-lock.json')),
128
+ ]),
129
+ ],
130
+ tools: [
131
+ ...new Map(
132
+ selection.checks.flatMap((check) =>
133
+ [...(check.tools ?? []), ...(Array.isArray(check.command) ? [check.command[0]] : [])].map(
134
+ (name) => [`${check.cwd ?? '.'}\0${name}`, { name, cwd: check.cwd ?? '.' }],
135
+ ),
136
+ ),
137
+ ).values(),
138
+ ],
139
+ };
140
+ const captured = captureSnapshot(root, context);
141
+ const before = captured.fingerprint;
142
+ const cache = checkCache(root, config, selection, captured, {
143
+ disabled: options['no-cache'] || options.all,
144
+ });
145
+ const passPath = join(state, 'push-pass.json');
146
+ const checkKey = JSON.stringify(selection.checks.map((check) => check.id));
147
+ let cached;
148
+ try {
149
+ cached = JSON.parse(readFileSync(passPath, 'utf8'));
150
+ } catch {}
151
+ if (
152
+ profile === 'push' &&
153
+ cache.reusablePass &&
154
+ !options['no-cache'] &&
155
+ clean(root) &&
156
+ cached?.fingerprint === before &&
157
+ cached?.base === base &&
158
+ cached?.checks === checkKey &&
159
+ !selection.excluded.length &&
160
+ !list('only').length
161
+ ) {
162
+ console.log('Pass recorded: matching commit, base, tooling, configuration and inputs.');
163
+ return true;
164
+ }
165
+ process.env.TOOLING_CONFIG_PATH = options.config ?? 'tooling.config.json';
166
+ process.env.TOOLING_REPORT_DIR = output;
167
+ process.env.TOOLING_COMMIT = git(root, 'rev-parse', 'HEAD');
168
+ process.env.TOOLING_VERSION = version;
169
+ const result = await execute(root, selection, {
170
+ cache,
171
+ toolCache: !options['no-cache'],
172
+ bail: options.bail,
173
+ concurrency:
174
+ options.concurrency !== undefined
175
+ ? Number(options.concurrency)
176
+ : config.execution?.concurrency,
177
+ });
178
+ const after = captureSnapshot(root, context).fingerprint;
179
+ if (before !== after) {
180
+ result.complete = false;
181
+ result.results.push({
182
+ id: 'inputs',
183
+ status: 'unavailable',
184
+ reason: 'Inputs changed during validation',
185
+ });
186
+ } else cache.commit(result.results);
187
+ const report = {
188
+ schemaVersion: 1,
189
+ version,
190
+ profile,
191
+ groups: selection.groups,
192
+ affectedWorkspaces: selection.affectedWorkspaces,
193
+ required: selection.required,
194
+ commit: git(root, 'rev-parse', 'HEAD'),
195
+ base,
196
+ tree: git(root, 'rev-parse', 'HEAD^{tree}'),
197
+ fingerprint: before,
198
+ finishedAt: new Date().toISOString(),
199
+ startedAt: new Date(started).toISOString(),
200
+ wallMilliseconds: Date.now() - started,
201
+ node: process.version,
202
+ platform: process.platform,
203
+ configuration: createHash('sha256').update(raw).digest('hex'),
204
+ ...result,
205
+ };
206
+ report.metrics = collectMetrics(root, output, report, config.reporting);
207
+ report.performance = performanceHistory(root, report, config.history);
208
+ writeReport(output, report);
209
+ for (const r of report.results)
210
+ console.log(`${r.status.padEnd(11)} ${r.id}${r.reason ? `: ${r.reason}` : ''}`);
211
+ console.log(`Report: ${join(output, 'index.html')}`);
212
+ if (profile === 'push' && result.complete) {
213
+ if (!clean(root)) {
214
+ console.error('No pass recorded: commit all tracked and untracked files first.');
215
+ return false;
216
+ }
217
+ mkdirSync(state, { recursive: true });
218
+ writeFileSync(passPath, JSON.stringify({ fingerprint: before, base, checks: checkKey }));
219
+ console.log('Pass recorded');
220
+ }
221
+ return result.complete;
222
+ }
223
+
224
+ try {
225
+ if (subcommand === 'generate') process.exitCode = generateCommand(root, generator, options);
226
+ else if (subcommand === 'history') {
227
+ const limit = options.limit === undefined ? 20 : Number(options.limit);
228
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
229
+ throw new Error('--limit must be between 1 and 1000');
230
+ console.log(historyText(root, limit));
231
+ } else if (subcommand) process.exitCode = await setupCommand(subcommand, root, options);
232
+ else if (!options.watch) process.exitCode = (await run()) ? 0 : 1;
233
+ else {
234
+ const controller = new AbortController();
235
+ const stop = () => controller.abort();
236
+ process.once('SIGINT', stop);
237
+ process.once('SIGTERM', stop);
238
+ try {
239
+ await watchChanges(root, run, {
240
+ signal: controller.signal,
241
+ inputs: () => loadConfig(root, options.config).config.inputs ?? [],
242
+ });
243
+ } finally {
244
+ process.removeListener('SIGINT', stop);
245
+ process.removeListener('SIGTERM', stop);
246
+ }
247
+ }
248
+ } catch (error) {
249
+ console.error(error.message);
250
+ process.exitCode = 2;
251
+ }
@@ -0,0 +1,148 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { isAbsolute, relative, resolve } from 'node:path';
3
+
4
+ const schema = JSON.parse(readFileSync(new URL('../config.schema.json', import.meta.url), 'utf8'));
5
+ export const defaults = {
6
+ docs: ['docs/**', '**/*.md', '**/*.mdx'],
7
+ styles: ['**/*.scss', '**/*.css'],
8
+ translations: ['**/locales/*.json'],
9
+ app: ['src/**'],
10
+ database: [],
11
+ functions: [],
12
+ workflows: ['.github/workflows/**'],
13
+ tooling: ['tooling.config.json', '*config*', 'scripts/**', '.githooks/**'],
14
+ dependencies: ['**/package.json', '**/package-lock.json', '**/npm-shrinkwrap.json'],
15
+ };
16
+ export const inside = (root, path) => {
17
+ const target = resolve(root, path);
18
+ const rel = relative(root, target);
19
+ if (rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || isAbsolute(rel))
20
+ throw new Error(`Path outside repository: ${path}`);
21
+ return target;
22
+ };
23
+
24
+ // Interpret the keywords used by our bundled schema without adding dependencies to the planner.
25
+ function validate(value, rule, path) {
26
+ const fail = (message) => {
27
+ throw new Error(`${path}: ${message}`);
28
+ };
29
+ if (rule.oneOf) {
30
+ let matches = 0;
31
+ for (const option of rule.oneOf) {
32
+ try {
33
+ validate(value, option, path);
34
+ matches++;
35
+ } catch {}
36
+ }
37
+ if (matches !== 1) fail('must match exactly one allowed shape');
38
+ }
39
+ if ('const' in rule && value !== rule.const) fail(`must be ${rule.const}`);
40
+ if (rule.enum && !rule.enum.includes(value)) fail(`must be one of ${rule.enum.join(', ')}`);
41
+ if (rule.type) {
42
+ const valid =
43
+ rule.type === 'object'
44
+ ? value !== null && typeof value === 'object' && !Array.isArray(value)
45
+ : rule.type === 'array'
46
+ ? Array.isArray(value)
47
+ : rule.type === 'integer'
48
+ ? Number.isInteger(value)
49
+ : rule.type === 'number'
50
+ ? typeof value === 'number' && Number.isFinite(value)
51
+ : typeof value === rule.type;
52
+ if (!valid) fail(`must be ${rule.type}`);
53
+ }
54
+ if (typeof value === 'string') {
55
+ if (rule.minLength !== undefined && value.length < rule.minLength) fail('must not be empty');
56
+ if (rule.pattern && !new RegExp(rule.pattern).test(value)) fail('invalid name');
57
+ }
58
+ if (typeof value === 'number') {
59
+ if (rule.minimum !== undefined && value < rule.minimum) fail(`must be >= ${rule.minimum}`);
60
+ if (rule.maximum !== undefined && value > rule.maximum) fail(`must be <= ${rule.maximum}`);
61
+ if (rule.exclusiveMinimum !== undefined && value <= rule.exclusiveMinimum)
62
+ fail(`must be > ${rule.exclusiveMinimum}`);
63
+ }
64
+ if (Array.isArray(value)) {
65
+ if (rule.minItems !== undefined && value.length < rule.minItems) fail('too few items');
66
+ if (rule.maxItems !== undefined && value.length > rule.maxItems) fail('too many items');
67
+ value.forEach((item, i) => {
68
+ const itemRule = rule.prefixItems?.[i] ?? rule.items;
69
+ if (itemRule) validate(item, itemRule, `${path}[${i}]`);
70
+ });
71
+ } else if (value !== null && typeof value === 'object') {
72
+ for (const key of rule.required ?? []) if (!Object.hasOwn(value, key)) fail(`missing ${key}`);
73
+ for (const [key, child] of Object.entries(value)) {
74
+ if (rule.propertyNames) validate(key, rule.propertyNames, `${path}.${key}`);
75
+ const childRule = rule.properties?.[key];
76
+ if (childRule) validate(child, childRule, `${path}.${key}`);
77
+ else if (rule.additionalProperties === false) fail(`unknown key ${key}`);
78
+ else if (rule.additionalProperties && typeof rule.additionalProperties === 'object')
79
+ validate(child, rule.additionalProperties, `${path}.${key}`);
80
+ }
81
+ }
82
+ }
83
+
84
+ export function validateConfig(value) {
85
+ validate(value, schema, 'config');
86
+ const layers = value.architecture?.layers ?? [];
87
+ if (new Set(layers.map((layer) => layer.name)).size !== layers.length)
88
+ throw new Error('Architecture layer names must be unique');
89
+ for (const layer of layers)
90
+ for (const name of layer.allow)
91
+ if (!layers.some((candidate) => candidate.name === name))
92
+ throw new Error(`Unknown architecture layer: ${name}`);
93
+ for (const route of value.a11y?.routes ?? [])
94
+ for (const action of route.actions ?? [])
95
+ if (['fill', 'press'].includes(action.type) && action.value === undefined)
96
+ throw new Error(`Accessibility action ${action.type} requires value`);
97
+ for (const url of [value.a11y?.baseURL, value.a11y?.server?.url].filter(Boolean))
98
+ if (!['http:', 'https:'].includes(new URL(url).protocol))
99
+ throw new Error('Accessibility URLs must use HTTP or HTTPS');
100
+ for (const path of value.execution?.typeScriptBuildInfo ?? [])
101
+ if (/[\r\n]/.test(path) || !path.endsWith('.tsbuildinfo'))
102
+ throw new Error('TypeScript cache paths must be .tsbuildinfo patterns');
103
+ for (const [id, check] of Object.entries(value.checks ?? {})) {
104
+ if (check && check.devFiles && check.devCommand && !Array.isArray(check.devCommand))
105
+ throw new Error(`Changed-file command ${id} must be an array`);
106
+ }
107
+ return value;
108
+ }
109
+
110
+ export function loadConfig(root, path = process.env.TOOLING_CONFIG_PATH ?? 'tooling.config.json') {
111
+ const raw = readFileSync(inside(root, path), 'utf8');
112
+ const config = validateConfig(JSON.parse(raw));
113
+ const paths = [
114
+ ...(config.inputs ?? []),
115
+ ...(config.sass?.entrypoints ?? []),
116
+ ...(config.sass?.include ?? []),
117
+ ...(config.sass?.exclude ?? []),
118
+ ...(config.sass?.importantExceptions ?? []),
119
+ ...(config.sass?.source ? [config.sass.source] : []),
120
+ ...(config.execution?.typeScriptBuildInfo ?? []),
121
+ ...(config.architecture?.include ?? []),
122
+ ...(config.architecture?.exclude ?? []),
123
+ ...(config.architecture?.tsconfig ? [config.architecture.tsconfig] : []),
124
+ ...(config.architecture?.modules ?? []).flatMap((module) => [module.root, ...module.public]),
125
+ ...(config.architecture?.layers ?? []).flatMap((layer) => layer.paths),
126
+ ...(config.dependencyConsistency?.manifests ?? []),
127
+ ...(config.dependencyConsistency?.include ?? []),
128
+ ...(config.dependencyConsistency?.exclude ?? []),
129
+ ...[
130
+ config.generators?.components,
131
+ config.generators?.hooks,
132
+ config.a11y?.storageState,
133
+ config.a11y?.server?.cwd,
134
+ ].filter(Boolean),
135
+ ...(config.reporting?.unit ?? []),
136
+ ...(config.reporting?.coverage ?? []),
137
+ ...(config.reporting?.playwright ?? []),
138
+ ...Object.values(config.workspaces ?? {}).flatMap((workspace) => workspace.paths),
139
+ ...Object.values(config.checks ?? {})
140
+ .filter(Boolean)
141
+ .flatMap((check) => [
142
+ ...(check.cwd !== undefined ? [check.cwd] : []),
143
+ ...(typeof check.cache === 'object' ? check.cache.inputs : []),
144
+ ]),
145
+ ];
146
+ paths.forEach((path) => inside(root, path));
147
+ return { config, raw };
148
+ }
@@ -0,0 +1,93 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readFileSync,
5
+ writeFileSync,
6
+ symlinkSync,
7
+ appendFileSync,
8
+ } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { invoke } from './execute.mjs';
12
+
13
+ export function formatterLock(root, selection) {
14
+ if (
15
+ selection.groups.length !== 1 ||
16
+ selection.groups[0] !== 'docs' ||
17
+ selection.checks.length !== 1 ||
18
+ selection.checks[0].id !== 'format' ||
19
+ selection.checks[0].excluded ||
20
+ selection.excluded.length ||
21
+ selection.checks[0].cwd ||
22
+ JSON.stringify(selection.checks[0].command) !== JSON.stringify(['prettier', '--check', '.'])
23
+ )
24
+ return null;
25
+ const lock = JSON.parse(readFileSync(join(root, 'package-lock.json'), 'utf8'));
26
+ const entry = lock.packages?.['node_modules/prettier'];
27
+ if (
28
+ !entry?.version ||
29
+ !entry.integrity ||
30
+ !entry.resolved ||
31
+ entry.link ||
32
+ Object.keys(entry.dependencies ?? {}).length ||
33
+ Object.keys(entry.optionalDependencies ?? {}).length ||
34
+ Object.keys(entry.peerDependencies ?? {}).length
35
+ )
36
+ return null;
37
+ return {
38
+ name: 'tooling-docs',
39
+ version: '1.0.0',
40
+ lockfileVersion: 3,
41
+ requires: true,
42
+ packages: {
43
+ '': { name: 'tooling-docs', version: '1.0.0', devDependencies: { prettier: entry.version } },
44
+ 'node_modules/prettier': { ...entry, dev: true, devOptional: undefined },
45
+ },
46
+ };
47
+ }
48
+
49
+ export async function installFormatter(root, lock) {
50
+ const directory = join(root, '.tooling', 'formatter');
51
+ mkdirSync(directory, { recursive: true });
52
+ writeFileSync(
53
+ join(directory, 'package.json'),
54
+ JSON.stringify({
55
+ name: lock.name,
56
+ version: lock.version,
57
+ private: true,
58
+ devDependencies: lock.packages[''].devDependencies,
59
+ }),
60
+ );
61
+ writeFileSync(join(directory, 'package-lock.json'), JSON.stringify(lock));
62
+ const result = await invoke(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], root, {
63
+ cwd: directory,
64
+ });
65
+ if (result.status !== 'passed') throw new Error('Formatter installation failed');
66
+ const links = [
67
+ [join(root, 'node_modules/prettier'), join(directory, 'node_modules/prettier')],
68
+ [join(root, 'node_modules/@dcaldeira/tooling'), fileURLToPath(new URL('../', import.meta.url))],
69
+ ];
70
+ for (const [target, source] of links) {
71
+ if (existsSync(target)) throw new Error(`Refusing to replace ${target}`);
72
+ mkdirSync(dirname(target), { recursive: true });
73
+ symlinkSync(source, target, process.platform === 'win32' ? 'junction' : 'dir');
74
+ }
75
+ }
76
+
77
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
78
+ const root = process.cwd();
79
+ const selection = JSON.parse(readFileSync(resolve(process.argv[2]), 'utf8'));
80
+ const lock = formatterLock(root, selection);
81
+ if (process.argv.includes('--plan')) {
82
+ if (process.env.GITHUB_OUTPUT)
83
+ appendFileSync(process.env.GITHUB_OUTPUT, `lightweight=${Boolean(lock)}\n`);
84
+ console.log(
85
+ lock
86
+ ? 'Standalone formatter installation available'
87
+ : 'Full dependency installation required',
88
+ );
89
+ } else {
90
+ if (!lock) throw new Error('This plan requires the full project installation');
91
+ await installFormatter(root, lock);
92
+ }
93
+ }