@dcaldeira/tooling 0.1.0 → 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 (49) hide show
  1. package/README.md +34 -34
  2. package/checks/a11y.mjs +206 -206
  3. package/checks/architecture.mjs +137 -137
  4. package/checks/audit.mjs +121 -121
  5. package/checks/bundle.mjs +126 -126
  6. package/checks/dependencies.mjs +277 -277
  7. package/checks/duplication.mjs +135 -0
  8. package/checks/lint-scss.mjs +363 -349
  9. package/checks/package.mjs +30 -30
  10. package/checks/playwright-summary.mjs +53 -53
  11. package/checks/sass.mjs +67 -67
  12. package/checks/scan-secrets.mjs +58 -58
  13. package/checks/shared.mjs +86 -86
  14. package/checks/translations.mjs +55 -55
  15. package/checks/visual-compare.mjs +148 -148
  16. package/checks/visual-report-html.mjs +470 -470
  17. package/checks/visual-report.mjs +13 -13
  18. package/config.schema.json +977 -927
  19. package/configs/eslint.mjs +27 -27
  20. package/configs/knip.json +11 -11
  21. package/configs/playwright.mjs +15 -15
  22. package/configs/vitest.mjs +16 -16
  23. package/package.json +105 -105
  24. package/release/finalize.mjs +65 -65
  25. package/release/github.mjs +64 -64
  26. package/release/prepare.mjs +30 -30
  27. package/runner/browsers.mjs +73 -73
  28. package/runner/cache.mjs +121 -121
  29. package/runner/ci-plan.mjs +54 -54
  30. package/runner/cli.mjs +250 -248
  31. package/runner/config.mjs +148 -148
  32. package/runner/docs-install.mjs +93 -93
  33. package/runner/execute.mjs +298 -286
  34. package/runner/generate.mjs +122 -122
  35. package/runner/git.mjs +122 -122
  36. package/runner/graph.mjs +250 -243
  37. package/runner/insights.mjs +313 -313
  38. package/runner/provision.mjs +53 -53
  39. package/runner/repo-standard.mjs +104 -0
  40. package/runner/report.mjs +35 -35
  41. package/runner/serve-static.mjs +76 -76
  42. package/runner/setup.mjs +241 -237
  43. package/runner/summary.mjs +112 -112
  44. package/runner/watch.mjs +82 -82
  45. package/templates/ci.yml +25 -25
  46. package/templates/dependabot-merge.yml +13 -13
  47. package/templates/dependabot.yml +26 -26
  48. package/templates/pre-push +13 -13
  49. package/templates/release.yml +23 -23
