@dcaldeira/tooling 0.0.0-stage → 0.1.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.
- package/LICENSE +9 -0
- package/README.md +34 -3
- package/checks/a11y.mjs +206 -0
- package/checks/architecture.mjs +137 -0
- package/checks/audit.mjs +121 -0
- package/checks/bundle.mjs +126 -0
- package/checks/dependencies.mjs +277 -0
- package/checks/lint-scss.mjs +349 -0
- package/checks/package.mjs +30 -0
- package/checks/playwright-summary.mjs +53 -0
- package/checks/sass.mjs +67 -0
- package/checks/scan-secrets.mjs +58 -0
- package/checks/shared.mjs +86 -0
- package/checks/style-property-order.json +498 -0
- package/checks/translations.mjs +55 -0
- package/checks/visual-compare.mjs +148 -0
- package/checks/visual-report-html.mjs +470 -0
- package/checks/visual-report.mjs +13 -0
- package/config.schema.json +927 -0
- package/configs/eslint.mjs +27 -0
- package/configs/knip.json +11 -0
- package/configs/playwright.mjs +15 -0
- package/configs/prettier.mjs +1 -0
- package/configs/tsconfig.json +16 -0
- package/configs/vitest.mjs +16 -0
- package/package.json +105 -6
- package/release/evidence.mjs +62 -0
- package/release/finalize.mjs +65 -0
- package/release/gh.mjs +25 -0
- package/release/github.mjs +64 -0
- package/release/prepare.mjs +30 -0
- package/runner/browsers.mjs +73 -0
- package/runner/cache.mjs +121 -0
- package/runner/ci-plan.mjs +54 -0
- package/runner/cli.mjs +249 -0
- package/runner/config.mjs +148 -0
- package/runner/docs-install.mjs +93 -0
- package/runner/execute.mjs +286 -0
- package/runner/generate.mjs +122 -0
- package/runner/git.mjs +122 -0
- package/runner/graph.mjs +243 -0
- package/runner/index.mjs +4 -0
- package/runner/insights.mjs +313 -0
- package/runner/provision.mjs +53 -0
- package/runner/report.mjs +35 -0
- package/runner/serve-static.mjs +76 -0
- package/runner/setup.mjs +237 -0
- package/runner/summary.mjs +112 -0
- package/runner/watch.mjs +82 -0
- package/templates/ci.yml +25 -0
- package/templates/dependabot-merge.yml +13 -0
- package/templates/dependabot.yml +26 -0
- package/templates/pre-push +13 -0
- package/templates/release.yml +23 -0
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import semver from 'semver';
|
|
5
|
+
import { loadConfig, inside } from '../runner/config.mjs';
|
|
6
|
+
import { matches } from '../runner/graph.mjs';
|
|
7
|
+
import {
|
|
8
|
+
compilerOptions,
|
|
9
|
+
importsIn,
|
|
10
|
+
peer,
|
|
11
|
+
rootDirectory,
|
|
12
|
+
sourceFiles,
|
|
13
|
+
writeDetails,
|
|
14
|
+
} from './shared.mjs';
|
|
15
|
+
|
|
16
|
+
export function analyseDependencies(root, settings = {}, manifests, lock, files, ts) {
|
|
17
|
+
const rootManifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
18
|
+
const workspacePatterns = Array.isArray(rootManifest.workspaces)
|
|
19
|
+
? rootManifest.workspaces
|
|
20
|
+
: (rootManifest.workspaces?.packages ?? []);
|
|
21
|
+
manifests ??= settings.manifests ?? [
|
|
22
|
+
'package.json',
|
|
23
|
+
...sourceFiles(root, ['**/package.json']).filter(
|
|
24
|
+
(file) =>
|
|
25
|
+
file !== 'package.json' &&
|
|
26
|
+
workspacePatterns.some((pattern) => matches(dirname(file).replaceAll('\\', '/'), pattern)),
|
|
27
|
+
),
|
|
28
|
+
];
|
|
29
|
+
const packages = [...new Set(manifests)].map((file) => ({
|
|
30
|
+
file,
|
|
31
|
+
directory: dirname(file).replaceAll('\\', '/'),
|
|
32
|
+
manifest: JSON.parse(readFileSync(inside(root, file), 'utf8')),
|
|
33
|
+
}));
|
|
34
|
+
const named = new Map();
|
|
35
|
+
const issues = [],
|
|
36
|
+
warnings = [],
|
|
37
|
+
declarations = new Map();
|
|
38
|
+
for (const pkg of packages) {
|
|
39
|
+
const name = pkg.manifest.name;
|
|
40
|
+
if (name && named.has(name))
|
|
41
|
+
issues.push({
|
|
42
|
+
rule: 'duplicate-workspace-name',
|
|
43
|
+
file: pkg.file,
|
|
44
|
+
message: `Duplicate package name ${name}`,
|
|
45
|
+
});
|
|
46
|
+
if (name) named.set(name, pkg);
|
|
47
|
+
for (const section of [
|
|
48
|
+
'dependencies',
|
|
49
|
+
'devDependencies',
|
|
50
|
+
'peerDependencies',
|
|
51
|
+
'optionalDependencies',
|
|
52
|
+
])
|
|
53
|
+
for (const [name, range] of Object.entries(pkg.manifest[section] ?? {})) {
|
|
54
|
+
const list = declarations.get(name) ?? [];
|
|
55
|
+
list.push({ pkg, section, range });
|
|
56
|
+
declarations.set(name, list);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function versionRange(name, entry) {
|
|
60
|
+
const range = entry.range;
|
|
61
|
+
if (typeof range !== 'string') {
|
|
62
|
+
issues.push({
|
|
63
|
+
rule: 'invalid-range',
|
|
64
|
+
file: entry.pkg.file,
|
|
65
|
+
message: `${name}: dependency range must be a string`,
|
|
66
|
+
});
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const local = named.get(name);
|
|
70
|
+
if (range.startsWith('workspace:')) {
|
|
71
|
+
if (!local) {
|
|
72
|
+
issues.push({
|
|
73
|
+
rule: 'missing-workspace',
|
|
74
|
+
file: entry.pkg.file,
|
|
75
|
+
message: `${name} uses workspace: but no workspace declares that name`,
|
|
76
|
+
});
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
const value = range.slice(10);
|
|
80
|
+
return ['*', '^', '~'].includes(value)
|
|
81
|
+
? value === '*'
|
|
82
|
+
? local.manifest.version
|
|
83
|
+
: value + local.manifest.version
|
|
84
|
+
: value;
|
|
85
|
+
}
|
|
86
|
+
if (/^(?:file|link):/.test(range)) {
|
|
87
|
+
if (
|
|
88
|
+
local &&
|
|
89
|
+
resolve(root, entry.pkg.directory, range.replace(/^[^:]+:/, '')) !==
|
|
90
|
+
resolve(root, local.directory)
|
|
91
|
+
)
|
|
92
|
+
issues.push({
|
|
93
|
+
rule: 'workspace-target',
|
|
94
|
+
file: entry.pkg.file,
|
|
95
|
+
message: `${name} points to a different local directory`,
|
|
96
|
+
});
|
|
97
|
+
return local?.manifest.version ?? null;
|
|
98
|
+
}
|
|
99
|
+
if (range.startsWith('npm:')) {
|
|
100
|
+
const at = range.lastIndexOf('@');
|
|
101
|
+
return at > 4 ? range.slice(at + 1) : '*';
|
|
102
|
+
}
|
|
103
|
+
return semver.validRange(range) ? range : null;
|
|
104
|
+
}
|
|
105
|
+
for (const [name, entries] of declarations) {
|
|
106
|
+
if (settings.ignore?.includes(name)) continue;
|
|
107
|
+
const normalized = entries.map((entry) => ({
|
|
108
|
+
...entry,
|
|
109
|
+
normalized: versionRange(name, entry),
|
|
110
|
+
}));
|
|
111
|
+
if (settings.strict?.includes(name) && new Set(entries.map((entry) => entry.range)).size > 1)
|
|
112
|
+
issues.push({
|
|
113
|
+
rule: 'version-drift',
|
|
114
|
+
message: `${name}: ranges differ: ${entries.map((entry) => `${entry.pkg.file}=${entry.range}`).join(', ')}`,
|
|
115
|
+
});
|
|
116
|
+
const expected = settings.expected?.[name];
|
|
117
|
+
if (expected && !semver.validRange(expected))
|
|
118
|
+
throw new Error(`Invalid expected range for ${name}: ${expected}`);
|
|
119
|
+
for (let i = 0; i < normalized.length; i++) {
|
|
120
|
+
const entry = normalized[i],
|
|
121
|
+
local = named.get(name);
|
|
122
|
+
if (entry.normalized && !semver.validRange(entry.normalized)) {
|
|
123
|
+
issues.push({
|
|
124
|
+
rule: 'invalid-range',
|
|
125
|
+
file: entry.pkg.file,
|
|
126
|
+
message: `${name}: invalid workspace range ${entry.range}`,
|
|
127
|
+
});
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (expected && (!entry.normalized || !semver.subset(entry.normalized, expected)))
|
|
131
|
+
issues.push({
|
|
132
|
+
rule: 'expected-version',
|
|
133
|
+
file: entry.pkg.file,
|
|
134
|
+
message: `${name}: ${entry.range} permits versions outside ${expected}`,
|
|
135
|
+
});
|
|
136
|
+
if (
|
|
137
|
+
local &&
|
|
138
|
+
entry.normalized &&
|
|
139
|
+
(!semver.valid(local.manifest.version) ||
|
|
140
|
+
!semver.satisfies(local.manifest.version, entry.normalized))
|
|
141
|
+
)
|
|
142
|
+
issues.push({
|
|
143
|
+
rule: 'workspace-version',
|
|
144
|
+
file: entry.pkg.file,
|
|
145
|
+
message: `${name}@${local.manifest.version} does not satisfy ${entry.range}`,
|
|
146
|
+
});
|
|
147
|
+
for (let j = i + 1; j < normalized.length; j++) {
|
|
148
|
+
const other = normalized[j];
|
|
149
|
+
if (
|
|
150
|
+
entry.normalized &&
|
|
151
|
+
other.normalized &&
|
|
152
|
+
semver.validRange(other.normalized) &&
|
|
153
|
+
!semver.intersects(entry.normalized, other.normalized)
|
|
154
|
+
)
|
|
155
|
+
issues.push({
|
|
156
|
+
rule: 'incompatible-ranges',
|
|
157
|
+
message: `${name}: ${entry.pkg.file} (${entry.range}) and ${other.pkg.file} (${other.range}) are incompatible`,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (lock === undefined) {
|
|
163
|
+
try {
|
|
164
|
+
lock = JSON.parse(readFileSync(join(root, 'package-lock.json'), 'utf8'));
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error.code !== 'ENOENT') throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const versions = new Map();
|
|
170
|
+
for (const [path, entry] of Object.entries(lock?.packages ?? {})) {
|
|
171
|
+
const match = path.match(/(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)$/);
|
|
172
|
+
if (!match || !entry.version || entry.link) continue;
|
|
173
|
+
const set = versions.get(match[1]) ?? new Set();
|
|
174
|
+
set.add(entry.version);
|
|
175
|
+
versions.set(match[1], set);
|
|
176
|
+
}
|
|
177
|
+
for (const [name, set] of versions)
|
|
178
|
+
if (set.size > 1 && !settings.ignore?.includes(name)) {
|
|
179
|
+
const issue = {
|
|
180
|
+
rule: 'duplicate-versions',
|
|
181
|
+
message: `${name}: lockfile contains ${[...set].sort().join(', ')}`,
|
|
182
|
+
};
|
|
183
|
+
(settings.singleVersion?.includes(name) ? issues : warnings).push(issue);
|
|
184
|
+
}
|
|
185
|
+
if (settings.checkImports !== false && packages.length > 1) {
|
|
186
|
+
ts ??= peer('typescript', root);
|
|
187
|
+
files ??= sourceFiles(root, settings.include ?? ['**/src/**'], settings.exclude ?? []);
|
|
188
|
+
const byDirectory = [...packages].sort((a, b) => b.directory.length - a.directory.length);
|
|
189
|
+
const owner = (file) =>
|
|
190
|
+
byDirectory.find((pkg) => pkg.directory === '.' || file.startsWith(pkg.directory + '/'));
|
|
191
|
+
const options = new Map(
|
|
192
|
+
packages.map((pkg) => [
|
|
193
|
+
pkg,
|
|
194
|
+
compilerOptions(
|
|
195
|
+
ts,
|
|
196
|
+
root,
|
|
197
|
+
pkg.directory === '.' ? 'tsconfig.json' : `${pkg.directory}/tsconfig.json`,
|
|
198
|
+
),
|
|
199
|
+
]),
|
|
200
|
+
);
|
|
201
|
+
const resolutionCaches = new Map(
|
|
202
|
+
packages.map((pkg) => [
|
|
203
|
+
pkg,
|
|
204
|
+
ts.createModuleResolutionCache(
|
|
205
|
+
root,
|
|
206
|
+
(file) => (ts.sys.useCaseSensitiveFileNames ? file : file.toLowerCase()),
|
|
207
|
+
options.get(pkg),
|
|
208
|
+
),
|
|
209
|
+
]),
|
|
210
|
+
);
|
|
211
|
+
for (const file of files.filter((file) => /\.[cm]?[jt]sx?$/.test(file))) {
|
|
212
|
+
const from = owner(file);
|
|
213
|
+
if (!from) continue;
|
|
214
|
+
for (const { specifier, line } of importsIn(ts, inside(root, file))) {
|
|
215
|
+
const internal = [...named].find(
|
|
216
|
+
([name]) => specifier === name || specifier.startsWith(name + '/'),
|
|
217
|
+
);
|
|
218
|
+
const resolved = ts.resolveModuleName(
|
|
219
|
+
specifier,
|
|
220
|
+
join(root, file),
|
|
221
|
+
options.get(from),
|
|
222
|
+
ts.sys,
|
|
223
|
+
resolutionCaches.get(from),
|
|
224
|
+
).resolvedModule;
|
|
225
|
+
const target =
|
|
226
|
+
internal?.[1] ??
|
|
227
|
+
(resolved
|
|
228
|
+
? owner(relative(root, resolved.resolvedFileName).replaceAll('\\', '/'))
|
|
229
|
+
: null);
|
|
230
|
+
if (!target || target === from || !target.manifest.name || target.directory === '.')
|
|
231
|
+
continue;
|
|
232
|
+
const name = target.manifest.name;
|
|
233
|
+
if (
|
|
234
|
+
!['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some(
|
|
235
|
+
(section) => Object.hasOwn(from.manifest[section] ?? {}, name),
|
|
236
|
+
)
|
|
237
|
+
)
|
|
238
|
+
issues.push({
|
|
239
|
+
rule: 'undeclared-workspace-import',
|
|
240
|
+
file,
|
|
241
|
+
line,
|
|
242
|
+
message: `${from.manifest.name ?? from.file} imports ${name} without declaring it`,
|
|
243
|
+
});
|
|
244
|
+
if (!internal)
|
|
245
|
+
issues.push({
|
|
246
|
+
rule: 'workspace-path-import',
|
|
247
|
+
file,
|
|
248
|
+
line,
|
|
249
|
+
message: `Import ${name} by package name instead of crossing workspace directories: ${specifier}`,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return { packages: packages.length, issues, warnings };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
258
|
+
const root = rootDirectory(),
|
|
259
|
+
{ config } = loadConfig(root);
|
|
260
|
+
const result = analyseDependencies(
|
|
261
|
+
root,
|
|
262
|
+
config.dependencyConsistency,
|
|
263
|
+
undefined,
|
|
264
|
+
undefined,
|
|
265
|
+
undefined,
|
|
266
|
+
config.dependencyConsistency?.checkImports === false ? undefined : peer('typescript'),
|
|
267
|
+
);
|
|
268
|
+
writeDetails({ dependencies: result });
|
|
269
|
+
for (const issue of result.issues)
|
|
270
|
+
console.error(
|
|
271
|
+
`${issue.file ?? 'dependencies'}:${issue.line ?? 1} ${issue.message} (${issue.rule})`,
|
|
272
|
+
);
|
|
273
|
+
console.log(
|
|
274
|
+
`Dependency consistency: ${result.packages} packages, ${result.issues.length} errors, ${result.warnings.length} duplicate-version notices`,
|
|
275
|
+
);
|
|
276
|
+
process.exitCode = result.issues.length ? 1 : 0;
|
|
277
|
+
}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, join, relative } from 'node:path';
|
|
4
|
+
import { loadConfig, inside } from '../runner/config.mjs';
|
|
5
|
+
import { matches } from '../runner/graph.mjs';
|
|
6
|
+
import scss from 'postcss-scss';
|
|
7
|
+
|
|
8
|
+
const repo = process.env.TOOLING_ROOT ?? process.cwd();
|
|
9
|
+
const { config } = loadConfig(repo);
|
|
10
|
+
const options = config.styles ?? {};
|
|
11
|
+
const ORDER = JSON.parse(
|
|
12
|
+
readFileSync(new URL('./style-property-order.json', import.meta.url), 'utf8'),
|
|
13
|
+
);
|
|
14
|
+
const RANK = new Map(ORDER.map((name, index) => [name, index]));
|
|
15
|
+
|
|
16
|
+
const BEM =
|
|
17
|
+
/^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z][a-z0-9]*(-[a-z0-9]+)*)?(--[a-z][a-z0-9]*(-[a-z0-9]+)*)?$/;
|
|
18
|
+
const rookie = options.preset === 'rookie';
|
|
19
|
+
const rules = { bem: rookie, componentName: rookie, palette: rookie, ...options.rules };
|
|
20
|
+
const COLOUR_FREE = /[/\\](_palette|themes)[/\\]/;
|
|
21
|
+
const MAX_DEPTH = options.maxDepth ?? 3;
|
|
22
|
+
const CONTROL = new Set(['for', 'each', 'while', 'if', 'else']);
|
|
23
|
+
const MAX_SPECIFICITY = options.maxSpecificity ?? [0, 4, 2];
|
|
24
|
+
const LENGTH_UNITS = 'px|em|rem|ex|ch|vw|vh|vmin|vmax|cm|mm|in|pt|pc|q';
|
|
25
|
+
const NAMED_COLOURS = new Set(
|
|
26
|
+
'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen'.split(
|
|
27
|
+
' ',
|
|
28
|
+
),
|
|
29
|
+
);
|
|
30
|
+
const COLOUR_PROPS =
|
|
31
|
+
/^(color|background(-color|-image)?|border(-[a-z]+)*-color|border(-top|-right|-bottom|-left)?|outline(-color)?|fill|stroke|box-shadow|text-shadow|caret-color|accent-color|text-decoration(-color)?|column-rule(-color)?)$/;
|
|
32
|
+
|
|
33
|
+
const files = (dir) =>
|
|
34
|
+
readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
35
|
+
const path = join(dir, entry.name);
|
|
36
|
+
if (entry.isDirectory()) return files(path);
|
|
37
|
+
return entry.isFile() && path.endsWith('.scss') ? [path] : [];
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const stripValue = (value) =>
|
|
41
|
+
value
|
|
42
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
43
|
+
.replace(/(['"])(?:\\.|(?!\1).)*\1/g, '""')
|
|
44
|
+
.replace(/#\{[^}]*\}/g, 'x');
|
|
45
|
+
|
|
46
|
+
const unprefixed = (prop) => prop.replace(/^-(webkit|moz|ms|o)-/, '');
|
|
47
|
+
|
|
48
|
+
const specificity = (selector) => {
|
|
49
|
+
const s = [0, 0, 0];
|
|
50
|
+
const clean = selector.replace(/\[[^\]]*\]/g, () => {
|
|
51
|
+
s[1] += 1;
|
|
52
|
+
return '';
|
|
53
|
+
});
|
|
54
|
+
for (const match of clean.matchAll(
|
|
55
|
+
/(#[\w-]+)|(\.[\w-]+)|(::?[\w-]+)(\([^)]*\))?|([a-zA-Z][\w-]*)/g,
|
|
56
|
+
)) {
|
|
57
|
+
if (match[1]) s[0] += 1;
|
|
58
|
+
else if (match[2]) s[1] += 1;
|
|
59
|
+
else if (match[3]) {
|
|
60
|
+
const name = match[3].replace(/^:+/, '');
|
|
61
|
+
if (
|
|
62
|
+
match[3].startsWith('::') ||
|
|
63
|
+
['before', 'after', 'first-line', 'first-letter'].includes(name)
|
|
64
|
+
)
|
|
65
|
+
s[2] += 1;
|
|
66
|
+
else if (name === 'where' || name === 'global') continue;
|
|
67
|
+
else if (['is', 'not', 'has'].includes(name)) {
|
|
68
|
+
const inner = (match[4] ?? '').slice(1, -1).split(',').map(specificity);
|
|
69
|
+
const top = inner.sort((a, b) => b[0] - a[0] || b[1] - a[1] || b[2] - a[2])[0] ?? [0, 0, 0];
|
|
70
|
+
s[0] += top[0];
|
|
71
|
+
s[1] += top[1];
|
|
72
|
+
s[2] += top[2];
|
|
73
|
+
} else s[1] += 1;
|
|
74
|
+
} else if (match[5]) s[2] += 1;
|
|
75
|
+
}
|
|
76
|
+
return s;
|
|
77
|
+
};
|
|
78
|
+
const tooSpecific = (s) =>
|
|
79
|
+
s[0] > MAX_SPECIFICITY[0] ||
|
|
80
|
+
(s[0] === MAX_SPECIFICITY[0] &&
|
|
81
|
+
(s[1] > MAX_SPECIFICITY[1] || (s[1] === MAX_SPECIFICITY[1] && s[2] > MAX_SPECIFICITY[2])));
|
|
82
|
+
|
|
83
|
+
const splitList = (selector) => {
|
|
84
|
+
const out = [];
|
|
85
|
+
let depth = 0;
|
|
86
|
+
let start = 0;
|
|
87
|
+
for (let i = 0; i < selector.length; i += 1) {
|
|
88
|
+
const c = selector[i];
|
|
89
|
+
if (c === '(' || c === '[') depth += 1;
|
|
90
|
+
else if (c === ')' || c === ']') depth -= 1;
|
|
91
|
+
else if (c === ',' && depth === 0) {
|
|
92
|
+
out.push(selector.slice(start, i).trim());
|
|
93
|
+
start = i + 1;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
out.push(selector.slice(start).trim());
|
|
97
|
+
return out.filter(Boolean);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const resolve = (selector, parents) =>
|
|
101
|
+
parents.length === 0
|
|
102
|
+
? splitList(selector)
|
|
103
|
+
: splitList(selector).flatMap((child) =>
|
|
104
|
+
parents.map((parent) =>
|
|
105
|
+
child.includes('&') ? child.replaceAll('&', parent) : `${parent} ${child}`,
|
|
106
|
+
),
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
/* An at-rule straight under the root (a mixin, a media query) and Sass control flow are not levels. */
|
|
110
|
+
const nestingDepth = (node, level = 0) => {
|
|
111
|
+
const parent = node.parent;
|
|
112
|
+
if (!parent || parent.type === 'root') return level;
|
|
113
|
+
if (parent.type === 'atrule' && parent.parent?.type === 'root') return level;
|
|
114
|
+
if (parent.type === 'atrule' && CONTROL.has(parent.name)) return nestingDepth(parent, level);
|
|
115
|
+
return nestingDepth(parent, level + 1);
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const line = (node) => node.source?.start?.line ?? 0;
|
|
119
|
+
const endLine = (node) => node.source?.end?.line ?? line(node);
|
|
120
|
+
const blankBefore = (node) => /\n[ \t\r]*\n/.test(node.raws.before ?? '');
|
|
121
|
+
|
|
122
|
+
const lintFile = (file, fix) => {
|
|
123
|
+
const source = readFileSync(file, 'utf8');
|
|
124
|
+
const problems = [];
|
|
125
|
+
const root = scss.parse(source, { from: file });
|
|
126
|
+
const colourFree =
|
|
127
|
+
!rules.palette ||
|
|
128
|
+
COLOUR_FREE.test(file) ||
|
|
129
|
+
(options.colourTokenPaths ?? []).some((pattern) => matches(relative(repo, file), pattern));
|
|
130
|
+
const moduleBlock =
|
|
131
|
+
rules.componentName && /\.module\.scss$/.test(file)
|
|
132
|
+
? basename(file, '.module.scss')
|
|
133
|
+
.replace(/(?<!^)(?=[A-Z])/g, '-')
|
|
134
|
+
.toLowerCase()
|
|
135
|
+
: null;
|
|
136
|
+
const disabled = new Map();
|
|
137
|
+
root.walkComments((c) => {
|
|
138
|
+
const m = /lint-scss-disable-next-line\s+([\w-]+)/.exec(c.text);
|
|
139
|
+
if (m) disabled.set(`${endLine(c) + 1}:${m[1]}`, true);
|
|
140
|
+
});
|
|
141
|
+
const report = (node, rule, message) => {
|
|
142
|
+
if (disabled.has(`${line(node)}:${rule}`)) return;
|
|
143
|
+
problems.push({ line: line(node), rule, message });
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const visit = (parent, selectors, depth) => {
|
|
147
|
+
const kids = parent.nodes ?? [];
|
|
148
|
+
kids.forEach((node, index) => {
|
|
149
|
+
const prev = kids[index - 1];
|
|
150
|
+
const first = index === 0;
|
|
151
|
+
const nested = parent.type !== 'root';
|
|
152
|
+
|
|
153
|
+
if (node.type === 'comment') {
|
|
154
|
+
const sameLine = prev && endLine(prev) === line(node);
|
|
155
|
+
const afterComment = prev?.type === 'comment';
|
|
156
|
+
if (
|
|
157
|
+
!sameLine &&
|
|
158
|
+
!afterComment &&
|
|
159
|
+
!first &&
|
|
160
|
+
!blankBefore(node) &&
|
|
161
|
+
!/lint-scss|stylelint/.test(node.text)
|
|
162
|
+
)
|
|
163
|
+
report(node, 'comment-empty-line-before', 'Expected an empty line before the comment');
|
|
164
|
+
if (!sameLine && first && nested && blankBefore(node))
|
|
165
|
+
report(
|
|
166
|
+
node,
|
|
167
|
+
'comment-empty-line-before',
|
|
168
|
+
'Unexpected empty line before the first comment',
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (
|
|
173
|
+
node.type === 'rule' &&
|
|
174
|
+
parent.name !== 'keyframes' &&
|
|
175
|
+
!/keyframes$/.test(parent.name ?? '')
|
|
176
|
+
) {
|
|
177
|
+
const own = resolve(node.selector, selectors);
|
|
178
|
+
const multi = endLine(node) > line(node);
|
|
179
|
+
const afterComment = prev?.type === 'comment';
|
|
180
|
+
if (first && nested && blankBefore(node))
|
|
181
|
+
report(node, 'rule-empty-line-before', 'Unexpected empty line before the first rule');
|
|
182
|
+
else if (!first && multi && !afterComment && !blankBefore(node))
|
|
183
|
+
report(node, 'rule-empty-line-before', 'Expected an empty line before the rule');
|
|
184
|
+
if (nestingDepth(node) > MAX_DEPTH)
|
|
185
|
+
report(node, 'max-nesting-depth', `Nesting deeper than ${MAX_DEPTH} levels`);
|
|
186
|
+
if (!node.nodes?.length) report(node, 'block-no-empty', 'Empty block');
|
|
187
|
+
for (const sel of own) {
|
|
188
|
+
if (!sel.includes('#{') && !sel.includes('%')) {
|
|
189
|
+
const bare = sel.replace(/:global\([^)]*\)/g, '').replace(/\[[^\]]*\]/g, '');
|
|
190
|
+
for (const m of bare.matchAll(/\.(-?[\w-]+)/g))
|
|
191
|
+
if (rules.bem && !BEM.test(m[1]))
|
|
192
|
+
report(
|
|
193
|
+
node,
|
|
194
|
+
'selector-class-pattern',
|
|
195
|
+
`Use BEM: .block, .block__element, .block--modifier, in kebab-case: .${m[1]}`,
|
|
196
|
+
);
|
|
197
|
+
for (const m of bare.matchAll(/\.([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?:__|--|(?![\w-]))/g))
|
|
198
|
+
if (moduleBlock && m[1] !== moduleBlock)
|
|
199
|
+
report(
|
|
200
|
+
node,
|
|
201
|
+
'block-name-matches-component',
|
|
202
|
+
`The block is named after the component: .${moduleBlock}, not .${m[1]}`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
if (!sel.includes('#{') && tooSpecific(specificity(sel)))
|
|
206
|
+
report(
|
|
207
|
+
node,
|
|
208
|
+
'selector-max-specificity',
|
|
209
|
+
`Specificity of "${sel}" is above ${MAX_SPECIFICITY.join(',')}`,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
visit(node, own, depth + 1);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (node.type === 'atrule') {
|
|
217
|
+
const blockless = !node.nodes;
|
|
218
|
+
const afterComment = prev?.type === 'comment';
|
|
219
|
+
const prevBlockless = prev?.type === 'atrule' && !prev.nodes;
|
|
220
|
+
if (node.name !== 'else') {
|
|
221
|
+
if (first && nested && blankBefore(node))
|
|
222
|
+
report(node, 'at-rule-empty-line-before', `Unexpected empty line before @${node.name}`);
|
|
223
|
+
else if (!first && !afterComment) {
|
|
224
|
+
if (blockless && prevBlockless && blankBefore(node))
|
|
225
|
+
report(
|
|
226
|
+
node,
|
|
227
|
+
'at-rule-empty-line-before',
|
|
228
|
+
`Unexpected empty line before @${node.name}`,
|
|
229
|
+
);
|
|
230
|
+
else if (!(blockless && prevBlockless) && !blankBefore(node))
|
|
231
|
+
report(
|
|
232
|
+
node,
|
|
233
|
+
'at-rule-empty-line-before',
|
|
234
|
+
`Expected an empty line before @${node.name}`,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (node.nodes) {
|
|
239
|
+
if (nestingDepth(node) > MAX_DEPTH && node.name !== 'keyframes')
|
|
240
|
+
report(node, 'max-nesting-depth', `Nesting deeper than ${MAX_DEPTH} levels`);
|
|
241
|
+
if (!node.nodes.length) report(node, 'block-no-empty', 'Empty block');
|
|
242
|
+
visit(node, selectors, node.name === 'keyframes' ? depth : depth + 1);
|
|
243
|
+
}
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (node.type === 'decl') {
|
|
248
|
+
const value = stripValue(node.value);
|
|
249
|
+
if (!colourFree) {
|
|
250
|
+
if (
|
|
251
|
+
/#[0-9a-fA-F]{3,8}\b/.test(value) &&
|
|
252
|
+
!node.prop.startsWith('$') &&
|
|
253
|
+
!node.prop.startsWith('--')
|
|
254
|
+
)
|
|
255
|
+
report(node, 'color-no-hex', 'Raw hex colour: use a palette token');
|
|
256
|
+
if (/\b(rgba?|hsla?)\(/i.test(value))
|
|
257
|
+
report(node, 'function-disallowed-list', 'Use a palette token, not rgb()/hsl()');
|
|
258
|
+
if (COLOUR_PROPS.test(node.prop)) {
|
|
259
|
+
for (const word of value.match(/(?<![\w$#.-])[a-zA-Z][a-zA-Z0-9-]*(?![\w(-])/g) ?? [])
|
|
260
|
+
if (NAMED_COLOURS.has(word.toLowerCase()))
|
|
261
|
+
report(node, 'color-named', `Named colour "${word}": use a palette token`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (!node.prop.startsWith('--') && !node.prop.startsWith('$')) {
|
|
265
|
+
const zero = new RegExp(`(?<![\\w.#$-])0(${LENGTH_UNITS})\\b`, 'i');
|
|
266
|
+
if (zero.test(value) && !/calc\(/.test(value))
|
|
267
|
+
report(node, 'length-zero-no-unit', 'Unexpected unit on a zero length');
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
const decls = kids.filter((n) => n.type === 'decl');
|
|
273
|
+
const seen = new Map();
|
|
274
|
+
decls.forEach((d, i) => {
|
|
275
|
+
if (d.prop.startsWith('$') || d.prop.startsWith('--')) return;
|
|
276
|
+
const before = seen.get(d.prop);
|
|
277
|
+
const consecutive = before !== undefined && decls[i - 1] === decls[before];
|
|
278
|
+
if (before !== undefined && !(consecutive && decls[before].value !== d.value))
|
|
279
|
+
report(d, 'declaration-block-no-duplicate-properties', `Duplicate property ${d.prop}`);
|
|
280
|
+
seen.set(d.prop, i);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
let run = [];
|
|
284
|
+
const flush = () => {
|
|
285
|
+
const known = run.filter((d) => RANK.has(unprefixed(d.prop)));
|
|
286
|
+
const sorted = [...known].sort(
|
|
287
|
+
(a, b) => RANK.get(unprefixed(a.prop)) - RANK.get(unprefixed(b.prop)),
|
|
288
|
+
);
|
|
289
|
+
known.forEach((d, i) => {
|
|
290
|
+
if (
|
|
291
|
+
d !== sorted[i] &&
|
|
292
|
+
!known
|
|
293
|
+
.slice(0, i)
|
|
294
|
+
.every((p) => RANK.get(unprefixed(p.prop)) <= RANK.get(unprefixed(d.prop)))
|
|
295
|
+
) {
|
|
296
|
+
const before = known
|
|
297
|
+
.slice(0, i)
|
|
298
|
+
.find((p) => RANK.get(unprefixed(p.prop)) > RANK.get(unprefixed(d.prop)));
|
|
299
|
+
report(
|
|
300
|
+
d,
|
|
301
|
+
'order/properties-order',
|
|
302
|
+
`Expected "${d.prop}" to come before "${before.prop}"`,
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
if (fix && known.some((d, i) => d !== sorted[i])) {
|
|
307
|
+
const slots = known.map((d) => ({ before: d.raws.before }));
|
|
308
|
+
const nodes = run.slice();
|
|
309
|
+
const positions = known.map((d) => nodes.indexOf(d));
|
|
310
|
+
const holders = positions.map((p) => nodes[p]);
|
|
311
|
+
sorted.forEach((d, i) => {
|
|
312
|
+
holders[i].replaceWith(d.clone({ raws: { ...d.raws, before: slots[i].before } }));
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
run = [];
|
|
316
|
+
};
|
|
317
|
+
for (const node of kids) {
|
|
318
|
+
if (node.type === 'decl') run.push(node);
|
|
319
|
+
else if (node.type !== 'comment') flush();
|
|
320
|
+
}
|
|
321
|
+
flush();
|
|
322
|
+
};
|
|
323
|
+
visit(root, [], 0);
|
|
324
|
+
|
|
325
|
+
if (fix) {
|
|
326
|
+
const out = root.toString();
|
|
327
|
+
if (out !== source) writeFileSync(file, out);
|
|
328
|
+
}
|
|
329
|
+
return problems;
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const fix = process.argv.includes('--fix');
|
|
333
|
+
const given = process.argv.slice(2).filter((a) => !a.startsWith('--'));
|
|
334
|
+
const targets = given.length ? given : files(inside(repo, options.source ?? 'src'));
|
|
335
|
+
let total = 0;
|
|
336
|
+
for (const file of targets) {
|
|
337
|
+
const problems = fix ? (lintFile(file, true), lintFile(file, false)) : lintFile(file, false);
|
|
338
|
+
for (const p of problems.sort((a, b) => a.line - b.line)) {
|
|
339
|
+
console.error(
|
|
340
|
+
`${relative(repo, file).replaceAll('\\', '/')}:${p.line} ${p.message} (${p.rule})`,
|
|
341
|
+
);
|
|
342
|
+
total += 1;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (total) {
|
|
346
|
+
console.error(`\n${total} SCSS problem${total === 1 ? '' : 's'}.`);
|
|
347
|
+
process.exit(1);
|
|
348
|
+
}
|
|
349
|
+
console.log(`SCSS lint passed (${targets.length} files).`);
|
|
@@ -0,0 +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
|
+
}
|