@@ -1,30 +1,30 @@
1
- import { existsSync, mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import { inside } from '../runner/config.mjs';
6
- import { invoke } from '../runner/execute.mjs';
7
-
8
- export async function checkPackage(root, requiredFiles, run = invoke) {
9
- if (!requiredFiles.length) throw new Error('Specify required package build files');
10
- const missing = requiredFiles.filter((file) => {
11
- const path = inside(root, file);
12
- return !existsSync(path) || !statSync(path).isFile();
13
- });
14
- if (missing.length) throw new Error(`Package build is missing: ${missing.join(', ')}`);
15
- const destination = mkdtempSync(join(tmpdir(), 'tooling-pack-'));
16
- try {
17
- const result = await run(['npm', 'pack', '--ignore-scripts', '--pack-destination', destination], root, { quiet: true });
18
- if (result.status !== 'passed') throw new Error('Package packing failed');
19
- const archives = readdirSync(destination).filter((file) => file.endsWith('.tgz'));
20
- if (archives.length !== 1) throw new Error('Package smoke check did not produce exactly one archive');
21
- return archives[0];
22
- } finally {
23
- rmSync(destination, { recursive: true, force: true });
24
- }
25
- }
26
-
27
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
28
- const archive = await checkPackage(process.cwd(), process.argv.slice(2));
29
- console.log(`Package smoke check passed (${archive}).`);
30
- }
1
+ import { existsSync, mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { inside } from '../runner/config.mjs';
6
+ import { invoke } from '../runner/execute.mjs';
7
+
8
+ export async function checkPackage(root, requiredFiles, run = invoke) {
9
+ if (!requiredFiles.length) throw new Error('Specify required package build files');
10
+ const missing = requiredFiles.filter((file) => {
11
+ const path = inside(root, file);
12
+ return !existsSync(path) || !statSync(path).isFile();
13
+ });
14
+ if (missing.length) throw new Error(`Package build is missing: ${missing.join(', ')}`);
15
+ const destination = mkdtempSync(join(tmpdir(), 'tooling-pack-'));
16
+ try {
17
+ const result = await run(['npm', 'pack', '--ignore-scripts', '--pack-destination', destination], root, { quiet: true });
18
+ if (result.status !== 'passed') throw new Error('Package packing failed');
19
+ const archives = readdirSync(destination).filter((file) => file.endsWith('.tgz'));
20
+ if (archives.length !== 1) throw new Error('Package smoke check did not produce exactly one archive');
21
+ return archives[0];
22
+ } finally {
23
+ rmSync(destination, { recursive: true, force: true });
24
+ }
25
+ }
26
+
27
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
28
+ const archive = await checkPackage(process.cwd(), process.argv.slice(2));
29
+ console.log(`Package smoke check passed (${archive}).`);
30
+ }
@@ -1,53 +1,53 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { pathToFileURL } from 'node:url';
3
-
4
- const cell = (text) => String(text).replaceAll('|', '|').replace(/[\r\n]+/g, ' ');
5
-
6
- export function playwrightSummary(data, { artifact = 'visual-diffs', report = 'playwright-report/index.html' } = {}) {
7
- const failures = [];
8
-
9
- const collect = (suite, path = []) => {
10
- const titles = suite.title ? [...path, suite.title] : path;
11
-
12
- for (const spec of suite.specs ?? []) {
13
- if (spec.ok) continue;
14
- const projects = [
15
- ...new Set((spec.tests ?? []).map((test) => test.projectName)),
16
- ];
17
- failures.push({
18
- name: [...titles, spec.title].join(' › '),
19
- projects: projects.join(', '),
20
- });
21
- }
22
- for (const child of suite.suites ?? []) collect(child, titles);
23
- };
24
-
25
- for (const suite of data.suites ?? [])
26
- collect(suite);
27
-
28
- if (failures.length === 0) return '';
29
-
30
- const rows = failures
31
- .map(({ name, projects }) => `| ${cell(name)} | ${cell(projects)} |`)
32
- .join('\n');
33
-
34
- return [
35
- '## Visual differences',
36
- '',
37
- `${failures.length} snapshot test(s) differ from their baseline.`,
38
- '',
39
- `Download the **${cell(artifact)}** artifact and open \`${cell(report)}\` for expected, actual and diff images. Fix the regression or update and review the intended baselines.`,
40
- '',
41
- '| Test | Project |',
42
- '| --- | --- |',
43
- rows,
44
- '',
45
- ].join('\n');
46
-
47
- }
48
-
49
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
50
- const [resultsPath = 'test-results/results.json', artifact, report] = process.argv.slice(2);
51
- if (existsSync(resultsPath))
52
- process.stdout.write(playwrightSummary(JSON.parse(readFileSync(resultsPath, 'utf8')), { artifact, report }));
53
- }
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { pathToFileURL } from 'node:url';
3
+
4
+ const cell = (text) => String(text).replaceAll('|', '|').replace(/[\r\n]+/g, ' ');
5
+
6
+ export function playwrightSummary(data, { artifact = 'visual-diffs', report = 'playwright-report/index.html' } = {}) {
7
+ const failures = [];
8
+
9
+ const collect = (suite, path = []) => {
10
+ const titles = suite.title ? [...path, suite.title] : path;
11
+
12
+ for (const spec of suite.specs ?? []) {
13
+ if (spec.ok) continue;
14
+ const projects = [
15
+ ...new Set((spec.tests ?? []).map((test) => test.projectName)),
16
+ ];
17
+ failures.push({
18
+ name: [...titles, spec.title].join(' › '),
19
+ projects: projects.join(', '),
20
+ });
21
+ }
22
+ for (const child of suite.suites ?? []) collect(child, titles);
23
+ };
24
+
25
+ for (const suite of data.suites ?? [])
26
+ collect(suite);
27
+
28
+ if (failures.length === 0) return '';
29
+
30
+ const rows = failures
31
+ .map(({ name, projects }) => `| ${cell(name)} | ${cell(projects)} |`)
32
+ .join('\n');
33
+
34
+ return [
35
+ '## Visual differences',
36
+ '',
37
+ `${failures.length} snapshot test(s) differ from their baseline.`,
38
+ '',
39
+ `Download the **${cell(artifact)}** artifact and open \`${cell(report)}\` for expected, actual and diff images. Fix the regression or update and review the intended baselines.`,
40
+ '',
41
+ '| Test | Project |',
42
+ '| --- | --- |',
43
+ rows,
44
+ '',
45
+ ].join('\n');
46
+
47
+ }
48
+
49
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
50
+ const [resultsPath = 'test-results/results.json', artifact, report] = process.argv.slice(2);
51
+ if (existsSync(resultsPath))
52
+ process.stdout.write(playwrightSummary(JSON.parse(readFileSync(resultsPath, 'utf8')), { artifact, report }));
53
+ }
package/checks/sass.mjs CHANGED
@@ -1,67 +1,67 @@
1
- import { readdirSync, readFileSync } from 'node:fs';
2
- import { createRequire } from 'node:module';
3
- import { join, relative } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import scss from 'postcss-scss';
6
- import { inside, loadConfig } from '../runner/config.mjs';
7
- import { matches } from '../runner/graph.mjs';
8
-
9
- export function importantViolations(source, file, exceptions = []) {
10
- const tree = scss.parse(source, { from: file });
11
- if (exceptions.some((pattern) => matches(file, pattern))) return [];
12
- const failures = [];
13
- tree.walkDecls((declaration) => {
14
- if (declaration.important)
15
- failures.push(`${file}:${declaration.source?.start?.line ?? 1}: avoid !important; use tokens or cascade structure`);
16
- });
17
- return failures;
18
- }
19
-
20
- export async function checkSass(root, options, { compile } = {}) {
21
- if (!options?.entrypoints?.length) throw new Error('Configure sass.entrypoints');
22
- const source = inside(root, options.source ?? 'src');
23
- const includes = options.include ?? ['**/*.scss'];
24
- const excludes = options.exclude ?? [];
25
- const files = [];
26
- const walk = (directory) => {
27
- for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
28
- const path = join(directory, entry.name);
29
- const file = relative(root, path).replaceAll('\\', '/');
30
- if (excludes.some((pattern) => matches(file, pattern))) continue;
31
- if (entry.isSymbolicLink()) throw new Error(`Sass source must not contain symlinks: ${file}`);
32
- if (entry.isDirectory()) walk(path);
33
- else if (entry.isFile() && includes.some((pattern) => matches(file, pattern))) files.push(path);
34
- }
35
- };
36
- walk(source);
37
- if (!files.length) throw new Error('No SCSS files matched sass.include');
38
- const entrypoints = options.entrypoints.map((file) => inside(root, file));
39
- const compiler = compile ?? createRequire(join(root, 'package.json'))('sass').compileAsync;
40
- const failures = [];
41
- for (const file of entrypoints) {
42
- try {
43
- await compiler(file, { style: 'compressed' });
44
- } catch (error) {
45
- failures.push(`${relative(root, file)}: Sass compilation failed: ${error.message}`);
46
- }
47
- }
48
- for (const path of files) {
49
- const file = relative(root, path).replaceAll('\\', '/');
50
- try {
51
- failures.push(...importantViolations(readFileSync(path, 'utf8'), file, options.importantExceptions));
52
- } catch (error) {
53
- failures.push(`${file}:${error.line ?? 1}: SCSS parsing failed: ${error.reason ?? error.message}`);
54
- }
55
- }
56
- return { files: files.length, entrypoints: entrypoints.length, failures };
57
- }
58
-
59
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
60
- const root = process.env.TOOLING_ROOT ?? process.cwd();
61
- const { config } = loadConfig(root);
62
- const result = await checkSass(root, config.sass);
63
- if (result.failures.length) {
64
- console.error(result.failures.join('\n'));
65
- process.exitCode = 1;
66
- } else console.log(`Sass checks passed (${result.files} files, ${result.entrypoints} entrypoints).`);
67
- }
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join, relative } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import scss from 'postcss-scss';
6
+ import { inside, loadConfig } from '../runner/config.mjs';
7
+ import { matches } from '../runner/graph.mjs';
8
+
9
+ export function importantViolations(source, file, exceptions = []) {
10
+ const tree = scss.parse(source, { from: file });
11
+ if (exceptions.some((pattern) => matches(file, pattern))) return [];
12
+ const failures = [];
13
+ tree.walkDecls((declaration) => {
14
+ if (declaration.important)
15
+ failures.push(`${file}:${declaration.source?.start?.line ?? 1}: avoid !important; use tokens or cascade structure`);
16
+ });
17
+ return failures;
18
+ }
19
+
20
+ export async function checkSass(root, options, { compile } = {}) {
21
+ if (!options?.entrypoints?.length) throw new Error('Configure sass.entrypoints');
22
+ const source = inside(root, options.source ?? 'src');
23
+ const includes = options.include ?? ['**/*.scss'];
24
+ const excludes = options.exclude ?? [];
25
+ const files = [];
26
+ const walk = (directory) => {
27
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
28
+ const path = join(directory, entry.name);
29
+ const file = relative(root, path).replaceAll('\\', '/');
30
+ if (excludes.some((pattern) => matches(file, pattern))) continue;
31
+ if (entry.isSymbolicLink()) throw new Error(`Sass source must not contain symlinks: ${file}`);
32
+ if (entry.isDirectory()) walk(path);
33
+ else if (entry.isFile() && includes.some((pattern) => matches(file, pattern))) files.push(path);
34
+ }
35
+ };
36
+ walk(source);
37
+ if (!files.length) throw new Error('No SCSS files matched sass.include');
38
+ const entrypoints = options.entrypoints.map((file) => inside(root, file));
39
+ const compiler = compile ?? createRequire(join(root, 'package.json'))('sass').compileAsync;
40
+ const failures = [];
41
+ for (const file of entrypoints) {
42
+ try {
43
+ await compiler(file, { style: 'compressed' });
44
+ } catch (error) {
45
+ failures.push(`${relative(root, file)}: Sass compilation failed: ${error.message}`);
46
+ }
47
+ }
48
+ for (const path of files) {
49
+ const file = relative(root, path).replaceAll('\\', '/');
50
+ try {
51
+ failures.push(...importantViolations(readFileSync(path, 'utf8'), file, options.importantExceptions));
52
+ } catch (error) {
53
+ failures.push(`${file}:${error.line ?? 1}: SCSS parsing failed: ${error.reason ?? error.message}`);
54
+ }
55
+ }
56
+ return { files: files.length, entrypoints: entrypoints.length, failures };
57
+ }
58
+
59
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
60
+ const root = process.env.TOOLING_ROOT ?? process.cwd();
61
+ const { config } = loadConfig(root);
62
+ const result = await checkSass(root, config.sass);
63
+ if (result.failures.length) {
64
+ console.error(result.failures.join('\n'));
65
+ process.exitCode = 1;
66
+ } else console.log(`Sass checks passed (${result.files} files, ${result.entrypoints} entrypoints).`);
67
+ }
@@ -1,58 +1,58 @@
1
- #!/usr/bin/env node
2
- import { lstatSync, readFileSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import { git } from '../runner/git.mjs';
6
- import { rootDirectory, writeDetails } from './shared.mjs';
7
-
8
- const patterns = [
9
- [/-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----/, 'private key'],
10
- [/sk_live_[0-9a-zA-Z]{20,}/, 'live secret key'],
11
- [/AKIA[0-9A-Z]{16}/, 'AWS access key'],
12
- [/VAPID_PRIVATE_KEY\s*=\s*['"]?[A-Za-z0-9_-]{40,}/, 'VAPID private key'],
13
- ];
14
-
15
- export function secretLabels(text) {
16
- const labels = patterns.filter(([pattern]) => pattern.test(text)).map(([, label]) => label);
17
- for (const match of text.matchAll(/\beyJ[A-Za-z0-9_-]*\.([A-Za-z0-9_-]+)\.[A-Za-z0-9_-]+/g)) {
18
- try {
19
- const payload = JSON.parse(Buffer.from(match[1], 'base64url').toString('utf8'));
20
- if (payload.role === 'service_role') labels.push('Supabase service-role JWT');
21
- } catch {
22
- // Ordinary dotted strings and malformed tokens are not service-role JWTs.
23
- }
24
- }
25
- return [...new Set(labels)];
26
- }
27
-
28
- export function scanSecrets(root) {
29
- const files = [...new Set(
30
- git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z').split('\0'),
31
- )].filter((file) => file && !/\.(?:png|jpe?g|gif|webp|ico|wasm|woff2?|pdf|zip)$/i.test(file));
32
- const hits = [];
33
- let scanned = 0;
34
- for (const file of files) {
35
- let text;
36
- try {
37
- const path = join(root, file);
38
- if (!lstatSync(path).isFile()) continue;
39
- text = readFileSync(path, 'utf8');
40
- } catch (error) {
41
- if (error.code === 'ENOENT') continue;
42
- throw error;
43
- }
44
- if (text.includes('\0')) continue;
45
- scanned++;
46
- for (const label of secretLabels(text)) hits.push({ file, label });
47
- }
48
- return { scanned, hits };
49
- }
50
-
51
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
52
- const result = scanSecrets(rootDirectory());
53
- writeDetails({ secrets: result });
54
- if (result.hits.length) {
55
- console.error(`Possible secrets committed:\n${result.hits.map(({ file, label }) => `${file}: ${label}`).join('\n')}`);
56
- process.exitCode = 1;
57
- } else console.log(`Secret scan passed (${result.scanned} files).`);
58
- }
1
+ #!/usr/bin/env node
2
+ import { lstatSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { git } from '../runner/git.mjs';
6
+ import { rootDirectory, writeDetails } from './shared.mjs';
7
+
8
+ const patterns = [
9
+ [/-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----/, 'private key'],
10
+ [/sk_live_[0-9a-zA-Z]{20,}/, 'live secret key'],
11
+ [/AKIA[0-9A-Z]{16}/, 'AWS access key'],
12
+ [/VAPID_PRIVATE_KEY\s*=\s*['"]?[A-Za-z0-9_-]{40,}/, 'VAPID private key'],
13
+ ];
14
+
15
+ export function secretLabels(text) {
16
+ const labels = patterns.filter(([pattern]) => pattern.test(text)).map(([, label]) => label);
17
+ for (const match of text.matchAll(/\beyJ[A-Za-z0-9_-]*\.([A-Za-z0-9_-]+)\.[A-Za-z0-9_-]+/g)) {
18
+ try {
19
+ const payload = JSON.parse(Buffer.from(match[1], 'base64url').toString('utf8'));
20
+ if (payload.role === 'service_role') labels.push('Supabase service-role JWT');
21
+ } catch {
22
+ // Ordinary dotted strings and malformed tokens are not service-role JWTs.
23
+ }
24
+ }
25
+ return [...new Set(labels)];
26
+ }
27
+
28
+ export function scanSecrets(root) {
29
+ const files = [...new Set(
30
+ git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z').split('\0'),
31
+ )].filter((file) => file && !/\.(?:png|jpe?g|gif|webp|ico|wasm|woff2?|pdf|zip)$/i.test(file));
32
+ const hits = [];
33
+ let scanned = 0;
34
+ for (const file of files) {
35
+ let text;
36
+ try {
37
+ const path = join(root, file);
38
+ if (!lstatSync(path).isFile()) continue;
39
+ text = readFileSync(path, 'utf8');
40
+ } catch (error) {
41
+ if (error.code === 'ENOENT') continue;
42
+ throw error;
43
+ }
44
+ if (text.includes('\0')) continue;
45
+ scanned++;
46
+ for (const label of secretLabels(text)) hits.push({ file, label });
47
+ }
48
+ return { scanned, hits };
49
+ }
50
+
51
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
52
+ const result = scanSecrets(rootDirectory());
53
+ writeDetails({ secrets: result });
54
+ if (result.hits.length) {
55
+ console.error(`Possible secrets committed:\n${result.hits.map(({ file, label }) => `${file}: ${label}`).join('\n')}`);
56
+ process.exitCode = 1;
57
+ } else console.log(`Secret scan passed (${result.scanned} files).`);
58
+ }
package/checks/shared.mjs CHANGED
@@ -1,86 +1,86 @@
1
- import { createRequire } from 'node:module';
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { join, dirname } from 'node:path';
4
- import { git } from '../runner/git.mjs';
5
- import { matches } from '../runner/graph.mjs';
6
-
7
- export const rootDirectory = () => process.env.TOOLING_ROOT ?? process.cwd();
8
- export function peer(name, cwd = process.cwd()) {
9
- try {
10
- return createRequire(join(cwd, 'package.json'))(name);
11
- } catch (error) {
12
- throw new Error(`Install ${name} in this project to enable this check`, { cause: error });
13
- }
14
- }
15
- export function sourceFiles(root, patterns, exclude = []) {
16
- return [
17
- ...new Set(
18
- git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z').split('\0'),
19
- ),
20
- ].filter(
21
- (file) =>
22
- file &&
23
- existsSync(join(root, file)) &&
24
- patterns.some((pattern) => matches(file, pattern)) &&
25
- !exclude.some((pattern) => matches(file, pattern)),
26
- );
27
- }
28
- export function writeDetails(value) {
29
- const directory = process.env.TOOLING_REPORT_DIR;
30
- const id = process.env.TOOLING_CHECK_ID;
31
- if (!directory || !id) return;
32
- mkdirSync(directory, { recursive: true });
33
- writeFileSync(join(directory, `${id}.details.json`), JSON.stringify(value, null, 2) + '\n');
34
- }
35
- export function compilerOptions(ts, root, configPath = 'tsconfig.json') {
36
- const path = join(root, configPath);
37
- if (!existsSync(path))
38
- return {
39
- allowJs: true,
40
- moduleResolution: ts.ModuleResolutionKind.Bundler,
41
- module: ts.ModuleKind.ESNext,
42
- };
43
- const read = ts.readConfigFile(path, ts.sys.readFile);
44
- if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, '\n'));
45
- const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(path), undefined, path);
46
- const errors = parsed.errors.filter((error) => ![18002, 18003].includes(error.code));
47
- if (errors.length)
48
- throw new Error(
49
- errors.map((error) => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'),
50
- );
51
- return parsed.options;
52
- }
53
- export function importsIn(ts, file) {
54
- const ast = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
55
- if (ast.parseDiagnostics.length)
56
- throw new Error(
57
- `${file}: ${ts.flattenDiagnosticMessageText(ast.parseDiagnostics[0].messageText, '\n')}`,
58
- );
59
- const imports = [];
60
- function visit(node) {
61
- let value;
62
- if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) value = node.moduleSpecifier;
63
- else if (
64
- ts.isImportEqualsDeclaration(node) &&
65
- ts.isExternalModuleReference(node.moduleReference)
66
- )
67
- value = node.moduleReference.expression;
68
- else if (
69
- ts.isCallExpression(node) &&
70
- (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
71
- (ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
72
- node.arguments.length === 1
73
- )
74
- value = node.arguments[0];
75
- else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument))
76
- value = node.argument.literal;
77
- if (value && ts.isStringLiteralLike(value))
78
- imports.push({
79
- specifier: value.text,
80
- line: ast.getLineAndCharacterOfPosition(value.getStart(ast)).line + 1,
81
- });
82
- ts.forEachChild(node, visit);
83
- }
84
- visit(ast);
85
- return imports;
86
- }
1
+ import { createRequire } from 'node:module';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join, dirname } from 'node:path';
4
+ import { git } from '../runner/git.mjs';
5
+ import { matches } from '../runner/graph.mjs';
6
+
7
+ export const rootDirectory = () => process.env.TOOLING_ROOT ?? process.cwd();
8
+ export function peer(name, cwd = process.cwd()) {
9
+ try {
10
+ return createRequire(join(cwd, 'package.json'))(name);
11
+ } catch (error) {
12
+ throw new Error(`Install ${name} in this project to enable this check`, { cause: error });
13
+ }
14
+ }
15
+ export function sourceFiles(root, patterns, exclude = []) {
16
+ return [
17
+ ...new Set(
18
+ git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z').split('\0'),
19
+ ),
20
+ ].filter(
21
+ (file) =>
22
+ file &&
23
+ existsSync(join(root, file)) &&
24
+ patterns.some((pattern) => matches(file, pattern)) &&
25
+ !exclude.some((pattern) => matches(file, pattern)),
26
+ );
27
+ }
28
+ export function writeDetails(value) {
29
+ const directory = process.env.TOOLING_REPORT_DIR;
30
+ const id = process.env.TOOLING_CHECK_ID;
31
+ if (!directory || !id) return;
32
+ mkdirSync(directory, { recursive: true });
33
+ writeFileSync(join(directory, `${id}.details.json`), JSON.stringify(value, null, 2) + '\n');
34
+ }
35
+ export function compilerOptions(ts, root, configPath = 'tsconfig.json') {
36
+ const path = join(root, configPath);
37
+ if (!existsSync(path))
38
+ return {
39
+ allowJs: true,
40
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
41
+ module: ts.ModuleKind.ESNext,
42
+ };
43
+ const read = ts.readConfigFile(path, ts.sys.readFile);
44
+ if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, '\n'));
45
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(path), undefined, path);
46
+ const errors = parsed.errors.filter((error) => ![18002, 18003].includes(error.code));
47
+ if (errors.length)
48
+ throw new Error(
49
+ errors.map((error) => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'),
50
+ );
51
+ return parsed.options;
52
+ }
53
+ export function importsIn(ts, file) {
54
+ const ast = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
55
+ if (ast.parseDiagnostics.length)
56
+ throw new Error(
57
+ `${file}: ${ts.flattenDiagnosticMessageText(ast.parseDiagnostics[0].messageText, '\n')}`,
58
+ );
59
+ const imports = [];
60
+ function visit(node) {
61
+ let value;
62
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) value = node.moduleSpecifier;
63
+ else if (
64
+ ts.isImportEqualsDeclaration(node) &&
65
+ ts.isExternalModuleReference(node.moduleReference)
66
+ )
67
+ value = node.moduleReference.expression;
68
+ else if (
69
+ ts.isCallExpression(node) &&
70
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
71
+ (ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
72
+ node.arguments.length === 1
73
+ )
74
+ value = node.arguments[0];
75
+ else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument))
76
+ value = node.argument.literal;
77
+ if (value && ts.isStringLiteralLike(value))
78
+ imports.push({
79
+ specifier: value.text,
80
+ line: ast.getLineAndCharacterOfPosition(value.getStart(ast)).line + 1,
81
+ });
82
+ ts.forEachChild(node, visit);
83
+ }
84
+ visit(ast);
85
+ return imports;
86
+ }