@better-css-modules/core 0.1.2 → 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.
- package/README.md +38 -45
- package/dist/dts-BWBpx_ii.mjs +1492 -0
- package/dist/dts-BjIczsCF.d.mts +275 -0
- package/dist/index.d.mts +16 -58
- package/dist/index.mjs +2377 -85
- package/dist/internal.d.mts +23 -0
- package/dist/internal.mjs +94 -0
- package/package.json +31 -20
- package/dist/generator-BlFEyanZ.mjs +0 -105
- package/dist/generator-Dy0W5B1c.cjs +0 -179
- package/dist/index.cjs +0 -130
- package/dist/index.d.cts +0 -62
- package/dist/loader.cjs +0 -16
- package/dist/loader.d.cts +0 -3
- package/dist/loader.d.mts +0 -4
- package/dist/loader.mjs +0 -16
package/dist/index.mjs
CHANGED
|
@@ -1,117 +1,2409 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { C as find, D as property, E as parse, O as walk$1, S as valueStart, T as lexer, _ as sortDiagnostics, a as resolveLayer, b as loadConfig, c as loadGlobalCss, d as findCssModules, f as loadCssModules, g as formatGitHubAnnotation, h as formatDiagnostic, m as tokenCategories, o as declaresToken, p as categoryOf, r as checkLayer, s as isForeign, t as generate, u as defaultIgnore, v as ConfigError, w as generate$1, x as paramsStart, y as defineConfig } from "./dts-BWBpx_ii.mjs";
|
|
2
|
+
import fs from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
|
-
import
|
|
4
|
+
import { ResolverFactory } from "oxc-resolver";
|
|
4
5
|
import fg from "fast-glob";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
import { parseSync } from "oxc-parser";
|
|
7
|
+
//#region src/breakpoint.ts
|
|
8
|
+
/** Media features that compare the width of the viewport. */
|
|
9
|
+
const WIDTH_FEATURES = /* @__PURE__ */ new Set([
|
|
10
|
+
"width",
|
|
11
|
+
"min-width",
|
|
12
|
+
"max-width"
|
|
13
|
+
]);
|
|
8
14
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
15
|
+
* The breakpoints the global CSS declares. A media query cannot use var(), so
|
|
16
|
+
* only a token whose value is one length can stand for a width there.
|
|
11
17
|
*/
|
|
12
|
-
function
|
|
13
|
-
const
|
|
14
|
-
for (const
|
|
15
|
-
|
|
16
|
-
|
|
18
|
+
function breakpointsOf(tokens) {
|
|
19
|
+
const breakpoints = [];
|
|
20
|
+
for (const token of tokens.values()) {
|
|
21
|
+
if (token.category !== "breakpoint") continue;
|
|
22
|
+
const length = lengthOfToken(token);
|
|
23
|
+
if (length) breakpoints.push({
|
|
24
|
+
name: token.name,
|
|
25
|
+
text: token.value,
|
|
26
|
+
...length
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
return breakpoints;
|
|
30
|
+
}
|
|
31
|
+
/** Report each width in the conditions of `@media` that is not a breakpoint. */
|
|
32
|
+
function checkMediaQuery(atRule, breakpoints, file) {
|
|
33
|
+
const text = atRule.raws.params?.raw ?? atRule.params;
|
|
34
|
+
let prelude;
|
|
35
|
+
try {
|
|
36
|
+
prelude = parse(text, {
|
|
37
|
+
context: "atrulePrelude",
|
|
38
|
+
atrule: "media",
|
|
39
|
+
positions: true,
|
|
40
|
+
...paramsStart(atRule)
|
|
41
|
+
});
|
|
42
|
+
} catch {
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
const diagnostics = [];
|
|
46
|
+
walk$1(prelude, (node) => {
|
|
47
|
+
for (const width of widthsOf(node)) {
|
|
48
|
+
const message = problemWith(width, text, breakpoints);
|
|
49
|
+
if (message && width.loc) {
|
|
50
|
+
const { start, end } = width.loc;
|
|
51
|
+
diagnostics.push({
|
|
52
|
+
file,
|
|
53
|
+
line: start.line,
|
|
54
|
+
column: start.column,
|
|
55
|
+
endLine: end.line,
|
|
56
|
+
endColumn: end.column,
|
|
57
|
+
rule: "tokens/breakpoint",
|
|
58
|
+
message
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
return diagnostics;
|
|
17
64
|
}
|
|
18
65
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
66
|
+
* Report a breakpoint token whose value is not one length, at its declaration:
|
|
67
|
+
* no media query can be written with it.
|
|
21
68
|
*/
|
|
22
|
-
function
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
return
|
|
69
|
+
function checkBreakpointToken(token) {
|
|
70
|
+
if (token.category !== "breakpoint" || lengthOfToken(token)) return [];
|
|
71
|
+
const range = token.node.type === "decl" ? valueRange(token.node) : nameRange(token.node);
|
|
72
|
+
if (!range) return [];
|
|
73
|
+
return [{
|
|
74
|
+
file: token.file,
|
|
75
|
+
line: range.start.line,
|
|
76
|
+
column: range.start.column,
|
|
77
|
+
endLine: range.end.line,
|
|
78
|
+
endColumn: range.end.column,
|
|
79
|
+
rule: "tokens/breakpoint",
|
|
80
|
+
message: `${token.name} must be one length such as 48rem; media queries compare widths with its value`
|
|
81
|
+
}];
|
|
26
82
|
}
|
|
83
|
+
/** The values a media feature compares the width with: `(min-width: <v>)`, `(<v> <= width < <v>)`. */
|
|
84
|
+
function widthsOf(node) {
|
|
85
|
+
if (node.type === "Feature") return node.value && WIDTH_FEATURES.has(node.name.toLowerCase()) ? [node.value] : [];
|
|
86
|
+
if (node.type !== "FeatureRange") return [];
|
|
87
|
+
const sides = [
|
|
88
|
+
node.left,
|
|
89
|
+
node.middle,
|
|
90
|
+
node.right
|
|
91
|
+
].filter((side) => side !== null);
|
|
92
|
+
const feature = sides.find((side) => side.type === "Identifier" && side.name.toLowerCase() === "width");
|
|
93
|
+
return feature ? sides.filter((side) => side !== feature) : [];
|
|
94
|
+
}
|
|
95
|
+
function problemWith(node, text, breakpoints) {
|
|
96
|
+
const length = lengthOf(node);
|
|
97
|
+
const matches = (breakpoint) => breakpoint.amount === length?.amount && breakpoint.unit === length.unit;
|
|
98
|
+
if (length && (length.amount === 0 || breakpoints.some(matches))) return null;
|
|
99
|
+
if (node.type === "Function" && node.name.toLowerCase() === "var") {
|
|
100
|
+
const reference = node.children.first;
|
|
101
|
+
const breakpoint = breakpoints.find(({ name }) => reference?.type === "Identifier" && reference.name === name);
|
|
102
|
+
if (breakpoint) return `var(${breakpoint.name}) does not work in a media query; write ${breakpoint.text}`;
|
|
103
|
+
}
|
|
104
|
+
const raw = node.loc ? text.slice(node.loc.start.offset, node.loc.end.offset) : generate$1(node);
|
|
105
|
+
const hint = breakpoints.length > 0 ? `the breakpoints are ${breakpoints.map(({ name, text }) => `${text} (${name})`).join(", ")}` : "no --breakpoint-* token is one length";
|
|
106
|
+
return `${raw.replace(/\s+/g, " ")} is not a breakpoint; ${hint}`;
|
|
107
|
+
}
|
|
108
|
+
/** The length a token's value is, when it is one. */
|
|
109
|
+
function lengthOfToken(token) {
|
|
110
|
+
let value;
|
|
111
|
+
try {
|
|
112
|
+
value = parse(token.value, { context: "value" });
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
const nodes = value.type === "Value" ? value.children.toArray() : [];
|
|
117
|
+
return nodes.length === 1 ? lengthOf(nodes[0]) : null;
|
|
118
|
+
}
|
|
119
|
+
/** A length written as one number and unit, or zero. */
|
|
120
|
+
function lengthOf(node) {
|
|
121
|
+
if (node.type === "Number" && Number(node.value) === 0) return {
|
|
122
|
+
amount: 0,
|
|
123
|
+
unit: ""
|
|
124
|
+
};
|
|
125
|
+
if (node.type !== "Dimension" || lexer.matchType("length", node).matched === null) return null;
|
|
126
|
+
return {
|
|
127
|
+
amount: Number(node.value),
|
|
128
|
+
unit: node.unit.toLowerCase()
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function valueRange(declaration) {
|
|
132
|
+
const start = valueStart(declaration);
|
|
133
|
+
if (!start) return null;
|
|
134
|
+
const lines = (declaration.raws.value?.raw ?? declaration.value).split("\n");
|
|
135
|
+
const last = lines[lines.length - 1];
|
|
136
|
+
return {
|
|
137
|
+
start,
|
|
138
|
+
end: lines.length === 1 ? {
|
|
139
|
+
line: start.line,
|
|
140
|
+
column: start.column + last.length
|
|
141
|
+
} : {
|
|
142
|
+
line: start.line + lines.length - 1,
|
|
143
|
+
column: last.length + 1
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function nameRange(atRule) {
|
|
148
|
+
const start = paramsStart(atRule);
|
|
149
|
+
return {
|
|
150
|
+
start,
|
|
151
|
+
end: {
|
|
152
|
+
line: start.line,
|
|
153
|
+
column: start.column + atRule.params.length
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/rules.ts
|
|
159
|
+
/** Every rule but the token categories, with how it can be disabled. */
|
|
160
|
+
const RULES = {
|
|
161
|
+
"usage/unused-class": "either",
|
|
162
|
+
"usage/unused-module": "file-wide",
|
|
163
|
+
"usage/unanalyzable": "file-wide",
|
|
164
|
+
"pure/selector": "either",
|
|
165
|
+
"pure/subject": "either",
|
|
166
|
+
"pure/global": "either",
|
|
167
|
+
"pure/id": "either",
|
|
168
|
+
"pure/important": "either",
|
|
169
|
+
"pure/at-rule": "either",
|
|
170
|
+
"pure/value": "either",
|
|
171
|
+
"tokens/unknown": "either",
|
|
172
|
+
"tokens/internal": "either",
|
|
173
|
+
"tokens/declaration": "either",
|
|
174
|
+
"layer/nested": "either",
|
|
175
|
+
"layer/composes": { never: "the plugins stop the build at composes in a layer" },
|
|
176
|
+
syntax: { never: "the bundlers cannot read the stylesheet either" },
|
|
177
|
+
"invalid-composes": { never: "the bundlers reject composes there" },
|
|
178
|
+
"invalid-disable": { never: "fix or remove the disable comment instead" }
|
|
179
|
+
};
|
|
27
180
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
181
|
+
* What is wrong with naming a rule in a disable comment of the next-line or
|
|
182
|
+
* the file-wide form, or null when nothing is.
|
|
30
183
|
*/
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
184
|
+
function problemDisabling(rule, fileWide) {
|
|
185
|
+
if (rule.startsWith("tokens/") && Object.hasOwn(tokenCategories, rule.slice(7))) return null;
|
|
186
|
+
if (!Object.hasOwn(RULES, rule)) return `unknown rule "${rule}"`;
|
|
187
|
+
const disabling = RULES[rule];
|
|
188
|
+
if (typeof disabling === "object") return `${rule} cannot be disabled: ${disabling.never}`;
|
|
189
|
+
if (disabling === "file-wide" && !fileWide) return `${rule} can only be disabled file-wide: write better-css-modules-disable at the top of the file`;
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
//#endregion
|
|
193
|
+
//#region src/disable.ts
|
|
194
|
+
const PREFIX = "better-css-modules-";
|
|
195
|
+
const DISABLE_NEXT_LINE = "better-css-modules-disable-next-line";
|
|
196
|
+
const DISABLE = "better-css-modules-disable";
|
|
197
|
+
/**
|
|
198
|
+
* Read the disable comments of a stylesheet. The next-line form silences the
|
|
199
|
+
* rules it names for the rule, at-rule or declaration that starts on the next
|
|
200
|
+
* line; the file-wide form, before anything but comments, silences them in
|
|
201
|
+
* the whole file. A malformed comment silences nothing and is reported.
|
|
202
|
+
*/
|
|
203
|
+
function readDisableComments(root, file) {
|
|
204
|
+
const directives = [];
|
|
205
|
+
const malformed = [];
|
|
206
|
+
const first = root.nodes.find((node) => node.type !== "comment");
|
|
207
|
+
root.walkComments((comment) => {
|
|
208
|
+
const [directive] = comment.text.split(/\s/, 1);
|
|
209
|
+
if (!directive.startsWith(PREFIX)) return;
|
|
210
|
+
if (directive !== DISABLE_NEXT_LINE && directive !== DISABLE) {
|
|
211
|
+
malformed.push(invalid(file, comment, `unknown directive "${directive}"; write ${DISABLE_NEXT_LINE} or ${DISABLE}`));
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const body = comment.text.slice(directive.length);
|
|
215
|
+
const separator = /(?:^|\s)--(?:\s|$)/.exec(body);
|
|
216
|
+
const reason = separator ? body.slice(separator.index + separator[0].length).trim() : "";
|
|
217
|
+
const rules = (separator ? body.slice(0, separator.index) : body).split(/[\s,]+/).filter(Boolean);
|
|
218
|
+
const messages = [...directive === DISABLE && (comment.parent !== root || first !== void 0 && root.index(first) < root.index(comment)) ? ["a file-wide disable comment must come before the first rule, at-rule or declaration"] : [], ...reason === "" ? ["a disable comment needs a reason: add \" -- <why>\" after the rule names"] : rules.length === 0 ? ["a disable comment must name the rules it disables, such as tokens/color"] : rules.map((rule) => problemDisabling(rule, directive === DISABLE)).filter((message) => message !== null)];
|
|
219
|
+
malformed.push(...messages.map((message) => invalid(file, comment, message)));
|
|
220
|
+
if (messages.length > 0) return;
|
|
221
|
+
const end = comment.source?.end?.line ?? 0;
|
|
222
|
+
directives.push({
|
|
223
|
+
comment,
|
|
224
|
+
rules,
|
|
225
|
+
line: directive === DISABLE ? null : end + 1,
|
|
226
|
+
silenced: /* @__PURE__ */ new Set()
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
const keep = (node, found) => {
|
|
230
|
+
const line = node?.source?.start?.line;
|
|
231
|
+
const applying = directives.filter((directive) => directive.line === null || directive.line === line);
|
|
232
|
+
return found.filter(({ rule }) => {
|
|
233
|
+
const silencing = applying.filter(({ rules }) => rules.includes(rule));
|
|
234
|
+
for (const directive of silencing) directive.silenced.add(rule);
|
|
235
|
+
return silencing.length === 0;
|
|
236
|
+
});
|
|
237
|
+
};
|
|
238
|
+
const problems = () => [...malformed, ...directives.flatMap(({ comment, rules, line, silenced }) => rules.filter((rule) => !silenced.has(rule)).map((rule) => invalid(file, comment, line === null ? `${rule} is disabled, but nothing reports it for this file` : `${rule} is disabled, but nothing on the next line reports it`)))];
|
|
239
|
+
return {
|
|
240
|
+
keep,
|
|
241
|
+
problems
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function invalid(file, comment, message) {
|
|
245
|
+
const start = comment.source?.start ?? {
|
|
246
|
+
line: 1,
|
|
247
|
+
column: 1
|
|
248
|
+
};
|
|
249
|
+
const end = comment.source?.end ?? start;
|
|
250
|
+
return {
|
|
251
|
+
file,
|
|
252
|
+
line: start.line,
|
|
253
|
+
column: start.column,
|
|
254
|
+
endLine: end.line,
|
|
255
|
+
endColumn: end.column + 1,
|
|
256
|
+
rule: "invalid-disable",
|
|
257
|
+
message
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
//#endregion
|
|
261
|
+
//#region src/pure.ts
|
|
262
|
+
/**
|
|
263
|
+
* At-rules that define something for the whole document, which takes effect
|
|
264
|
+
* only while the module holding them is loaded. What they hold are
|
|
265
|
+
* descriptors, not properties of an element.
|
|
266
|
+
*/
|
|
267
|
+
const GLOBAL_AT_RULES = /* @__PURE__ */ new Set([
|
|
268
|
+
"font-face",
|
|
269
|
+
"property",
|
|
270
|
+
"import",
|
|
271
|
+
"counter-style",
|
|
272
|
+
"page",
|
|
273
|
+
"font-palette-values",
|
|
274
|
+
"font-feature-values",
|
|
275
|
+
"namespace",
|
|
276
|
+
"view-transition",
|
|
277
|
+
"color-profile"
|
|
278
|
+
]);
|
|
279
|
+
/**
|
|
280
|
+
* Check one CSS Module against the pure rules, handing the diagnostics of each
|
|
281
|
+
* rule, at-rule and declaration to `report` with the node they belong to.
|
|
282
|
+
*/
|
|
283
|
+
function checkPure(root, file, report) {
|
|
284
|
+
walkContainer(root, {
|
|
285
|
+
nested: false,
|
|
286
|
+
scoped: false,
|
|
287
|
+
local: true
|
|
288
|
+
}, {
|
|
289
|
+
file,
|
|
290
|
+
report
|
|
291
|
+
});
|
|
292
|
+
root.walkDecls((declaration) => {
|
|
293
|
+
if (declaration.important) report(declaration, checkImportant(declaration, file));
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
function walkContainer(container, context, checker) {
|
|
297
|
+
container.each((node) => {
|
|
298
|
+
if (node.type === "rule") visitRule(node, context, checker);
|
|
299
|
+
else if (node.type === "atrule") visitAtRule(node, context, checker);
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
function visitRule(rule, context, checker) {
|
|
303
|
+
const start = rule.source?.start;
|
|
304
|
+
const text = rule.raws.selector?.raw ?? rule.selector;
|
|
305
|
+
const list = start ? parseSelectorList(text, start) : null;
|
|
306
|
+
if (list) checker.report(rule, checkSelectorList(list, text, context, checker.file));
|
|
307
|
+
const trimmed = text.trim();
|
|
308
|
+
const local = trimmed === ":global" ? false : trimmed === ":local" ? true : context.local;
|
|
309
|
+
walkContainer(rule, {
|
|
310
|
+
...context,
|
|
311
|
+
nested: true,
|
|
312
|
+
local
|
|
313
|
+
}, checker);
|
|
314
|
+
}
|
|
315
|
+
function visitAtRule(atRule, context, checker) {
|
|
316
|
+
const name = atRule.name.toLowerCase();
|
|
317
|
+
if (GLOBAL_AT_RULES.has(name)) {
|
|
318
|
+
checker.report(atRule, checkGlobalAtRule(atRule, checker.file));
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (name === "value") {
|
|
322
|
+
checker.report(atRule, checkValue(atRule, checker.file));
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (name.endsWith("keyframes")) {
|
|
326
|
+
checker.report(atRule, checkKeyframesName(atRule, checker.file));
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const inner = name === "scope" ? visitScope(atRule, context, checker) : context;
|
|
330
|
+
if (atRule.nodes) walkContainer(atRule, inner, checker);
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* The root of an @scope is local when its selectors have a local subject, or,
|
|
334
|
+
* without one, when the @scope is nested in a style rule: that rule is the root.
|
|
335
|
+
*/
|
|
336
|
+
function visitScope(atRule, context, checker) {
|
|
337
|
+
const text = atRule.raws.params?.raw ?? atRule.params;
|
|
338
|
+
const base = paramsStart(atRule);
|
|
339
|
+
let prelude;
|
|
340
|
+
try {
|
|
341
|
+
prelude = parse(text, {
|
|
342
|
+
context: "atrulePrelude",
|
|
343
|
+
atrule: "scope",
|
|
344
|
+
positions: true,
|
|
345
|
+
line: base.line,
|
|
346
|
+
column: base.column
|
|
347
|
+
});
|
|
348
|
+
} catch {
|
|
349
|
+
return context;
|
|
350
|
+
}
|
|
351
|
+
const scope = find(prelude, (node) => node.type === "Scope");
|
|
352
|
+
const root = scope?.root?.type === "SelectorList" ? scope.root : null;
|
|
353
|
+
const scan = {
|
|
354
|
+
local: false,
|
|
355
|
+
globals: [],
|
|
356
|
+
ids: []
|
|
357
|
+
};
|
|
358
|
+
for (const list of [root, scope?.limit]) if (list?.type === "SelectorList") scanList(list, context.local, false, text, scan);
|
|
359
|
+
checker.report(atRule, [...scan.globals.map((found) => globalDiagnostic(found, checker.file)), ...scan.ids.map((found) => idDiagnostic(found, checker.file))]);
|
|
360
|
+
const rooted = root ? hasLocalSubjects(root, context.local, context.nested) : context.nested;
|
|
361
|
+
return {
|
|
362
|
+
...context,
|
|
363
|
+
scoped: context.scoped || rooted
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
function checkSelectorList(list, text, context, file) {
|
|
367
|
+
const diagnostics = [];
|
|
368
|
+
list.children.forEach((selector) => {
|
|
369
|
+
if (selector.type !== "Selector") return;
|
|
370
|
+
const scan = {
|
|
371
|
+
local: false,
|
|
372
|
+
globals: [],
|
|
373
|
+
ids: []
|
|
374
|
+
};
|
|
375
|
+
scanSelector(selector, context.local, false, text, scan);
|
|
376
|
+
if (!context.nested && !scan.local) {
|
|
377
|
+
const hint = context.scoped ? ", and bundlers do not count the root of a top-level @scope; nest the @scope inside the rule of its root class" : "; every selector of a CSS Module needs one";
|
|
378
|
+
diagnostics.push(diagnosticAt$1({
|
|
379
|
+
node: selector,
|
|
380
|
+
text
|
|
381
|
+
}, file, "pure/selector", (written) => `${written} has no local class${hint}`));
|
|
382
|
+
} else if (!context.scoped) {
|
|
383
|
+
const subject = subjectOf(selector, context.local);
|
|
384
|
+
if (!isLocalCompound(subject, context.nested) && !isReportedElsewhere(subject)) diagnostics.push(subjectDiagnostic(subject, text, file));
|
|
385
|
+
}
|
|
386
|
+
diagnostics.push(...scan.globals.map((found) => globalDiagnostic(found, file)), ...scan.ids.map((found) => idDiagnostic(found, file)));
|
|
40
387
|
});
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
388
|
+
return diagnostics;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Scan for local classes, :global and ids. `inGlobal` is set inside the
|
|
392
|
+
* argument of `:global()`, which stays global whatever `:local` it holds:
|
|
393
|
+
* bundlers emit it as written, and no key is generated for it.
|
|
394
|
+
*/
|
|
395
|
+
function scanList(list, local, inGlobal, text, scan) {
|
|
396
|
+
list.children.forEach((selector) => {
|
|
397
|
+
if (selector.type === "Selector") scanSelector(selector, local, inGlobal, text, scan);
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
function scanSelector(selector, local, inGlobal, text, scan) {
|
|
401
|
+
let mode = local;
|
|
402
|
+
selector.children.forEach((node) => {
|
|
403
|
+
if (node.type === "ClassSelector") scan.local ||= mode;
|
|
404
|
+
else if (node.type === "IdSelector") {
|
|
405
|
+
scan.local ||= mode;
|
|
406
|
+
scan.ids.push({
|
|
407
|
+
node,
|
|
408
|
+
text
|
|
409
|
+
});
|
|
410
|
+
} else if (node.type === "PseudoClassSelector") {
|
|
411
|
+
const name = node.name.toLowerCase();
|
|
412
|
+
if (name !== "global" && name !== "local") {
|
|
413
|
+
scanArguments(node.children, mode, inGlobal, text, scan);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (name === "global") scan.globals.push({
|
|
417
|
+
node,
|
|
418
|
+
text
|
|
419
|
+
});
|
|
420
|
+
const switched = name === "local" && !inGlobal;
|
|
421
|
+
if (node.children === null) {
|
|
422
|
+
mode = switched;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const argument = argumentOf(node);
|
|
426
|
+
if (argument) scanList(argument.list, switched, inGlobal || name === "global", argument.text, scan);
|
|
427
|
+
} else if (node.type === "PseudoElementSelector") {
|
|
428
|
+
if (node.name.toLowerCase().startsWith("view-transition-")) return;
|
|
429
|
+
scanArguments(node.children, mode, inGlobal, text, scan);
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
function scanArguments(children, local, inGlobal, text, scan) {
|
|
434
|
+
children?.forEach((child) => {
|
|
435
|
+
if (child.type === "SelectorList") scanList(child, local, inGlobal, text, scan);
|
|
436
|
+
else if (child.type === "Selector") scanSelector(child, local, inGlobal, text, scan);
|
|
437
|
+
else if (child.type === "Nth" && child.selector) scanList(child.selector, local, inGlobal, text, scan);
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
/** css-tree does not know `:global()` and `:local()`, so their argument is Raw. */
|
|
441
|
+
function argumentOf(node) {
|
|
442
|
+
const raw = node.children?.first;
|
|
443
|
+
if (raw?.type !== "Raw" || !raw.loc) return null;
|
|
444
|
+
const list = parseSelectorList(raw.value, raw.loc.start);
|
|
445
|
+
return list ? {
|
|
446
|
+
list,
|
|
447
|
+
text: raw.value
|
|
448
|
+
} : null;
|
|
449
|
+
}
|
|
450
|
+
/** The compound after the last combinator: what an element must match to be styled. */
|
|
451
|
+
function subjectOf(selector, local) {
|
|
452
|
+
let mode = local;
|
|
453
|
+
let parts = [];
|
|
454
|
+
selector.children.forEach((node) => {
|
|
455
|
+
if (node.type === "Combinator") parts = [];
|
|
456
|
+
else if (node.type === "PseudoClassSelector" && node.children === null && isScoping(node)) mode = node.name.toLowerCase() === "local";
|
|
457
|
+
else parts.push({
|
|
458
|
+
node,
|
|
459
|
+
local: mode
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
return parts;
|
|
463
|
+
}
|
|
464
|
+
function isLocalCompound(parts, nested) {
|
|
465
|
+
return parts.some(({ node, local }) => {
|
|
466
|
+
switch (node.type) {
|
|
467
|
+
case "ClassSelector": return local;
|
|
468
|
+
case "NestingSelector": return nested;
|
|
469
|
+
case "PseudoClassSelector": {
|
|
470
|
+
const name = node.name.toLowerCase();
|
|
471
|
+
if (name === "local") {
|
|
472
|
+
const argument = argumentOf(node);
|
|
473
|
+
return argument !== null && hasLocalSubjects(argument.list, true, nested);
|
|
474
|
+
}
|
|
475
|
+
const [argument] = node.children?.toArray() ?? [];
|
|
476
|
+
if ((name === "is" || name === "where") && argument?.type === "SelectorList") return hasLocalSubjects(argument, local, nested);
|
|
477
|
+
if ((name === "nth-child" || name === "nth-last-child") && argument?.type === "Nth") return argument.selector !== null && hasLocalSubjects(argument.selector, local, nested);
|
|
478
|
+
return false;
|
|
479
|
+
}
|
|
480
|
+
default: return false;
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
function hasLocalSubjects(list, local, nested) {
|
|
485
|
+
return list.children.toArray().every((selector) => selector.type === "Selector" && isLocalCompound(subjectOf(selector, local), nested));
|
|
486
|
+
}
|
|
487
|
+
/** A subject made global or written as an id is reported as pure/global or pure/id. */
|
|
488
|
+
function isReportedElsewhere(parts) {
|
|
489
|
+
return parts.some(({ node, local }) => !local || find(node, (child) => child.type === "IdSelector" || child.type === "PseudoClassSelector" && child.name.toLowerCase() === "global") !== null);
|
|
490
|
+
}
|
|
491
|
+
function isScoping(node) {
|
|
492
|
+
const name = node.name.toLowerCase();
|
|
493
|
+
return name === "global" || name === "local";
|
|
494
|
+
}
|
|
495
|
+
function subjectDiagnostic(parts, text, file) {
|
|
496
|
+
const first = parts[0].node.loc;
|
|
497
|
+
const last = parts[parts.length - 1].node.loc;
|
|
498
|
+
const written = first && last ? text.slice(first.start.offset, last.end.offset) : "";
|
|
499
|
+
return {
|
|
500
|
+
file,
|
|
501
|
+
line: first?.start.line ?? 1,
|
|
502
|
+
column: first?.start.column ?? 1,
|
|
503
|
+
endLine: last?.end.line,
|
|
504
|
+
endColumn: last?.end.column,
|
|
505
|
+
rule: "pure/subject",
|
|
506
|
+
message: `${written} is not a local class; give the element a class of its own, or style markup the component does not write inside @scope`
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function globalDiagnostic(found, file) {
|
|
510
|
+
return diagnosticAt$1(found, file, "pure/global", (written) => `${written} reaches outside this module; a mode overrides tokens in the global CSS, and markup the component does not write is styled inside @scope`);
|
|
511
|
+
}
|
|
512
|
+
function idDiagnostic(found, file) {
|
|
513
|
+
return diagnosticAt$1(found, file, "pure/id", (written) => `${written} is an id; its specificity defeats overrides from outside the component, so use a class`);
|
|
514
|
+
}
|
|
515
|
+
function diagnosticAt$1({ node, text }, file, rule, message) {
|
|
516
|
+
const loc = node.loc;
|
|
517
|
+
const written = loc ? text.slice(loc.start.offset, loc.end.offset).replace(/\s+/g, " ") : "";
|
|
518
|
+
return {
|
|
519
|
+
file,
|
|
520
|
+
line: loc?.start.line ?? 1,
|
|
521
|
+
column: loc?.start.column ?? 1,
|
|
522
|
+
endLine: loc?.end.line,
|
|
523
|
+
endColumn: loc?.end.column,
|
|
524
|
+
rule,
|
|
525
|
+
message: message(written)
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
function checkGlobalAtRule(atRule, file) {
|
|
529
|
+
const start = atRule.source?.start;
|
|
530
|
+
if (!start) return [];
|
|
531
|
+
return [{
|
|
532
|
+
file,
|
|
533
|
+
line: start.line,
|
|
534
|
+
column: start.column,
|
|
535
|
+
endLine: start.line,
|
|
536
|
+
endColumn: start.column + 1 + atRule.name.length,
|
|
537
|
+
rule: "pure/at-rule",
|
|
538
|
+
message: `@${atRule.name} is global and takes effect only while this module is loaded; move it to the global CSS`
|
|
539
|
+
}];
|
|
540
|
+
}
|
|
541
|
+
function checkValue(atRule, file) {
|
|
542
|
+
const start = atRule.source?.start;
|
|
543
|
+
if (!start) return [];
|
|
544
|
+
return [{
|
|
545
|
+
file,
|
|
546
|
+
line: start.line,
|
|
547
|
+
column: start.column,
|
|
548
|
+
endLine: start.line,
|
|
549
|
+
endColumn: start.column + 1 + atRule.name.length,
|
|
550
|
+
rule: "pure/value",
|
|
551
|
+
message: "@value is not CSS: lightningcss (Turbopack) ignores it, and its names bypass the token checks; use a custom property"
|
|
552
|
+
}];
|
|
553
|
+
}
|
|
554
|
+
function checkKeyframesName(atRule, file) {
|
|
555
|
+
const name = atRule.params;
|
|
556
|
+
if (!name.toLowerCase().startsWith(":global")) return [];
|
|
557
|
+
const start = paramsStart(atRule);
|
|
558
|
+
return [{
|
|
559
|
+
file,
|
|
560
|
+
line: start.line,
|
|
561
|
+
column: start.column,
|
|
562
|
+
endLine: start.line,
|
|
563
|
+
endColumn: start.column + name.length,
|
|
564
|
+
rule: "pure/global",
|
|
565
|
+
message: `${name} reaches outside this module; shared keyframes belong in the global CSS`
|
|
566
|
+
}];
|
|
567
|
+
}
|
|
568
|
+
function checkImportant(declaration, file) {
|
|
569
|
+
const start = valueStart(declaration);
|
|
570
|
+
const value = declaration.raws.value?.raw ?? declaration.value;
|
|
571
|
+
const flag = /!\s*important/i.exec(declaration.raws.important ?? " !important");
|
|
572
|
+
const input = declaration.source?.input;
|
|
573
|
+
if (!start || !flag || !input) return [];
|
|
574
|
+
const offset = start.offset + value.length + flag.index;
|
|
575
|
+
const first = input.fromOffset(offset);
|
|
576
|
+
const end = input.fromOffset(offset + flag[0].length);
|
|
577
|
+
if (!first || !end) return [];
|
|
578
|
+
return [{
|
|
579
|
+
file,
|
|
580
|
+
line: first.line,
|
|
581
|
+
column: first.col,
|
|
582
|
+
endLine: end.line,
|
|
583
|
+
endColumn: end.col,
|
|
584
|
+
rule: "pure/important",
|
|
585
|
+
message: "!important defeats overrides from outside the component and the order of @layer"
|
|
586
|
+
}];
|
|
587
|
+
}
|
|
588
|
+
function parseSelectorList(text, base) {
|
|
589
|
+
try {
|
|
590
|
+
const node = parse(text, {
|
|
591
|
+
context: "selectorList",
|
|
592
|
+
positions: true,
|
|
593
|
+
line: base.line,
|
|
594
|
+
column: base.column
|
|
595
|
+
});
|
|
596
|
+
return node.type === "SelectorList" ? node : null;
|
|
597
|
+
} catch {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
//#endregion
|
|
602
|
+
//#region ../../node_modules/.pnpm/oxc-walker@1.1.1_@oxc-project+types@0.151.0_oxc-parser@0.151.0/node_modules/oxc-walker/dist/index.mjs
|
|
603
|
+
function isNode(v) {
|
|
604
|
+
return v !== null && typeof v === "object" && typeof v.type === "string";
|
|
605
|
+
}
|
|
606
|
+
var WalkerBase = class {
|
|
607
|
+
scopeTracker;
|
|
608
|
+
enter;
|
|
609
|
+
leave;
|
|
610
|
+
contextEnter = {
|
|
611
|
+
skip: () => {
|
|
612
|
+
this._skip = true;
|
|
613
|
+
},
|
|
614
|
+
remove: () => {
|
|
615
|
+
this._remove = true;
|
|
616
|
+
},
|
|
617
|
+
replace: (node) => {
|
|
618
|
+
this._replacement = node;
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
contextLeave = {
|
|
622
|
+
remove: this.contextEnter.remove,
|
|
623
|
+
replace: this.contextEnter.replace
|
|
624
|
+
};
|
|
625
|
+
_skip = false;
|
|
626
|
+
_remove = false;
|
|
627
|
+
_replacement = null;
|
|
628
|
+
constructor(handler, options) {
|
|
629
|
+
this.enter = handler.enter;
|
|
630
|
+
this.leave = handler.leave;
|
|
631
|
+
this.scopeTracker = options?.scopeTracker;
|
|
632
|
+
}
|
|
633
|
+
replace(parent, key, index, node) {
|
|
634
|
+
if (!parent || key === null) return;
|
|
635
|
+
if (index !== null) parent[key][index] = node;
|
|
636
|
+
else parent[key] = node;
|
|
637
|
+
}
|
|
638
|
+
insert(parent, key, index, node) {
|
|
639
|
+
if (!parent || key === null) return;
|
|
640
|
+
if (index !== null) parent[key].splice(index, 0, node);
|
|
641
|
+
else parent[key] = node;
|
|
642
|
+
}
|
|
643
|
+
remove(parent, key, index) {
|
|
644
|
+
if (!parent || key === null) return;
|
|
645
|
+
if (index !== null) parent[key].splice(index, 1);
|
|
646
|
+
else delete parent[key];
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
var WalkerSync = class extends WalkerBase {
|
|
650
|
+
constructor(handler, options) {
|
|
651
|
+
super(handler, options);
|
|
652
|
+
}
|
|
653
|
+
traverse(input, key, index, parent) {
|
|
654
|
+
const ctx = {
|
|
655
|
+
key: null,
|
|
656
|
+
index: index ?? null,
|
|
657
|
+
ast: input
|
|
658
|
+
};
|
|
659
|
+
const scopeTracker = this.scopeTracker;
|
|
660
|
+
const enter = this.enter;
|
|
661
|
+
const leave = this.leave;
|
|
662
|
+
const contextEnter = this.contextEnter;
|
|
663
|
+
const contextLeave = this.contextLeave;
|
|
664
|
+
const _walk = (input, parent, key, index, skip) => {
|
|
665
|
+
if (scopeTracker) scopeTracker.processNodeEnter(input);
|
|
666
|
+
let currentNode = input;
|
|
667
|
+
let removedInEnter = false;
|
|
668
|
+
let replacedInEnter = false;
|
|
669
|
+
let skipChildren = skip;
|
|
670
|
+
if (enter && !skip) {
|
|
671
|
+
const _skip = this._skip;
|
|
672
|
+
const _remove = this._remove;
|
|
673
|
+
const _replacement = this._replacement;
|
|
674
|
+
this._skip = false;
|
|
675
|
+
this._remove = false;
|
|
676
|
+
this._replacement = null;
|
|
677
|
+
ctx.key = key;
|
|
678
|
+
ctx.index = index;
|
|
679
|
+
enter.call(contextEnter, input, parent, ctx);
|
|
680
|
+
if (this._replacement && !this._remove) {
|
|
681
|
+
currentNode = this._replacement;
|
|
682
|
+
replacedInEnter = true;
|
|
683
|
+
this.replace(parent, key, index, this._replacement);
|
|
684
|
+
if (scopeTracker) scopeTracker.processNodeEnter(currentNode);
|
|
685
|
+
}
|
|
686
|
+
if (this._remove) {
|
|
687
|
+
removedInEnter = true;
|
|
688
|
+
currentNode = null;
|
|
689
|
+
this.remove(parent, key, index);
|
|
690
|
+
}
|
|
691
|
+
if (this._skip) skipChildren = true;
|
|
692
|
+
this._skip = _skip;
|
|
693
|
+
this._remove = _remove;
|
|
694
|
+
this._replacement = _replacement;
|
|
695
|
+
}
|
|
696
|
+
if ((!skipChildren || scopeTracker) && currentNode) for (const k in currentNode) {
|
|
697
|
+
if (k === "type" || k === "start" || k === "end") continue;
|
|
698
|
+
const node = currentNode[k];
|
|
699
|
+
if (!node || typeof node !== "object") continue;
|
|
700
|
+
if (Array.isArray(node)) for (let i = 0; i < node.length; i++) {
|
|
701
|
+
const child = node[i];
|
|
702
|
+
if (isNode(child)) {
|
|
703
|
+
if (_walk(child, currentNode, k, i, skipChildren) === null) i--;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
else if (typeof node.type === "string") _walk(node, currentNode, k, null, skipChildren);
|
|
707
|
+
}
|
|
708
|
+
if (scopeTracker) {
|
|
709
|
+
if (replacedInEnter) scopeTracker.processNodeLeave(currentNode);
|
|
710
|
+
scopeTracker.processNodeLeave(input);
|
|
711
|
+
}
|
|
712
|
+
if (leave && !skip) {
|
|
713
|
+
const _replacement = this._replacement;
|
|
714
|
+
const _remove = this._remove;
|
|
715
|
+
this._replacement = null;
|
|
716
|
+
this._remove = false;
|
|
717
|
+
ctx.key = key;
|
|
718
|
+
ctx.index = index;
|
|
719
|
+
leave.call(contextLeave, input, parent, ctx);
|
|
720
|
+
if (this._replacement && !this._remove) {
|
|
721
|
+
currentNode = this._replacement;
|
|
722
|
+
if (removedInEnter) this.insert(parent, key, index, this._replacement);
|
|
723
|
+
else this.replace(parent, key, index, this._replacement);
|
|
724
|
+
}
|
|
725
|
+
if (this._remove) {
|
|
726
|
+
currentNode = null;
|
|
727
|
+
this.remove(parent, key, index);
|
|
728
|
+
}
|
|
729
|
+
this._replacement = _replacement;
|
|
730
|
+
this._remove = _remove;
|
|
731
|
+
}
|
|
732
|
+
return currentNode;
|
|
733
|
+
};
|
|
734
|
+
if (!isNode(input)) return null;
|
|
735
|
+
if (scopeTracker) scopeTracker.onWalkStart(input);
|
|
736
|
+
if (scopeTracker && !enter && !leave) {
|
|
737
|
+
const _walkScopesOnly = (input) => {
|
|
738
|
+
scopeTracker.processNodeEnter(input);
|
|
739
|
+
for (const k in input) {
|
|
740
|
+
if (k === "type" || k === "start" || k === "end") continue;
|
|
741
|
+
const node = input[k];
|
|
742
|
+
if (!node || typeof node !== "object") continue;
|
|
743
|
+
if (Array.isArray(node)) for (let i = 0; i < node.length; i++) {
|
|
744
|
+
const child = node[i];
|
|
745
|
+
if (isNode(child)) _walkScopesOnly(child);
|
|
746
|
+
}
|
|
747
|
+
else if (typeof node.type === "string") _walkScopesOnly(node);
|
|
748
|
+
}
|
|
749
|
+
scopeTracker.processNodeLeave(input);
|
|
750
|
+
};
|
|
751
|
+
_walkScopesOnly(input);
|
|
752
|
+
return input;
|
|
753
|
+
}
|
|
754
|
+
return _walk(input, parent ?? null, key ?? null, index ?? null, false);
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
/**
|
|
758
|
+
* Walk the AST with the given options.
|
|
759
|
+
* @param input The AST to walk.
|
|
760
|
+
* @param options The options to be used when walking the AST. Here you can specify the callbacks for entering and leaving nodes, as well as other options.
|
|
761
|
+
*/
|
|
762
|
+
function walk(input, options) {
|
|
763
|
+
return new WalkerSync({
|
|
764
|
+
enter: options.enter,
|
|
765
|
+
leave: options.leave
|
|
766
|
+
}, { scopeTracker: options.scopeTracker }).traverse(input);
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* The node types handled by {@link ScopeTracker.processNodeEnter}.
|
|
770
|
+
* Must list every `case` of its switch statement; a missing entry silently disables
|
|
771
|
+
* scope tracking for that node type (see the drift test in `test/scope-tracker.test.ts`).
|
|
772
|
+
*/
|
|
773
|
+
const SCOPE_ENTER_TYPES = /* @__PURE__ */ new Set([
|
|
774
|
+
"Program",
|
|
775
|
+
"BlockStatement",
|
|
776
|
+
"StaticBlock",
|
|
777
|
+
"TSModuleBlock",
|
|
778
|
+
"FunctionDeclaration",
|
|
779
|
+
"FunctionExpression",
|
|
780
|
+
"ArrowFunctionExpression",
|
|
781
|
+
"VariableDeclaration",
|
|
782
|
+
"ClassDeclaration",
|
|
783
|
+
"ClassExpression",
|
|
784
|
+
"ImportDeclaration",
|
|
785
|
+
"TSEnumDeclaration",
|
|
786
|
+
"TSModuleDeclaration",
|
|
787
|
+
"TSImportEqualsDeclaration",
|
|
788
|
+
"TSDeclareFunction",
|
|
789
|
+
"TSInterfaceDeclaration",
|
|
790
|
+
"TSTypeAliasDeclaration",
|
|
791
|
+
"TSTypeParameter",
|
|
792
|
+
"TSMappedType",
|
|
793
|
+
"TSEnumBody",
|
|
794
|
+
"TSMethodSignature",
|
|
795
|
+
"TSCallSignatureDeclaration",
|
|
796
|
+
"TSConstructSignatureDeclaration",
|
|
797
|
+
"TSFunctionType",
|
|
798
|
+
"TSConstructorType",
|
|
799
|
+
"TSConditionalType",
|
|
800
|
+
"CatchClause",
|
|
801
|
+
"ForStatement",
|
|
802
|
+
"ForOfStatement",
|
|
803
|
+
"ForInStatement",
|
|
804
|
+
"SwitchStatement"
|
|
805
|
+
]);
|
|
806
|
+
/**
|
|
807
|
+
* Tracks variable scopes and identifier declarations within a JavaScript AST.
|
|
808
|
+
*
|
|
809
|
+
* Maintains a stack of scopes, each represented as a map from identifier names to their declaration nodes,
|
|
810
|
+
* enabling efficient lookup of the declaration.
|
|
811
|
+
*
|
|
812
|
+
* The ScopeTracker is designed to integrate with the `walk` function,
|
|
813
|
+
* it automatically manages scope creation and identifier tracking,
|
|
814
|
+
* so only query and inspection methods are exposed for external use.
|
|
815
|
+
*
|
|
816
|
+
* ### Scope tracking
|
|
817
|
+
* A new scope is created when entering blocks, function parameters, loop variables, etc.
|
|
818
|
+
* Note that this representation may split a single JavaScript lexical scope into multiple internal scopes,
|
|
819
|
+
* meaning it doesn't mirror JavaScript’s scoping 1:1.
|
|
820
|
+
*
|
|
821
|
+
* Scopes are represented using a string-based index like `"0-1-2"`, which tracks depth and ancestry.
|
|
822
|
+
*
|
|
823
|
+
* #### Root scope
|
|
824
|
+
* The root scope is represented by an empty string `""`.
|
|
825
|
+
*
|
|
826
|
+
* #### Scope key format
|
|
827
|
+
* Scope keys are hierarchical strings that uniquely identify each scope and its position in the tree.
|
|
828
|
+
* They are constructed using a depth-based indexing scheme, where:
|
|
829
|
+
*
|
|
830
|
+
* - the root scope is represented by an empty string `""`.
|
|
831
|
+
* - the first child scope is `"0"`.
|
|
832
|
+
* - a parallel sibling of `"0"` becomes `"1"`, `"2"`, etc.
|
|
833
|
+
* - a nested scope under `"0"` is `"0-0"`, then its sibling is `"0-1"`, and so on.
|
|
834
|
+
*
|
|
835
|
+
* Each segment in the key corresponds to the zero-based index of the scope at that depth level in
|
|
836
|
+
* the order of AST traversal.
|
|
837
|
+
*
|
|
838
|
+
* ### Additional features
|
|
839
|
+
* - supports freezing the tracker to allow for second passes through the AST without modifying the scope data
|
|
840
|
+
* (useful for doing a pre-pass to collect all identifiers before walking).
|
|
841
|
+
*
|
|
842
|
+
* @example
|
|
843
|
+
* ```ts
|
|
844
|
+
* const scopeTracker = new ScopeTracker()
|
|
845
|
+
* walk(code, {
|
|
846
|
+
* scopeTracker,
|
|
847
|
+
* enter(node) {
|
|
848
|
+
* // ...
|
|
849
|
+
* },
|
|
850
|
+
* })
|
|
851
|
+
* ```
|
|
852
|
+
*
|
|
853
|
+
* @see parseAndWalk
|
|
854
|
+
* @see walk
|
|
855
|
+
*/
|
|
856
|
+
var ScopeTracker = class {
|
|
857
|
+
scopeIndexStack = [];
|
|
858
|
+
/**
|
|
859
|
+
* The scope keys of the ancestors of the current scope, one entry per active scope.
|
|
860
|
+
* `pushScope` pushes the current `scopeIndexKey` before deriving the new one,
|
|
861
|
+
* and `popScope` restores it from here, so the stack always mirrors the path
|
|
862
|
+
* from the root scope down to the parent of the current scope.
|
|
863
|
+
*/
|
|
864
|
+
scopeKeyStack = [];
|
|
865
|
+
/**
|
|
866
|
+
* The nodes that created the currently active scopes, one entry per scope.
|
|
867
|
+
* A node that creates multiple scopes (e.g. `FunctionExpression`) appears once per scope.
|
|
868
|
+
* This lets `processNodeLeave` detect scope ends with a pointer comparison
|
|
869
|
+
* instead of checking the node type.
|
|
870
|
+
*/
|
|
871
|
+
scopeOwnerStack = [];
|
|
872
|
+
scopeIndexKey = "";
|
|
873
|
+
scopes = /* @__PURE__ */ new Map();
|
|
874
|
+
typeScopes = /* @__PURE__ */ new Map();
|
|
875
|
+
/**
|
|
876
|
+
* The implicit `arguments` keyed by the function that introduces them,
|
|
877
|
+
* so that repeated queries return the same instance.
|
|
878
|
+
*/
|
|
879
|
+
implicitArguments = /* @__PURE__ */ new WeakMap();
|
|
880
|
+
options;
|
|
881
|
+
isFrozen = false;
|
|
882
|
+
constructor(options = {}) {
|
|
883
|
+
this.options = options;
|
|
884
|
+
}
|
|
885
|
+
onWalkStart = (root) => {
|
|
886
|
+
if (this.scopeIndexStack.length === 0 && root.type !== "Program") this.scopeIndexStack.push(0);
|
|
887
|
+
};
|
|
888
|
+
pushScope(owner) {
|
|
889
|
+
const depthIndex = this.scopeIndexStack[this.scopeIndexStack.length - 1];
|
|
890
|
+
this.scopeKeyStack.push(this.scopeIndexKey);
|
|
891
|
+
this.scopeOwnerStack.push(owner);
|
|
892
|
+
this.scopeIndexStack.push(0);
|
|
893
|
+
if (depthIndex !== void 0) this.scopeIndexKey = this.scopeIndexKey ? `${this.scopeIndexKey}-${depthIndex}` : `${depthIndex}`;
|
|
894
|
+
}
|
|
895
|
+
popScope() {
|
|
896
|
+
this.scopeOwnerStack.pop();
|
|
897
|
+
this.scopeIndexStack.pop();
|
|
898
|
+
if (this.scopeIndexStack[this.scopeIndexStack.length - 1] !== void 0) this.scopeIndexStack[this.scopeIndexStack.length - 1]++;
|
|
899
|
+
if (!this.options.preserveExitedScopes) {
|
|
900
|
+
this.scopes.delete(this.scopeIndexKey);
|
|
901
|
+
this.typeScopes.delete(this.scopeIndexKey);
|
|
902
|
+
}
|
|
903
|
+
this.scopeIndexKey = this.scopeKeyStack.pop() ?? "";
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Get the key of the active scope at the given index of the scope stacks.
|
|
907
|
+
*/
|
|
908
|
+
getScopeKeyAt(index) {
|
|
909
|
+
return index === this.scopeKeyStack.length - 1 ? this.scopeIndexKey : this.scopeKeyStack[index + 1];
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Get the key of the closest function-like scope (function bodies, static blocks,
|
|
913
|
+
* module blocks and the root scope), which is where `var` declarations are hoisted to.
|
|
914
|
+
*/
|
|
915
|
+
getVarScopeKey() {
|
|
916
|
+
const owners = this.scopeOwnerStack;
|
|
917
|
+
for (let i = owners.length - 1; i >= 0; i--) switch (owners[i].type) {
|
|
918
|
+
case "FunctionDeclaration":
|
|
919
|
+
case "FunctionExpression":
|
|
920
|
+
case "ArrowFunctionExpression":
|
|
921
|
+
case "TSDeclareFunction":
|
|
922
|
+
case "Program":
|
|
923
|
+
case "StaticBlock":
|
|
924
|
+
case "TSModuleBlock": return this.getScopeKeyAt(i);
|
|
925
|
+
}
|
|
926
|
+
return "";
|
|
927
|
+
}
|
|
928
|
+
declareInNamespace(scopes, name, node) {
|
|
929
|
+
let scope = scopes.get(node.scope);
|
|
930
|
+
if (!scope) {
|
|
931
|
+
scope = /* @__PURE__ */ new Map();
|
|
932
|
+
scopes.set(node.scope, scope);
|
|
933
|
+
}
|
|
934
|
+
scope.set(name, node);
|
|
935
|
+
}
|
|
936
|
+
declareIdentifier(name, data, namespaces = { value: true }) {
|
|
937
|
+
if (this.isFrozen) return;
|
|
938
|
+
if (namespaces.value) this.declareInNamespace(this.scopes, name, data);
|
|
939
|
+
if (namespaces.type) this.declareInNamespace(this.typeScopes, name, data);
|
|
940
|
+
}
|
|
941
|
+
declareFunctionParameter(param, fn) {
|
|
942
|
+
if (this.isFrozen) return;
|
|
943
|
+
const identifiers = getPatternIdentifiers(param);
|
|
944
|
+
for (const identifier of identifiers) this.declareIdentifier(identifier.name, new ScopeTrackerFunctionParam(identifier, this.scopeIndexKey, fn));
|
|
945
|
+
}
|
|
946
|
+
declarePattern(pattern, parent) {
|
|
947
|
+
if (this.isFrozen) return;
|
|
948
|
+
const scopeKey = parent.type === "VariableDeclaration" && parent.kind === "var" ? this.getVarScopeKey() : this.scopeIndexKey;
|
|
949
|
+
const identifiers = getPatternIdentifiers(pattern);
|
|
950
|
+
for (const identifier of identifiers) this.declareIdentifier(identifier.name, parent.type === "VariableDeclaration" ? new ScopeTrackerVariable(identifier, scopeKey, parent) : parent.type === "CatchClause" ? new ScopeTrackerCatchParam(identifier, scopeKey, parent) : new ScopeTrackerFunctionParam(identifier, scopeKey, parent));
|
|
951
|
+
}
|
|
952
|
+
processNodeEnter = (node) => {
|
|
953
|
+
if (!SCOPE_ENTER_TYPES.has(node.type)) return;
|
|
954
|
+
switch (node.type) {
|
|
955
|
+
case "Program":
|
|
956
|
+
case "BlockStatement":
|
|
957
|
+
case "StaticBlock":
|
|
958
|
+
case "SwitchStatement":
|
|
959
|
+
case "TSModuleBlock":
|
|
960
|
+
case "TSMethodSignature":
|
|
961
|
+
case "TSCallSignatureDeclaration":
|
|
962
|
+
case "TSConstructSignatureDeclaration":
|
|
963
|
+
case "TSFunctionType":
|
|
964
|
+
case "TSConstructorType":
|
|
965
|
+
case "TSConditionalType":
|
|
966
|
+
this.pushScope(node);
|
|
967
|
+
break;
|
|
968
|
+
case "FunctionDeclaration":
|
|
969
|
+
if (node.id?.name) this.declareIdentifier(node.id.name, new ScopeTrackerFunction(node, this.scopeIndexKey));
|
|
970
|
+
this.pushScope(node);
|
|
971
|
+
for (const param of node.params) this.declareFunctionParameter(param, node);
|
|
972
|
+
break;
|
|
973
|
+
case "FunctionExpression":
|
|
974
|
+
this.pushScope(node);
|
|
975
|
+
if (node.id?.name) this.declareIdentifier(node.id.name, new ScopeTrackerFunction(node, this.scopeIndexKey));
|
|
976
|
+
this.pushScope(node);
|
|
977
|
+
for (const param of node.params) this.declareFunctionParameter(param, node);
|
|
978
|
+
break;
|
|
979
|
+
case "ArrowFunctionExpression":
|
|
980
|
+
this.pushScope(node);
|
|
981
|
+
for (const param of node.params) this.declareFunctionParameter(param, node);
|
|
982
|
+
break;
|
|
983
|
+
case "VariableDeclaration":
|
|
984
|
+
for (const decl of node.declarations) this.declarePattern(decl.id, node);
|
|
985
|
+
break;
|
|
986
|
+
case "ClassDeclaration":
|
|
987
|
+
if (node.id?.name) this.declareIdentifier(node.id.name, new ScopeTrackerIdentifier(node.id, this.scopeIndexKey), {
|
|
988
|
+
value: true,
|
|
989
|
+
type: true
|
|
990
|
+
});
|
|
991
|
+
if (node.typeParameters) this.pushScope(node);
|
|
992
|
+
break;
|
|
993
|
+
case "ClassExpression":
|
|
994
|
+
this.pushScope(node);
|
|
995
|
+
if (node.id?.name) this.declareIdentifier(node.id.name, new ScopeTrackerIdentifier(node.id, this.scopeIndexKey), {
|
|
996
|
+
value: true,
|
|
997
|
+
type: true
|
|
54
998
|
});
|
|
55
|
-
|
|
999
|
+
break;
|
|
1000
|
+
case "ImportDeclaration":
|
|
1001
|
+
for (const specifier of node.specifiers) {
|
|
1002
|
+
const isTypeOnly = node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type";
|
|
1003
|
+
this.declareIdentifier(specifier.local.name, new ScopeTrackerImport(specifier, this.scopeIndexKey, node), {
|
|
1004
|
+
value: !isTypeOnly,
|
|
1005
|
+
type: true
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
break;
|
|
1009
|
+
case "TSEnumDeclaration":
|
|
1010
|
+
case "TSModuleDeclaration":
|
|
1011
|
+
case "TSImportEqualsDeclaration":
|
|
1012
|
+
if (node.type === "TSModuleDeclaration" && node.kind === "global") break;
|
|
1013
|
+
if (node.id?.type === "Identifier" && node.id.name) this.declareIdentifier(node.id.name, new ScopeTrackerIdentifier(node.id, this.scopeIndexKey), {
|
|
1014
|
+
value: true,
|
|
1015
|
+
type: true
|
|
1016
|
+
});
|
|
1017
|
+
break;
|
|
1018
|
+
case "TSDeclareFunction":
|
|
1019
|
+
if (node.id?.name) this.declareIdentifier(node.id.name, new ScopeTrackerIdentifier(node.id, this.scopeIndexKey));
|
|
1020
|
+
this.pushScope(node);
|
|
1021
|
+
break;
|
|
1022
|
+
case "TSInterfaceDeclaration":
|
|
1023
|
+
case "TSTypeAliasDeclaration":
|
|
1024
|
+
if (node.id?.name) this.declareIdentifier(node.id.name, new ScopeTrackerIdentifier(node.id, this.scopeIndexKey), { type: true });
|
|
1025
|
+
this.pushScope(node);
|
|
1026
|
+
break;
|
|
1027
|
+
case "TSTypeParameter":
|
|
1028
|
+
if (node.name?.name) this.declareIdentifier(node.name.name, new ScopeTrackerIdentifier(node.name, this.scopeIndexKey), { type: true });
|
|
1029
|
+
break;
|
|
1030
|
+
case "TSMappedType":
|
|
1031
|
+
this.pushScope(node);
|
|
1032
|
+
this.declareIdentifier(node.key.name, new ScopeTrackerIdentifier(node.key, this.scopeIndexKey), { type: true });
|
|
1033
|
+
break;
|
|
1034
|
+
case "TSEnumBody":
|
|
1035
|
+
this.pushScope(node);
|
|
1036
|
+
for (const member of node.members) if (member.id.type === "Identifier") this.declareIdentifier(member.id.name, new ScopeTrackerIdentifier(member.id, this.scopeIndexKey));
|
|
1037
|
+
break;
|
|
1038
|
+
case "CatchClause":
|
|
1039
|
+
this.pushScope(node);
|
|
1040
|
+
if (node.param) this.declarePattern(node.param, node);
|
|
1041
|
+
break;
|
|
1042
|
+
case "ForStatement":
|
|
1043
|
+
case "ForOfStatement":
|
|
1044
|
+
case "ForInStatement":
|
|
1045
|
+
this.pushScope(node);
|
|
1046
|
+
if (node.type === "ForStatement" && node.init?.type === "VariableDeclaration") for (const decl of node.init.declarations) this.declarePattern(decl.id, node.init);
|
|
1047
|
+
else if ((node.type === "ForOfStatement" || node.type === "ForInStatement") && node.left.type === "VariableDeclaration") for (const decl of node.left.declarations) this.declarePattern(decl.id, node.left);
|
|
1048
|
+
}
|
|
1049
|
+
};
|
|
1050
|
+
processNodeLeave = (node) => {
|
|
1051
|
+
const owners = this.scopeOwnerStack;
|
|
1052
|
+
while (owners.length > 0 && owners[owners.length - 1] === node) this.popScope();
|
|
1053
|
+
};
|
|
1054
|
+
getDeclarationIn(scopes, name) {
|
|
1055
|
+
let key = this.scopeIndexKey;
|
|
1056
|
+
while (true) {
|
|
1057
|
+
const node = scopes.get(key)?.get(name);
|
|
1058
|
+
if (node) return node;
|
|
1059
|
+
if (!key) return null;
|
|
1060
|
+
const separatorIndex = key.lastIndexOf("-");
|
|
1061
|
+
key = separatorIndex === -1 ? "" : key.slice(0, separatorIndex);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Check if an identifier is declared in the current scope or any parent scope.
|
|
1066
|
+
* @param name the identifier name to check
|
|
1067
|
+
* @param options which namespace to check — the value namespace (default), the type namespace, or both
|
|
1068
|
+
*/
|
|
1069
|
+
isDeclared(name, options) {
|
|
1070
|
+
return this.getDeclaration(name, options) !== null;
|
|
1071
|
+
}
|
|
1072
|
+
/**
|
|
1073
|
+
* Get the declaration node for a given identifier name.
|
|
1074
|
+
* @param name the identifier name to look up
|
|
1075
|
+
* @param options which namespace to check — the value namespace (default), the type namespace, or both
|
|
1076
|
+
*/
|
|
1077
|
+
getDeclaration(name, options) {
|
|
1078
|
+
const mode = options?.mode ?? "value";
|
|
1079
|
+
const declaration = (mode !== "type" ? this.getDeclarationIn(this.scopes, name) : null) ?? (mode !== "value" ? this.getDeclarationIn(this.typeScopes, name) : null);
|
|
1080
|
+
if (name === "arguments" && mode !== "type") {
|
|
1081
|
+
const owners = this.scopeOwnerStack;
|
|
1082
|
+
for (let i = owners.length - 1; i >= 0; i--) {
|
|
1083
|
+
const owner = owners[i];
|
|
1084
|
+
if (owner.type === "FunctionDeclaration" || owner.type === "FunctionExpression") {
|
|
1085
|
+
const fnScope = this.getScopeKeyAt(i);
|
|
1086
|
+
if (!declaration || isChildScope(fnScope, declaration.scope)) {
|
|
1087
|
+
let implicit = this.implicitArguments.get(owner);
|
|
1088
|
+
if (!implicit) {
|
|
1089
|
+
implicit = new ScopeTrackerFunctionArguments(owner, fnScope);
|
|
1090
|
+
this.implicitArguments.set(owner, implicit);
|
|
1091
|
+
}
|
|
1092
|
+
return implicit;
|
|
1093
|
+
}
|
|
1094
|
+
break;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
return declaration;
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Get the current scope key.
|
|
1102
|
+
*/
|
|
1103
|
+
getCurrentScope() {
|
|
1104
|
+
return this.scopeIndexKey;
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Check if the current scope is a child of a specific scope.
|
|
1108
|
+
* @example
|
|
1109
|
+
* ```ts
|
|
1110
|
+
* // current scope is 0-1
|
|
1111
|
+
* isCurrentScopeUnder('0') // true
|
|
1112
|
+
* isCurrentScopeUnder('0-1') // false
|
|
1113
|
+
* ```
|
|
1114
|
+
*
|
|
1115
|
+
* @param scope the parent scope key to check against
|
|
1116
|
+
* @returns `true` if the current scope is a child of the specified scope, `false` otherwise (also when they are the same)
|
|
1117
|
+
*/
|
|
1118
|
+
isCurrentScopeUnder(scope) {
|
|
1119
|
+
return isChildScope(this.scopeIndexKey, scope);
|
|
1120
|
+
}
|
|
1121
|
+
/**
|
|
1122
|
+
* Freezes the ScopeTracker, preventing further modifications to its state.
|
|
1123
|
+
* It also resets the scope index stack to its initial state so that the tracker can be reused.
|
|
1124
|
+
*
|
|
1125
|
+
* This is useful for second passes through the AST.
|
|
1126
|
+
*/
|
|
1127
|
+
freeze() {
|
|
1128
|
+
this.isFrozen = true;
|
|
1129
|
+
this.scopeIndexStack = [];
|
|
1130
|
+
this.scopeKeyStack = [];
|
|
1131
|
+
this.scopeOwnerStack = [];
|
|
1132
|
+
this.scopeIndexKey = "";
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
function getPatternIdentifiers(pattern) {
|
|
1136
|
+
const identifiers = [];
|
|
1137
|
+
function collectIdentifiers(pattern) {
|
|
1138
|
+
switch (pattern.type) {
|
|
1139
|
+
case "Identifier":
|
|
1140
|
+
identifiers.push(pattern);
|
|
1141
|
+
break;
|
|
1142
|
+
case "AssignmentPattern":
|
|
1143
|
+
collectIdentifiers(pattern.left);
|
|
1144
|
+
break;
|
|
1145
|
+
case "RestElement":
|
|
1146
|
+
collectIdentifiers(pattern.argument);
|
|
1147
|
+
break;
|
|
1148
|
+
case "TSParameterProperty":
|
|
1149
|
+
collectIdentifiers(pattern.parameter);
|
|
1150
|
+
break;
|
|
1151
|
+
case "ArrayPattern":
|
|
1152
|
+
for (const element of pattern.elements) if (element) collectIdentifiers(element.type === "RestElement" ? element.argument : element);
|
|
1153
|
+
break;
|
|
1154
|
+
case "ObjectPattern": for (const property of pattern.properties) collectIdentifiers(property.type === "RestElement" ? property.argument : property.value);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
collectIdentifiers(pattern);
|
|
1158
|
+
return identifiers;
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* An allocation-free alternative to `getPatternIdentifiers(pattern).includes(node)`
|
|
1162
|
+
*/
|
|
1163
|
+
function isIdentifierInPattern(pattern, node) {
|
|
1164
|
+
switch (pattern.type) {
|
|
1165
|
+
case "Identifier": return pattern === node;
|
|
1166
|
+
case "AssignmentPattern": return isIdentifierInPattern(pattern.left, node);
|
|
1167
|
+
case "RestElement": return isIdentifierInPattern(pattern.argument, node);
|
|
1168
|
+
case "TSParameterProperty": return isIdentifierInPattern(pattern.parameter, node);
|
|
1169
|
+
case "ArrayPattern":
|
|
1170
|
+
for (const element of pattern.elements) if (element && isIdentifierInPattern(element.type === "RestElement" ? element.argument : element, node)) return true;
|
|
1171
|
+
return false;
|
|
1172
|
+
case "ObjectPattern":
|
|
1173
|
+
for (const property of pattern.properties) if (isIdentifierInPattern(property.type === "RestElement" ? property.argument : property.value, node)) return true;
|
|
1174
|
+
return false;
|
|
1175
|
+
}
|
|
1176
|
+
return false;
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Check if an identifier is in a binding position, where it declares a new variable.
|
|
1180
|
+
*
|
|
1181
|
+
* Note that identifiers nested in destructuring patterns (`const { a, b = c } = obj`)
|
|
1182
|
+
* cannot be resolved from the direct parent alone; this function returns `false` for them
|
|
1183
|
+
* and {@link isReferenceIdentifier} reports them as references.
|
|
1184
|
+
* Pair these functions with a {@link ScopeTracker} to resolve such identifiers correctly.
|
|
1185
|
+
*/
|
|
1186
|
+
function isOnlyBindingIdentifier(node, parent) {
|
|
1187
|
+
if (!parent || node.type !== "Identifier") return false;
|
|
1188
|
+
switch (parent.type) {
|
|
1189
|
+
case "FunctionDeclaration":
|
|
1190
|
+
case "FunctionExpression":
|
|
1191
|
+
case "ArrowFunctionExpression":
|
|
1192
|
+
case "TSDeclareFunction":
|
|
1193
|
+
case "TSEmptyBodyFunctionExpression":
|
|
1194
|
+
if (parent.type !== "ArrowFunctionExpression" && parent.id === node) return true;
|
|
1195
|
+
for (const param of parent.params) if (isIdentifierInPattern(param, node)) return true;
|
|
1196
|
+
return false;
|
|
1197
|
+
case "ClassDeclaration":
|
|
1198
|
+
case "ClassExpression": return parent.id === node;
|
|
1199
|
+
case "VariableDeclarator": return isIdentifierInPattern(parent.id, node);
|
|
1200
|
+
case "CatchClause":
|
|
1201
|
+
if (!parent.param) return false;
|
|
1202
|
+
return isIdentifierInPattern(parent.param, node);
|
|
1203
|
+
case "ImportSpecifier": return parent.local === node;
|
|
1204
|
+
case "ImportDefaultSpecifier":
|
|
1205
|
+
case "ImportNamespaceSpecifier": return true;
|
|
1206
|
+
case "TSEnumDeclaration":
|
|
1207
|
+
case "TSModuleDeclaration": return parent.id === node;
|
|
1208
|
+
case "TSImportEqualsDeclaration": return parent.id === node;
|
|
1209
|
+
case "TSParameterProperty": return isIdentifierInPattern(parent.parameter, node);
|
|
1210
|
+
}
|
|
1211
|
+
return false;
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* Check if an identifier is a reference.
|
|
1215
|
+
*
|
|
1216
|
+
* Note that this function returns `true` for the local name of a plain export
|
|
1217
|
+
* (`export { foo }`), where it is a genuine reference to a local variable,
|
|
1218
|
+
* but also for the local name of a re-export (`export { foo } from '...'`),
|
|
1219
|
+
* where it refers to the other module's exports instead.
|
|
1220
|
+
*
|
|
1221
|
+
* The two are indistinguishable from the specifier alone, as the `source` lives
|
|
1222
|
+
* on the parent `ExportNamedDeclaration`.
|
|
1223
|
+
* Skip re-export declarations during the walk to avoid the false positives.
|
|
1224
|
+
*
|
|
1225
|
+
* Identifiers nested in destructuring patterns (`const { a, b = c } = obj`) are also
|
|
1226
|
+
* indistinguishable from references based on the direct parent alone and are reported
|
|
1227
|
+
* as references. Pair this function with a {@link ScopeTracker} to resolve them correctly.
|
|
1228
|
+
*/
|
|
1229
|
+
function isReferenceIdentifier(node, parent, options) {
|
|
1230
|
+
if (!parent) return false;
|
|
1231
|
+
const mode = options?.mode ?? "value";
|
|
1232
|
+
if (node.type === "JSXIdentifier") {
|
|
1233
|
+
if (mode === "type") return false;
|
|
1234
|
+
switch (parent.type) {
|
|
1235
|
+
case "JSXOpeningElement":
|
|
1236
|
+
case "JSXClosingElement": return parent.name === node && !/^[a-z]/.test(node.name);
|
|
1237
|
+
case "JSXMemberExpression": return parent.object === node;
|
|
1238
|
+
case "JSXAttribute":
|
|
1239
|
+
case "JSXNamespacedName": return false;
|
|
56
1240
|
}
|
|
1241
|
+
return false;
|
|
1242
|
+
}
|
|
1243
|
+
if (node.type !== "Identifier" || isOnlyBindingIdentifier(node, parent)) return false;
|
|
1244
|
+
switch (parent.type) {
|
|
1245
|
+
case "MemberExpression": return mode !== "type" && (parent.object === node || parent.computed);
|
|
1246
|
+
case "Property": return mode !== "type" && (parent.value === node || parent.computed);
|
|
1247
|
+
case "MethodDefinition":
|
|
1248
|
+
case "PropertyDefinition":
|
|
1249
|
+
case "AccessorProperty":
|
|
1250
|
+
case "TSAbstractMethodDefinition":
|
|
1251
|
+
case "TSAbstractPropertyDefinition":
|
|
1252
|
+
case "TSAbstractAccessorProperty": return mode !== "type" && (parent.value === node || parent.computed);
|
|
1253
|
+
case "ExportSpecifier": return mode !== "type" && parent.local === node;
|
|
1254
|
+
case "ExportAllDeclaration": return false;
|
|
1255
|
+
case "ImportSpecifier": return false;
|
|
1256
|
+
case "LabeledStatement":
|
|
1257
|
+
case "BreakStatement":
|
|
1258
|
+
case "ContinueStatement": return false;
|
|
1259
|
+
case "MetaProperty": return false;
|
|
1260
|
+
case "ImportAttribute": return false;
|
|
1261
|
+
case "TSEnumMember": return mode !== "type" && parent.id !== node;
|
|
1262
|
+
case "TSMappedType": return false;
|
|
1263
|
+
case "TSTypeReference": return mode !== "value";
|
|
1264
|
+
case "TSQualifiedName": return mode !== "value" && parent.left === node;
|
|
1265
|
+
case "TSClassImplements":
|
|
1266
|
+
case "TSInterfaceHeritage": return mode !== "value" && parent.expression === node;
|
|
1267
|
+
case "TSTypeParameter":
|
|
1268
|
+
case "TSInterfaceDeclaration":
|
|
1269
|
+
case "TSTypeAliasDeclaration":
|
|
1270
|
+
case "TSPropertySignature":
|
|
1271
|
+
case "TSMethodSignature":
|
|
1272
|
+
case "TSIndexSignature": return false;
|
|
1273
|
+
case "TSFunctionType":
|
|
1274
|
+
case "TSConstructorType":
|
|
1275
|
+
case "TSCallSignatureDeclaration":
|
|
1276
|
+
case "TSConstructSignatureDeclaration": return false;
|
|
57
1277
|
}
|
|
58
|
-
return
|
|
1278
|
+
return mode !== "type";
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* A function to check whether scope A is a child of scope B.
|
|
1282
|
+
* @example
|
|
1283
|
+
* ```ts
|
|
1284
|
+
* isChildScope('0-1-2', '0-1') // true
|
|
1285
|
+
* isChildScope('0-1', '0-1') // false
|
|
1286
|
+
* ```
|
|
1287
|
+
*
|
|
1288
|
+
* @param a the child scope
|
|
1289
|
+
* @param b the parent scope
|
|
1290
|
+
* @returns true if scope A is a child of scope B, false otherwise (also when they are the same)
|
|
1291
|
+
*/
|
|
1292
|
+
function isChildScope(a, b) {
|
|
1293
|
+
return a.length > b.length && a.startsWith(b) && (b === "" || a[b.length] === "-");
|
|
59
1294
|
}
|
|
1295
|
+
var BaseNode = class {
|
|
1296
|
+
scope;
|
|
1297
|
+
node;
|
|
1298
|
+
constructor(node, scope) {
|
|
1299
|
+
this.node = node;
|
|
1300
|
+
this.scope = scope;
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* Check if the node is defined under a specific scope.
|
|
1304
|
+
* @param scope
|
|
1305
|
+
*/
|
|
1306
|
+
isUnderScope(scope) {
|
|
1307
|
+
return isChildScope(this.scope, scope);
|
|
1308
|
+
}
|
|
1309
|
+
};
|
|
1310
|
+
var ScopeTrackerIdentifier = class extends BaseNode {
|
|
1311
|
+
type = "Identifier";
|
|
1312
|
+
get start() {
|
|
1313
|
+
return this.node.start;
|
|
1314
|
+
}
|
|
1315
|
+
get end() {
|
|
1316
|
+
return this.node.end;
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
var ScopeTrackerFunctionParam = class extends BaseNode {
|
|
1320
|
+
type = "FunctionParam";
|
|
1321
|
+
fnNode;
|
|
1322
|
+
constructor(node, scope, fnNode) {
|
|
1323
|
+
super(node, scope);
|
|
1324
|
+
this.fnNode = fnNode;
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* @deprecated The representation of this position may change in the future. Use `.fnNode.start` instead for now.
|
|
1328
|
+
*/
|
|
1329
|
+
get start() {
|
|
1330
|
+
return this.fnNode.start;
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* @deprecated The representation of this position may change in the future. Use `.fnNode.end` instead for now.
|
|
1334
|
+
*/
|
|
1335
|
+
get end() {
|
|
1336
|
+
return this.fnNode.end;
|
|
1337
|
+
}
|
|
1338
|
+
};
|
|
1339
|
+
var ScopeTrackerFunction = class extends BaseNode {
|
|
1340
|
+
type = "Function";
|
|
1341
|
+
get start() {
|
|
1342
|
+
return this.node.start;
|
|
1343
|
+
}
|
|
1344
|
+
get end() {
|
|
1345
|
+
return this.node.end;
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
var ScopeTrackerFunctionArguments = class extends BaseNode {
|
|
1349
|
+
type = "FunctionArguments";
|
|
1350
|
+
get start() {
|
|
1351
|
+
return this.node.start;
|
|
1352
|
+
}
|
|
1353
|
+
get end() {
|
|
1354
|
+
return this.node.end;
|
|
1355
|
+
}
|
|
1356
|
+
};
|
|
1357
|
+
var ScopeTrackerVariable = class extends BaseNode {
|
|
1358
|
+
type = "Variable";
|
|
1359
|
+
variableNode;
|
|
1360
|
+
constructor(node, scope, variableNode) {
|
|
1361
|
+
super(node, scope);
|
|
1362
|
+
this.variableNode = variableNode;
|
|
1363
|
+
}
|
|
1364
|
+
get start() {
|
|
1365
|
+
return this.variableNode.start;
|
|
1366
|
+
}
|
|
1367
|
+
get end() {
|
|
1368
|
+
return this.variableNode.end;
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
var ScopeTrackerImport = class extends BaseNode {
|
|
1372
|
+
type = "Import";
|
|
1373
|
+
importNode;
|
|
1374
|
+
constructor(node, scope, importNode) {
|
|
1375
|
+
super(node, scope);
|
|
1376
|
+
this.importNode = importNode;
|
|
1377
|
+
}
|
|
1378
|
+
get start() {
|
|
1379
|
+
return this.importNode.start;
|
|
1380
|
+
}
|
|
1381
|
+
get end() {
|
|
1382
|
+
return this.importNode.end;
|
|
1383
|
+
}
|
|
1384
|
+
};
|
|
1385
|
+
var ScopeTrackerCatchParam = class extends BaseNode {
|
|
1386
|
+
type = "CatchParam";
|
|
1387
|
+
catchNode;
|
|
1388
|
+
constructor(node, scope, catchNode) {
|
|
1389
|
+
super(node, scope);
|
|
1390
|
+
this.catchNode = catchNode;
|
|
1391
|
+
}
|
|
1392
|
+
get start() {
|
|
1393
|
+
return this.catchNode.start;
|
|
1394
|
+
}
|
|
1395
|
+
get end() {
|
|
1396
|
+
return this.catchNode.end;
|
|
1397
|
+
}
|
|
1398
|
+
};
|
|
60
1399
|
//#endregion
|
|
61
|
-
//#region src/
|
|
1400
|
+
//#region src/usage.ts
|
|
1401
|
+
const SOURCE_GLOBS = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
|
|
1402
|
+
const IGNORED_DIRS = [
|
|
1403
|
+
"dist",
|
|
1404
|
+
"build",
|
|
1405
|
+
"out",
|
|
1406
|
+
"coverage",
|
|
1407
|
+
"storybook-static"
|
|
1408
|
+
];
|
|
1409
|
+
/** Expression wrappers that do not change what is referenced. */
|
|
1410
|
+
const TS_WRAPPERS = /* @__PURE__ */ new Set([
|
|
1411
|
+
"ParenthesizedExpression",
|
|
1412
|
+
"TSAsExpression",
|
|
1413
|
+
"TSNonNullExpression",
|
|
1414
|
+
"TSSatisfiesExpression",
|
|
1415
|
+
"TSTypeAssertion",
|
|
1416
|
+
"TSInstantiationExpression"
|
|
1417
|
+
]);
|
|
1418
|
+
/**
|
|
1419
|
+
* Find CSS Modules classes and modules that no source file uses.
|
|
1420
|
+
*
|
|
1421
|
+
* Usage is aggregated per CSS file across the whole project and reported at
|
|
1422
|
+
* the CSS side; places where usage cannot be determined statically (dynamic
|
|
1423
|
+
* access, the module object escaping as a value) are reported at the source
|
|
1424
|
+
* side instead of guessing. The modules must be loaded from their real paths,
|
|
1425
|
+
* which is how resolved imports come back.
|
|
1426
|
+
*/
|
|
1427
|
+
async function analyzeUsage(modules, config) {
|
|
1428
|
+
const root = fs.realpathSync(config.root);
|
|
1429
|
+
const byPath = new Map(modules.map((analysis) => [analysis.file, analysis]));
|
|
1430
|
+
const usage = new Map(modules.map((analysis) => [analysis.file, {
|
|
1431
|
+
used: /* @__PURE__ */ new Set(),
|
|
1432
|
+
patterns: [],
|
|
1433
|
+
opaque: [],
|
|
1434
|
+
importers: /* @__PURE__ */ new Set()
|
|
1435
|
+
}]));
|
|
1436
|
+
const resolvers = new Resolvers(root);
|
|
1437
|
+
const files = (await findSources(config, root)).map((file) => {
|
|
1438
|
+
const source = fs.readFileSync(file, "utf-8");
|
|
1439
|
+
return {
|
|
1440
|
+
file,
|
|
1441
|
+
source,
|
|
1442
|
+
result: parseSync(file, source, {
|
|
1443
|
+
sourceType: "module",
|
|
1444
|
+
lang: langOf(file),
|
|
1445
|
+
preserveParens: false
|
|
1446
|
+
})
|
|
1447
|
+
};
|
|
1448
|
+
});
|
|
1449
|
+
const rel = (file) => relative(process.cwd(), file);
|
|
1450
|
+
const markOpaque = (css, opaque) => {
|
|
1451
|
+
const target = usage.get(css);
|
|
1452
|
+
if (!target.opaque.some((o) => o.file === opaque.file && o.offset === opaque.offset)) target.opaque.push(opaque);
|
|
1453
|
+
};
|
|
1454
|
+
const reexports = /* @__PURE__ */ new Map();
|
|
1455
|
+
for (const { file, result } of files) for (const staticExport of result.module.staticExports) for (const entry of staticExport.entries) {
|
|
1456
|
+
if (!entry.moduleRequest || entry.isType) continue;
|
|
1457
|
+
const css = resolvers.resolve(file, entry.moduleRequest.value);
|
|
1458
|
+
if (!css || !byPath.has(css)) continue;
|
|
1459
|
+
usage.get(css).importers.add(file);
|
|
1460
|
+
if (entry.importName.kind === "Name" && entry.importName.name === "default") {
|
|
1461
|
+
if (!reexports.has(file)) reexports.set(file, /* @__PURE__ */ new Map());
|
|
1462
|
+
reexports.get(file).set(entry.exportName.name ?? "default", css);
|
|
1463
|
+
} else if (entry.importName.kind === "Name" && entry.importName.name) usage.get(css).used.add(entry.importName.name);
|
|
1464
|
+
else markOpaque(css, {
|
|
1465
|
+
file,
|
|
1466
|
+
offset: entry.start,
|
|
1467
|
+
message: `the module is re-exported wholesale here, so usage of ${rel(css)} cannot be determined`
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
for (const { file, result } of files) for (const staticExport of result.module.staticExports) for (const entry of staticExport.entries) {
|
|
1471
|
+
if (!entry.moduleRequest || entry.isType) continue;
|
|
1472
|
+
const resolved = resolvers.resolve(file, entry.moduleRequest.value);
|
|
1473
|
+
const exported = resolved ? reexports.get(resolved) : void 0;
|
|
1474
|
+
if (!exported) continue;
|
|
1475
|
+
const affected = entry.importName.kind === "Name" ? [exported.get(entry.importName.name ?? "")].filter((css) => css !== void 0) : [...exported.values()];
|
|
1476
|
+
for (const css of affected) markOpaque(css, {
|
|
1477
|
+
file,
|
|
1478
|
+
offset: entry.start,
|
|
1479
|
+
message: `the module is re-exported here through another module, so usage of ${rel(css)} cannot be determined`
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
for (const { file, source, result } of files) {
|
|
1483
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
1484
|
+
const imported = /* @__PURE__ */ new Set();
|
|
1485
|
+
for (const staticImport of result.module.staticImports) {
|
|
1486
|
+
if (staticImport.entries.filter((entry) => !entry.isType).length === 0 && staticImport.entries.length > 0) continue;
|
|
1487
|
+
const resolved = resolvers.resolve(file, staticImport.moduleRequest.value);
|
|
1488
|
+
if (!resolved) continue;
|
|
1489
|
+
if (byPath.has(resolved)) {
|
|
1490
|
+
usage.get(resolved).importers.add(file);
|
|
1491
|
+
imported.add(resolved);
|
|
1492
|
+
for (const entry of staticImport.entries) {
|
|
1493
|
+
if (entry.isType) continue;
|
|
1494
|
+
if (entry.importName.kind === "Name" && entry.importName.name !== "default") usage.get(resolved).used.add(entry.importName.name ?? "");
|
|
1495
|
+
else bindings.set(entry.localName.value, {
|
|
1496
|
+
css: resolved,
|
|
1497
|
+
namespace: entry.importName.kind === "NamespaceObject"
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
continue;
|
|
1501
|
+
}
|
|
1502
|
+
const exported = reexports.get(resolved);
|
|
1503
|
+
if (!exported) continue;
|
|
1504
|
+
for (const entry of staticImport.entries) {
|
|
1505
|
+
if (entry.isType) continue;
|
|
1506
|
+
if (entry.importName.kind === "NamespaceObject") {
|
|
1507
|
+
for (const css of exported.values()) {
|
|
1508
|
+
usage.get(css).importers.add(file);
|
|
1509
|
+
markOpaque(css, {
|
|
1510
|
+
file,
|
|
1511
|
+
offset: staticImport.start,
|
|
1512
|
+
message: `the module is reached here through a namespace import, so usage of ${rel(css)} cannot be determined`
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
continue;
|
|
1516
|
+
}
|
|
1517
|
+
const name = entry.importName.kind === "Default" ? "default" : entry.importName.name;
|
|
1518
|
+
const css = name === null ? void 0 : exported.get(name);
|
|
1519
|
+
if (!css) continue;
|
|
1520
|
+
usage.get(css).importers.add(file);
|
|
1521
|
+
imported.add(css);
|
|
1522
|
+
bindings.set(entry.localName.value, {
|
|
1523
|
+
css,
|
|
1524
|
+
namespace: false
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
for (const dynamicImport of result.module.dynamicImports) {
|
|
1529
|
+
const specifier = source.slice(dynamicImport.moduleRequest.start, dynamicImport.moduleRequest.end).replace(/^(["'`])(.*)\1$/s, "$2");
|
|
1530
|
+
const css = resolvers.resolve(file, specifier);
|
|
1531
|
+
if (!css || !byPath.has(css)) continue;
|
|
1532
|
+
usage.get(css).importers.add(file);
|
|
1533
|
+
markOpaque(css, {
|
|
1534
|
+
file,
|
|
1535
|
+
offset: dynamicImport.start,
|
|
1536
|
+
message: `the module is imported dynamically here, so usage of ${rel(css)} cannot be determined`
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
if (result.errors.length > 0) {
|
|
1540
|
+
for (const css of imported) markOpaque(css, {
|
|
1541
|
+
file,
|
|
1542
|
+
offset: 0,
|
|
1543
|
+
message: `${rel(file)} could not be parsed, so usage of ${rel(css)} cannot be determined`
|
|
1544
|
+
});
|
|
1545
|
+
continue;
|
|
1546
|
+
}
|
|
1547
|
+
if (bindings.size > 0) collectReferences(file, result, bindings, usage, markOpaque, rel);
|
|
1548
|
+
}
|
|
1549
|
+
linkCssReferences(modules, byPath, usage, resolvers);
|
|
1550
|
+
const found = [];
|
|
1551
|
+
const sourcesByPath = new Map(files.map((entry) => [entry.file, entry.source]));
|
|
1552
|
+
for (const analysis of modules) {
|
|
1553
|
+
const moduleUsage = usage.get(analysis.file);
|
|
1554
|
+
if (moduleUsage.importers.size === 0) {
|
|
1555
|
+
found.push({
|
|
1556
|
+
module: analysis.file,
|
|
1557
|
+
node: null,
|
|
1558
|
+
diagnostic: {
|
|
1559
|
+
file: analysis.file,
|
|
1560
|
+
line: 1,
|
|
1561
|
+
column: 1,
|
|
1562
|
+
rule: "usage/unused-module",
|
|
1563
|
+
message: `${rel(analysis.file)} is never imported`
|
|
1564
|
+
}
|
|
1565
|
+
});
|
|
1566
|
+
continue;
|
|
1567
|
+
}
|
|
1568
|
+
if (moduleUsage.opaque.length > 0) {
|
|
1569
|
+
for (const opaque of moduleUsage.opaque) {
|
|
1570
|
+
const position = positionAt(sourcesByPath.get(opaque.file) ?? "", opaque.offset);
|
|
1571
|
+
found.push({
|
|
1572
|
+
module: analysis.file,
|
|
1573
|
+
node: null,
|
|
1574
|
+
diagnostic: {
|
|
1575
|
+
file: opaque.file,
|
|
1576
|
+
...position,
|
|
1577
|
+
rule: "usage/unanalyzable",
|
|
1578
|
+
message: opaque.message
|
|
1579
|
+
}
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
continue;
|
|
1583
|
+
}
|
|
1584
|
+
const firstOccurrences = /* @__PURE__ */ new Map();
|
|
1585
|
+
for (const occurrence of analysis.classes) if (!firstOccurrences.has(occurrence.name)) firstOccurrences.set(occurrence.name, occurrence);
|
|
1586
|
+
for (const [name, first] of firstOccurrences) {
|
|
1587
|
+
if (isUsed(moduleUsage, name)) continue;
|
|
1588
|
+
found.push({
|
|
1589
|
+
module: analysis.file,
|
|
1590
|
+
node: first.node,
|
|
1591
|
+
diagnostic: {
|
|
1592
|
+
file: analysis.file,
|
|
1593
|
+
line: first.range.start.line,
|
|
1594
|
+
column: first.range.start.column,
|
|
1595
|
+
endLine: first.range.end.line,
|
|
1596
|
+
endColumn: first.range.end.column,
|
|
1597
|
+
rule: "usage/unused-class",
|
|
1598
|
+
message: `.${name} is never used`
|
|
1599
|
+
}
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
return found;
|
|
1604
|
+
}
|
|
1605
|
+
function collectReferences(file, result, bindings, usage, markOpaque, rel) {
|
|
1606
|
+
const scopeTracker = new ScopeTracker();
|
|
1607
|
+
const ancestors = [];
|
|
1608
|
+
walk(result.program, {
|
|
1609
|
+
scopeTracker,
|
|
1610
|
+
leave() {
|
|
1611
|
+
ancestors.pop();
|
|
1612
|
+
},
|
|
1613
|
+
enter(rawNode, rawParent) {
|
|
1614
|
+
const node = rawNode;
|
|
1615
|
+
ancestors.push(node);
|
|
1616
|
+
if (node.type !== "Identifier" || !rawParent) return;
|
|
1617
|
+
const name = node.name;
|
|
1618
|
+
const binding = bindings.get(name);
|
|
1619
|
+
if (!binding) return;
|
|
1620
|
+
if (!isReferenceIdentifier(rawNode, rawParent, { mode: "value" })) return;
|
|
1621
|
+
const declaration = scopeTracker.getDeclaration(name);
|
|
1622
|
+
if (declaration && declaration.type !== "Import") return;
|
|
1623
|
+
if (rawParent.type === "TSTypeQuery") return;
|
|
1624
|
+
const { css } = binding;
|
|
1625
|
+
let namespace = binding.namespace;
|
|
1626
|
+
let subject = name;
|
|
1627
|
+
let at = throughWrappers(ancestors, ancestors.length - 1);
|
|
1628
|
+
let parent = ancestors[at - 1];
|
|
1629
|
+
if (namespace && isObjectOf(parent, ancestors[at]) && staticKeyOf(parent) === "default") {
|
|
1630
|
+
namespace = false;
|
|
1631
|
+
subject = `${name}.default`;
|
|
1632
|
+
at = throughWrappers(ancestors, at - 1);
|
|
1633
|
+
parent = ancestors[at - 1];
|
|
1634
|
+
}
|
|
1635
|
+
const child = ancestors[at];
|
|
1636
|
+
const target = usage.get(css);
|
|
1637
|
+
if (isObjectOf(parent, child)) {
|
|
1638
|
+
const key = staticKeyOf(parent);
|
|
1639
|
+
if (key !== null) {
|
|
1640
|
+
target.used.add(key);
|
|
1641
|
+
return;
|
|
1642
|
+
}
|
|
1643
|
+
const { property } = parent;
|
|
1644
|
+
if (property.type === "TemplateLiteral") {
|
|
1645
|
+
const { quasis, expressions } = property;
|
|
1646
|
+
const head = quasis[0]?.value.cooked ?? "";
|
|
1647
|
+
const tail = quasis.at(-1)?.value.cooked ?? "";
|
|
1648
|
+
if (expressions.length === 0) {
|
|
1649
|
+
target.used.add(head);
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
if (head !== "" || tail !== "") {
|
|
1653
|
+
target.patterns.push({
|
|
1654
|
+
head,
|
|
1655
|
+
tail
|
|
1656
|
+
});
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
markOpaque(css, {
|
|
1661
|
+
file,
|
|
1662
|
+
offset: parent.start,
|
|
1663
|
+
message: `a class is accessed dynamically here, so usage of ${rel(css)} cannot be determined`
|
|
1664
|
+
});
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
if (parent.type === "VariableDeclarator") {
|
|
1668
|
+
const declarator = parent;
|
|
1669
|
+
if (declarator.init === child && declarator.id.type === "ObjectPattern") {
|
|
1670
|
+
for (const property of declarator.id.properties) {
|
|
1671
|
+
const key = keyNameOf(property);
|
|
1672
|
+
if (key === null || namespace && key === "default") {
|
|
1673
|
+
markOpaque(css, {
|
|
1674
|
+
file,
|
|
1675
|
+
offset: property.start,
|
|
1676
|
+
message: `the module is destructured here without naming each class, so usage of ${rel(css)} cannot be determined`
|
|
1677
|
+
});
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
target.used.add(key);
|
|
1681
|
+
}
|
|
1682
|
+
return;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
markOpaque(css, {
|
|
1686
|
+
file,
|
|
1687
|
+
offset: node.start,
|
|
1688
|
+
message: `${subject} escapes as a value here, so usage of ${rel(css)} cannot be determined`
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
1693
|
+
/** The outermost of `x as T`, `x!` and the like around `ancestors[index]`, which is what consumes it. */
|
|
1694
|
+
function throughWrappers(ancestors, index) {
|
|
1695
|
+
while (index > 0 && TS_WRAPPERS.has(ancestors[index - 1].type) && ancestors[index - 1].expression === ancestors[index]) index--;
|
|
1696
|
+
return index;
|
|
1697
|
+
}
|
|
1698
|
+
function isObjectOf(parent, child) {
|
|
1699
|
+
return parent.type === "MemberExpression" && parent.object === child;
|
|
1700
|
+
}
|
|
1701
|
+
/** The property `x.name` or `x["name"]` reads, or null when it is computed. */
|
|
1702
|
+
function staticKeyOf(member) {
|
|
1703
|
+
const { property, computed } = member;
|
|
1704
|
+
if (!computed && property.type === "Identifier") return property.name;
|
|
1705
|
+
if (property.type === "Literal" && typeof property.value === "string") return property.value;
|
|
1706
|
+
return null;
|
|
1707
|
+
}
|
|
1708
|
+
/** The static key of an object-pattern property, or null for `...rest` and computed keys. */
|
|
1709
|
+
function keyNameOf(property) {
|
|
1710
|
+
if (property.type !== "Property" || property.computed) return null;
|
|
1711
|
+
const key = property.key;
|
|
1712
|
+
if (key.type === "Identifier") return key.name;
|
|
1713
|
+
if (key.type === "Literal") return String(key.value);
|
|
1714
|
+
return null;
|
|
1715
|
+
}
|
|
62
1716
|
/**
|
|
63
|
-
*
|
|
64
|
-
*
|
|
1717
|
+
* CSS files refer to each other too: `composes ... from` and `@value ... from`
|
|
1718
|
+
* make the named file an import, and a composed class is used whenever the
|
|
1719
|
+
* composing class is.
|
|
65
1720
|
*/
|
|
66
|
-
function
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
1721
|
+
function linkCssReferences(modules, byPath, usage, resolvers) {
|
|
1722
|
+
const edges = [];
|
|
1723
|
+
for (const analysis of modules) {
|
|
1724
|
+
for (const specifier of analysis.valueImports) {
|
|
1725
|
+
const to = resolvers.resolve(analysis.file, specifier);
|
|
1726
|
+
if (to && byPath.has(to) && to !== analysis.file) usage.get(to).importers.add(analysis.file);
|
|
1727
|
+
}
|
|
1728
|
+
for (const composes of analysis.composes) {
|
|
1729
|
+
const { className } = composes;
|
|
1730
|
+
if (className === null || composes.from.kind === "global") continue;
|
|
1731
|
+
const to = composes.from.kind === "local" ? analysis.file : resolvers.resolve(analysis.file, composes.from.specifier);
|
|
1732
|
+
if (!to || !byPath.has(to)) continue;
|
|
1733
|
+
if (to !== analysis.file) usage.get(to).importers.add(analysis.file);
|
|
1734
|
+
edges.push({
|
|
1735
|
+
from: analysis.file,
|
|
1736
|
+
className,
|
|
1737
|
+
to,
|
|
1738
|
+
names: composes.names
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
let changed = true;
|
|
1743
|
+
while (changed) {
|
|
1744
|
+
changed = false;
|
|
1745
|
+
for (const edge of edges) {
|
|
1746
|
+
if (!isUsed(usage.get(edge.from), edge.className)) continue;
|
|
1747
|
+
const target = usage.get(edge.to);
|
|
1748
|
+
for (const name of edge.names) {
|
|
1749
|
+
if (target.used.has(name)) continue;
|
|
1750
|
+
target.used.add(name);
|
|
1751
|
+
changed = true;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
72
1754
|
}
|
|
73
|
-
return staticParts.join("/") || ".";
|
|
74
1755
|
}
|
|
75
|
-
function
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
1756
|
+
function isUsed(moduleUsage, name) {
|
|
1757
|
+
if (moduleUsage.opaque.length > 0 || moduleUsage.used.has(name)) return true;
|
|
1758
|
+
return moduleUsage.patterns.some(({ head, tail }) => name.length >= head.length + tail.length && name.startsWith(head) && name.endsWith(tail));
|
|
1759
|
+
}
|
|
1760
|
+
async function findSources(config, cwd) {
|
|
1761
|
+
const ignore = [...defaultIgnore(config), ...IGNORED_DIRS.map((dir) => `${dir}/**`)];
|
|
1762
|
+
return (await fg(SOURCE_GLOBS, {
|
|
80
1763
|
cwd,
|
|
81
|
-
|
|
1764
|
+
ignore,
|
|
1765
|
+
absolute: true
|
|
1766
|
+
})).filter((file) => !/\.d\.[mc]?ts$/.test(file)).sort();
|
|
1767
|
+
}
|
|
1768
|
+
function langOf(file) {
|
|
1769
|
+
const extension = path.extname(file);
|
|
1770
|
+
if (extension === ".tsx") return "tsx";
|
|
1771
|
+
if (extension === ".ts" || extension === ".mts" || extension === ".cts") return "ts";
|
|
1772
|
+
return "jsx";
|
|
1773
|
+
}
|
|
1774
|
+
function relative(cwd, file) {
|
|
1775
|
+
return path.relative(cwd, file).split(path.sep).join("/");
|
|
1776
|
+
}
|
|
1777
|
+
function positionAt(source, offset) {
|
|
1778
|
+
let line = 1;
|
|
1779
|
+
let lineStart = 0;
|
|
1780
|
+
for (let i = 0; i < offset && i < source.length; i++) if (source.charCodeAt(i) === 10) {
|
|
1781
|
+
line++;
|
|
1782
|
+
lineStart = i + 1;
|
|
1783
|
+
}
|
|
1784
|
+
return {
|
|
1785
|
+
line,
|
|
1786
|
+
column: offset - lineStart + 1
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
/**
|
|
1790
|
+
* Module resolution honouring the nearest `tsconfig.json` (for `paths`), one
|
|
1791
|
+
* resolver per config so a monorepo's packages keep their own aliases.
|
|
1792
|
+
*/
|
|
1793
|
+
var Resolvers = class {
|
|
1794
|
+
cwd;
|
|
1795
|
+
byTsconfig = /* @__PURE__ */ new Map();
|
|
1796
|
+
tsconfigByDir = /* @__PURE__ */ new Map();
|
|
1797
|
+
constructor(cwd) {
|
|
1798
|
+
this.cwd = cwd;
|
|
1799
|
+
}
|
|
1800
|
+
resolve(fromFile, specifier) {
|
|
1801
|
+
const directory = path.dirname(fromFile);
|
|
1802
|
+
return this.resolverFor(directory).sync(directory, specifier).path ?? null;
|
|
1803
|
+
}
|
|
1804
|
+
resolverFor(directory) {
|
|
1805
|
+
const tsconfig = this.findTsconfig(directory);
|
|
1806
|
+
let resolver = this.byTsconfig.get(tsconfig);
|
|
1807
|
+
if (!resolver) {
|
|
1808
|
+
resolver = new ResolverFactory({
|
|
1809
|
+
extensions: [
|
|
1810
|
+
".ts",
|
|
1811
|
+
".tsx",
|
|
1812
|
+
".mts",
|
|
1813
|
+
".cts",
|
|
1814
|
+
".js",
|
|
1815
|
+
".jsx",
|
|
1816
|
+
".mjs",
|
|
1817
|
+
".cjs",
|
|
1818
|
+
".css"
|
|
1819
|
+
],
|
|
1820
|
+
extensionAlias: {
|
|
1821
|
+
".js": [
|
|
1822
|
+
".ts",
|
|
1823
|
+
".tsx",
|
|
1824
|
+
".js"
|
|
1825
|
+
],
|
|
1826
|
+
".jsx": [".tsx", ".jsx"],
|
|
1827
|
+
".mjs": [".mts", ".mjs"],
|
|
1828
|
+
".cjs": [".cts", ".cjs"]
|
|
1829
|
+
},
|
|
1830
|
+
conditionNames: ["import", "default"],
|
|
1831
|
+
...tsconfig ? { tsconfig: {
|
|
1832
|
+
configFile: tsconfig,
|
|
1833
|
+
references: "auto"
|
|
1834
|
+
} } : {}
|
|
1835
|
+
});
|
|
1836
|
+
this.byTsconfig.set(tsconfig, resolver);
|
|
1837
|
+
}
|
|
1838
|
+
return resolver;
|
|
1839
|
+
}
|
|
1840
|
+
findTsconfig(directory) {
|
|
1841
|
+
const cached = this.tsconfigByDir.get(directory);
|
|
1842
|
+
if (cached !== void 0) return cached;
|
|
1843
|
+
const candidate = path.join(directory, "tsconfig.json");
|
|
1844
|
+
let found = null;
|
|
1845
|
+
if (fs.existsSync(candidate)) found = candidate;
|
|
1846
|
+
else if (directory !== this.cwd && directory.startsWith(this.cwd)) found = this.findTsconfig(path.dirname(directory));
|
|
1847
|
+
this.tsconfigByDir.set(directory, found);
|
|
1848
|
+
return found;
|
|
1849
|
+
}
|
|
1850
|
+
};
|
|
1851
|
+
//#endregion
|
|
1852
|
+
//#region src/check.ts
|
|
1853
|
+
const CSS_WIDE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1854
|
+
"inherit",
|
|
1855
|
+
"initial",
|
|
1856
|
+
"unset",
|
|
1857
|
+
"revert",
|
|
1858
|
+
"revert-layer"
|
|
1859
|
+
]);
|
|
1860
|
+
const MATH_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
1861
|
+
"calc",
|
|
1862
|
+
"min",
|
|
1863
|
+
"max",
|
|
1864
|
+
"clamp",
|
|
1865
|
+
"round",
|
|
1866
|
+
"mod",
|
|
1867
|
+
"rem",
|
|
1868
|
+
"abs",
|
|
1869
|
+
"sign",
|
|
1870
|
+
"sin",
|
|
1871
|
+
"cos",
|
|
1872
|
+
"tan",
|
|
1873
|
+
"asin",
|
|
1874
|
+
"acos",
|
|
1875
|
+
"atan",
|
|
1876
|
+
"atan2",
|
|
1877
|
+
"pow",
|
|
1878
|
+
"sqrt",
|
|
1879
|
+
"hypot",
|
|
1880
|
+
"log",
|
|
1881
|
+
"exp"
|
|
1882
|
+
]);
|
|
1883
|
+
/** Functions that spell a color out of channel values. */
|
|
1884
|
+
const CHANNEL_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
1885
|
+
"rgb",
|
|
1886
|
+
"rgba",
|
|
1887
|
+
"hsl",
|
|
1888
|
+
"hsla",
|
|
1889
|
+
"hwb",
|
|
1890
|
+
"lab",
|
|
1891
|
+
"lch",
|
|
1892
|
+
"oklab",
|
|
1893
|
+
"oklch",
|
|
1894
|
+
"color",
|
|
1895
|
+
"device-cmyk"
|
|
1896
|
+
]);
|
|
1897
|
+
/** Functions that build a color out of other colors. */
|
|
1898
|
+
const COMPOSING_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
1899
|
+
"color-mix",
|
|
1900
|
+
"light-dark",
|
|
1901
|
+
"contrast-color"
|
|
1902
|
+
]);
|
|
1903
|
+
const GRADIENT_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
1904
|
+
"linear-gradient",
|
|
1905
|
+
"radial-gradient",
|
|
1906
|
+
"conic-gradient",
|
|
1907
|
+
"repeating-linear-gradient",
|
|
1908
|
+
"repeating-radial-gradient",
|
|
1909
|
+
"repeating-conic-gradient"
|
|
1910
|
+
]);
|
|
1911
|
+
const TIME_UNITS = /* @__PURE__ */ new Set(["s", "ms"]);
|
|
1912
|
+
const FONT_SIZE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1913
|
+
"xx-small",
|
|
1914
|
+
"x-small",
|
|
1915
|
+
"small",
|
|
1916
|
+
"medium",
|
|
1917
|
+
"large",
|
|
1918
|
+
"x-large",
|
|
1919
|
+
"xx-large",
|
|
1920
|
+
"xxx-large",
|
|
1921
|
+
"smaller",
|
|
1922
|
+
"larger",
|
|
1923
|
+
"math"
|
|
1924
|
+
]);
|
|
1925
|
+
const FONT_WEIGHT_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1926
|
+
"bold",
|
|
1927
|
+
"bolder",
|
|
1928
|
+
"lighter"
|
|
1929
|
+
]);
|
|
1930
|
+
/** Parts that take the whole value, leaving nothing to a category that takes a part of it. */
|
|
1931
|
+
const WHOLE_VALUE_PARTS = /* @__PURE__ */ new Set([
|
|
1932
|
+
"value",
|
|
1933
|
+
"colors",
|
|
1934
|
+
"shadows"
|
|
1935
|
+
]);
|
|
1936
|
+
const PARTS_BY_PROPERTY = /* @__PURE__ */ new Map();
|
|
1937
|
+
for (const [category, definition] of Object.entries(tokenCategories)) for (const [name, part] of Object.entries(definition.properties)) {
|
|
1938
|
+
const parts = PARTS_BY_PROPERTY.get(name) ?? [];
|
|
1939
|
+
parts.push({
|
|
1940
|
+
category,
|
|
1941
|
+
part
|
|
82
1942
|
});
|
|
83
|
-
|
|
84
|
-
|
|
1943
|
+
PARTS_BY_PROPERTY.set(name, parts);
|
|
1944
|
+
}
|
|
1945
|
+
/**
|
|
1946
|
+
* Check the project: every CSS Modules file the config includes, how the
|
|
1947
|
+
* sources use them, and the project's own global CSS. Throws ConfigError when
|
|
1948
|
+
* include matches no file, the global CSS cannot be read, or it does not
|
|
1949
|
+
* declare the layer.
|
|
1950
|
+
*/
|
|
1951
|
+
async function check(config) {
|
|
1952
|
+
const files = await findCssModules(config);
|
|
1953
|
+
if (files.length === 0) throw new ConfigError(`include matches no files in the project root ${config.root}: ${config.include.join(", ")}`);
|
|
1954
|
+
const globalCss = await loadGlobalCss(config);
|
|
1955
|
+
const layer = config.layer === void 0 ? void 0 : resolveLayer(config.layer, globalCss);
|
|
1956
|
+
const { modules, diagnostics } = await loadCssModules(files.map((file) => fs.realpathSync(file)));
|
|
1957
|
+
const usage = await analyzeUsage(modules, config);
|
|
1958
|
+
const found = [
|
|
1959
|
+
...diagnostics,
|
|
1960
|
+
...modules.flatMap((analysis) => checkCss(analysis, globalCss, layer, usage.filter(({ module }) => module === analysis.file))),
|
|
1961
|
+
...checkGlobalCss(globalCss)
|
|
1962
|
+
];
|
|
1963
|
+
const declared = new Set([...globalCss.tokens.values()].map(({ category }) => category));
|
|
1964
|
+
return {
|
|
1965
|
+
diagnostics: sortDiagnostics(found),
|
|
1966
|
+
modules: files.length,
|
|
1967
|
+
tokens: Object.keys(tokenCategories).filter((category) => declared.has(category))
|
|
1968
|
+
};
|
|
1969
|
+
}
|
|
1970
|
+
/**
|
|
1971
|
+
* Check a CSS Modules file against the pure rules and the tokens the global CSS
|
|
1972
|
+
* declares.
|
|
1973
|
+
*
|
|
1974
|
+
* The pure rules always apply: every selector holds a local class, and so does
|
|
1975
|
+
* its subject outside an @scope rooted at one; `:global`, ids, `!important`,
|
|
1976
|
+
* global-only at-rules and `@value` are reported. Each category the global CSS declares a
|
|
1977
|
+
* token for is restricted: in its properties only its tokens, its keywords and
|
|
1978
|
+
* arithmetic on its tokens pass. Anywhere in the file a token name the global
|
|
1979
|
+
* CSS does not declare is reported, and so is a name it declares without a
|
|
1980
|
+
* category prefix, which is internal to it. A module cannot declare either kind
|
|
1981
|
+
* of name. `composes` outside a rule of a single local class is reported,
|
|
1982
|
+
* which bundlers reject. With a layer, what wrapping the module in it would
|
|
1983
|
+
* break is reported too. The usage problems found about the module are
|
|
1984
|
+
* passed in, so that its disable comments apply to them as well. Pure: reads
|
|
1985
|
+
* nothing but its arguments.
|
|
1986
|
+
*/
|
|
1987
|
+
function checkCss(analysis, globalCss, layer, usage = []) {
|
|
1988
|
+
const disabled = readDisableComments(analysis.root, analysis.file);
|
|
1989
|
+
const context = contextOf(analysis.file, globalCss, null, layer);
|
|
1990
|
+
const diagnostics = sortDiagnostics([
|
|
1991
|
+
...checkRoot(analysis.root, context, disabled.keep),
|
|
1992
|
+
...usage.flatMap(({ node, diagnostic }) => disabled.keep(node, [diagnostic])),
|
|
1993
|
+
...disabled.problems()
|
|
1994
|
+
]);
|
|
1995
|
+
if (layer) return diagnostics;
|
|
1996
|
+
const invalid = analysis.composes.filter(({ className }) => className === null);
|
|
1997
|
+
return sortDiagnostics([...diagnostics, ...invalid.map(({ range }) => ({
|
|
1998
|
+
file: analysis.file,
|
|
1999
|
+
line: range.start.line,
|
|
2000
|
+
column: range.start.column,
|
|
2001
|
+
endLine: range.end.line,
|
|
2002
|
+
endColumn: range.end.column,
|
|
2003
|
+
rule: "invalid-composes",
|
|
2004
|
+
message: "composes is only allowed in a rule whose selector is a single local class"
|
|
2005
|
+
}))]);
|
|
2006
|
+
}
|
|
2007
|
+
/**
|
|
2008
|
+
* Check the project's own stylesheets of the global CSS: their declarations
|
|
2009
|
+
* are held to the tokens like a module's, and a mode may only override a
|
|
2010
|
+
* token. A package's stylesheets are left to the package. Pure.
|
|
2011
|
+
*/
|
|
2012
|
+
function checkGlobalCss(globalCss) {
|
|
2013
|
+
return sortDiagnostics(globalCss.files.filter(({ checked }) => checked).flatMap((file) => {
|
|
2014
|
+
const disabled = readDisableComments(file.root, file.file);
|
|
2015
|
+
const context = contextOf(file.file, globalCss, file);
|
|
2016
|
+
return [...checkRoot(file.root, context, disabled.keep), ...disabled.problems()];
|
|
2017
|
+
}));
|
|
2018
|
+
}
|
|
2019
|
+
function contextOf(file, globalCss, global, layer) {
|
|
2020
|
+
const restrictions = /* @__PURE__ */ new Map();
|
|
2021
|
+
for (const { category } of globalCss.tokens.values()) {
|
|
2022
|
+
if (!category || restrictions.has(category)) continue;
|
|
2023
|
+
const definition = tokenCategories[category];
|
|
2024
|
+
restrictions.set(category, {
|
|
2025
|
+
category,
|
|
2026
|
+
keywords: new Set(definition.keywords),
|
|
2027
|
+
percentages: definition.percentages ?? false,
|
|
2028
|
+
hint: hintFor(category, globalCss.tokens)
|
|
2029
|
+
});
|
|
85
2030
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
2031
|
+
const breakpoints = breakpointsOf(globalCss.tokens);
|
|
2032
|
+
return {
|
|
2033
|
+
file,
|
|
2034
|
+
tokens: globalCss.tokens,
|
|
2035
|
+
restrictions,
|
|
2036
|
+
breakpoints,
|
|
2037
|
+
global,
|
|
2038
|
+
layer
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
/** What to write instead of a raw value: the kinds of token the global CSS declares for the category. */
|
|
2042
|
+
function hintFor(category, tokens) {
|
|
2043
|
+
const names = [...tokens.values()].filter((token) => token.category === category);
|
|
2044
|
+
const hints = [];
|
|
2045
|
+
if (names.some(({ name }) => name !== `--${category}`)) hints.push(`a --${category}-* token`);
|
|
2046
|
+
if (names.some(({ name }) => name === `--${category}`)) hints.push(`var(--${category}), alone or multiplied in calc()`);
|
|
2047
|
+
return `use ${hints.join(", or ")}`;
|
|
2048
|
+
}
|
|
2049
|
+
function checkRoot(root, context, disabled) {
|
|
2050
|
+
const diagnostics = [];
|
|
2051
|
+
const keep = (node, found) => {
|
|
2052
|
+
if (context.global && isForeign(node)) return;
|
|
2053
|
+
diagnostics.push(...disabled(node, found));
|
|
2054
|
+
};
|
|
2055
|
+
if (!context.global) checkPure(root, context.file, keep);
|
|
2056
|
+
if (context.layer) checkLayer(root, context.file, context.layer, keep);
|
|
2057
|
+
if (context.tokens.size > 0 || context.global) root.walkDecls((declaration) => keep(declaration, checkDeclaration(declaration, context)));
|
|
2058
|
+
if (context.global) root.walkAtRules(/^property$/i, (atRule) => {
|
|
2059
|
+
keep(atRule, checkDeclaredName(atRule.params, paramsStart(atRule), atRule, context));
|
|
89
2060
|
});
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
await regenerate(filePath, config.outDir, cwd, config.silent);
|
|
2061
|
+
if (context.restrictions.has("breakpoint")) root.walkAtRules(/^media$/i, (atRule) => {
|
|
2062
|
+
keep(atRule, checkMediaQuery(atRule, context.breakpoints, context.file));
|
|
93
2063
|
});
|
|
94
|
-
|
|
95
|
-
if (
|
|
96
|
-
|
|
2064
|
+
if (context.global) {
|
|
2065
|
+
for (const token of context.tokens.values()) if (token.file === context.file) keep(token.node, checkBreakpointToken(token));
|
|
2066
|
+
}
|
|
2067
|
+
return sortDiagnostics(diagnostics);
|
|
2068
|
+
}
|
|
2069
|
+
function checkDeclaration(declaration, context) {
|
|
2070
|
+
if (isDescriptor(declaration)) return [];
|
|
2071
|
+
const diagnostics = [];
|
|
2072
|
+
const { name, basename, custom } = property(declaration.prop);
|
|
2073
|
+
const start = declaration.source?.start;
|
|
2074
|
+
if (custom && start) diagnostics.push(...checkDeclaredName(declaration.prop, start, declaration, context));
|
|
2075
|
+
const position = valueStart(declaration);
|
|
2076
|
+
if (!position) return diagnostics;
|
|
2077
|
+
const text = declaration.raws.value?.raw ?? declaration.value;
|
|
2078
|
+
const nodes = parseComponents(text, {
|
|
2079
|
+
offset: 0,
|
|
2080
|
+
line: position.line,
|
|
2081
|
+
column: position.column
|
|
97
2082
|
});
|
|
98
|
-
return
|
|
2083
|
+
if (!nodes) return diagnostics;
|
|
2084
|
+
checkReferences(nodes, context, diagnostics);
|
|
2085
|
+
if (custom) return diagnostics;
|
|
2086
|
+
const parts = (PARTS_BY_PROPERTY.get(name) ?? PARTS_BY_PROPERTY.get(basename) ?? []).filter(({ category }) => context.restrictions.has(category));
|
|
2087
|
+
const whole = parts.filter(({ part }) => WHOLE_VALUE_PARTS.has(part));
|
|
2088
|
+
for (const { category, part } of whole.length > 0 ? whole : parts) {
|
|
2089
|
+
const restriction = context.restrictions.get(category);
|
|
2090
|
+
if (restriction) checkPart(part, nodes, {
|
|
2091
|
+
context,
|
|
2092
|
+
text,
|
|
2093
|
+
restriction,
|
|
2094
|
+
diagnostics
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
return diagnostics;
|
|
99
2098
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
2099
|
+
/** In an at-rule such as @font-face or a margin box of @page, at any depth. */
|
|
2100
|
+
function isDescriptor(declaration) {
|
|
2101
|
+
for (let node = declaration.parent; node; node = node.parent) if (node.type === "atrule" && GLOBAL_AT_RULES.has(node.name.toLowerCase())) return true;
|
|
2102
|
+
return false;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* The value of a custom property is free, but its name is not. A module that
|
|
2106
|
+
* declared a token name could feed any raw value through it, and one that
|
|
2107
|
+
* declared an internal name would change the design system from inside. In
|
|
2108
|
+
* the global CSS, a mode may only override a name declared at `:root`.
|
|
2109
|
+
*/
|
|
2110
|
+
function checkDeclaredName(name, start, node, context) {
|
|
2111
|
+
const report = (message) => [{
|
|
2112
|
+
file: context.file,
|
|
2113
|
+
line: start.line,
|
|
2114
|
+
column: start.column,
|
|
2115
|
+
endLine: start.line,
|
|
2116
|
+
endColumn: start.column + name.length,
|
|
2117
|
+
rule: "tokens/declaration",
|
|
2118
|
+
message
|
|
2119
|
+
}];
|
|
2120
|
+
if (context.global) {
|
|
2121
|
+
if (context.tokens.has(name) || declaresToken(node, context.global.conditional)) return [];
|
|
2122
|
+
return report(`${name} is not declared at :root; a mode can only override a token, so declare the token in a :root rule`);
|
|
2123
|
+
}
|
|
2124
|
+
const category = categoryOf(name);
|
|
2125
|
+
if (category && context.restrictions.has(category)) return report(`${name} is a ${category} token name and cannot be declared here; rename the custom property`);
|
|
2126
|
+
if (!category && context.tokens.has(name)) return report(`${name} is internal to the global CSS and cannot be declared here; rename the custom property`);
|
|
2127
|
+
return [];
|
|
2128
|
+
}
|
|
2129
|
+
/**
|
|
2130
|
+
* Report each var() of a token name the global CSS does not declare, which is
|
|
2131
|
+
* most likely a typo, and, outside the global CSS, of an internal name.
|
|
2132
|
+
*/
|
|
2133
|
+
function checkReferences(nodes, context, diagnostics) {
|
|
2134
|
+
for (const node of nodes) walk$1(node, (child) => {
|
|
2135
|
+
if (child.type !== "Function" || child.name.toLowerCase() !== "var") return;
|
|
2136
|
+
const reference = child.children.first;
|
|
2137
|
+
if (reference?.type === "Identifier") {
|
|
2138
|
+
const { name } = reference;
|
|
2139
|
+
const category = categoryOf(name);
|
|
2140
|
+
if (category && context.restrictions.has(category) && !context.tokens.has(name)) {
|
|
2141
|
+
const suggestion = closestToken(name, category, context.tokens);
|
|
2142
|
+
const message = `${name} is not defined in the global CSS${suggestion ? `; did you mean ${suggestion}?` : ""}`;
|
|
2143
|
+
diagnostics.push(...diagnosticAt(context.file, child, child, "tokens/unknown", message));
|
|
2144
|
+
} else if (!category && !context.global && context.tokens.has(name)) {
|
|
2145
|
+
const message = `${name} is internal to the global CSS; use a token with a category prefix`;
|
|
2146
|
+
diagnostics.push(...diagnosticAt(context.file, child, child, "tokens/internal", message));
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
checkReferences(fallbackOf(child), context, diagnostics);
|
|
2150
|
+
});
|
|
2151
|
+
}
|
|
2152
|
+
/** The declared token of the category nearest to a misspelt name, within two edits. */
|
|
2153
|
+
function closestToken(name, category, tokens) {
|
|
2154
|
+
let closest = null;
|
|
2155
|
+
let best = 3;
|
|
2156
|
+
for (const token of tokens.values()) {
|
|
2157
|
+
if (token.category !== category) continue;
|
|
2158
|
+
const distance = editDistance(name, token.name);
|
|
2159
|
+
if (distance < best) {
|
|
2160
|
+
best = distance;
|
|
2161
|
+
closest = token.name;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
return closest;
|
|
2165
|
+
}
|
|
2166
|
+
/** Optimal string alignment distance: a swap of two neighbours counts as one edit. */
|
|
2167
|
+
function editDistance(a, b) {
|
|
2168
|
+
const rows = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
|
|
2169
|
+
for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
|
|
2170
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
2171
|
+
rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + cost);
|
|
2172
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1);
|
|
2173
|
+
}
|
|
2174
|
+
return rows[a.length][b.length];
|
|
2175
|
+
}
|
|
2176
|
+
function checkPart(part, nodes, scope) {
|
|
2177
|
+
switch (part) {
|
|
2178
|
+
case "value":
|
|
2179
|
+
for (const node of nodes) checkQuantity(node, scope, "none");
|
|
2180
|
+
break;
|
|
2181
|
+
case "colors":
|
|
2182
|
+
checkColors(nodes, scope, "colors");
|
|
2183
|
+
break;
|
|
2184
|
+
case "layer-color":
|
|
2185
|
+
for (const layer of layersOf(nodes)) checkColors(layer, scope, "shorthand-color");
|
|
2186
|
+
break;
|
|
2187
|
+
case "shadow-color":
|
|
2188
|
+
for (const layer of layersOf(nodes)) if (!loneVar(layer)) checkColors(layer, scope, "shorthand-color");
|
|
2189
|
+
break;
|
|
2190
|
+
case "gradient-colors":
|
|
2191
|
+
checkColors(nodes, scope, "unknown");
|
|
2192
|
+
break;
|
|
2193
|
+
case "shadows":
|
|
2194
|
+
checkShadows(nodes, scope);
|
|
2195
|
+
break;
|
|
2196
|
+
case "font":
|
|
2197
|
+
checkFont(nodes, scope);
|
|
2198
|
+
break;
|
|
2199
|
+
case "times": checkTimes(nodes, scope);
|
|
2200
|
+
}
|
|
106
2201
|
}
|
|
107
|
-
|
|
108
|
-
const
|
|
2202
|
+
function checkQuantity(node, scope, arithmetic) {
|
|
2203
|
+
const { restriction } = scope;
|
|
2204
|
+
switch (node.type) {
|
|
2205
|
+
case "Identifier":
|
|
2206
|
+
if (arithmetic === "none" && !isKeyword(node, restriction)) reportRaw(scope, node);
|
|
2207
|
+
break;
|
|
2208
|
+
case "Number":
|
|
2209
|
+
if (arithmetic !== "token" && !isZero(node)) reportRaw(scope, node);
|
|
2210
|
+
break;
|
|
2211
|
+
case "Dimension":
|
|
2212
|
+
if (!isZero(node)) reportRaw(scope, node);
|
|
2213
|
+
break;
|
|
2214
|
+
case "Percentage":
|
|
2215
|
+
if (!restriction.percentages && !isZero(node)) reportRaw(scope, node);
|
|
2216
|
+
break;
|
|
2217
|
+
case "Parentheses":
|
|
2218
|
+
node.children.forEach((child) => checkQuantity(child, scope, arithmetic));
|
|
2219
|
+
break;
|
|
2220
|
+
case "Function": {
|
|
2221
|
+
const name = node.name.toLowerCase();
|
|
2222
|
+
if (name === "var") {
|
|
2223
|
+
checkToken(node, scope);
|
|
2224
|
+
for (const child of fallbackOf(node)) checkQuantity(child, scope, "none");
|
|
2225
|
+
} else if (name === "env") {
|
|
2226
|
+
const [, ...fallback] = layersOf(node.children.toArray());
|
|
2227
|
+
for (const child of fallback.flat()) checkQuantity(child, scope, "none");
|
|
2228
|
+
} else if (MATH_FUNCTIONS.has(name)) {
|
|
2229
|
+
const inner = arithmetic === "token" || find(node, isReference) ? "token" : "raw";
|
|
2230
|
+
node.children.forEach((child) => checkQuantity(child, scope, inner));
|
|
2231
|
+
}
|
|
2232
|
+
break;
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
function checkColors(nodes, scope, vars) {
|
|
2237
|
+
const oneColor = vars === "shorthand-color" || vars === "stop-color";
|
|
2238
|
+
let hasColor = false;
|
|
2239
|
+
const undecided = [];
|
|
2240
|
+
for (const node of nodes) if (node.type === "Hash" || node.type === "Identifier" && isRawColorName(node, scope)) {
|
|
2241
|
+
reportRaw(scope, node);
|
|
2242
|
+
hasColor = true;
|
|
2243
|
+
} else if (node.type === "Identifier") hasColor ||= scope.restriction.keywords.has(node.name.toLowerCase());
|
|
2244
|
+
else if (node.type === "Function") {
|
|
2245
|
+
const name = node.name.toLowerCase();
|
|
2246
|
+
if (name === "var") {
|
|
2247
|
+
if (vars === "colors" || oneColor && allowsReference(node, scope)) {
|
|
2248
|
+
checkToken(node, scope);
|
|
2249
|
+
checkColors(fallbackOf(node), scope, "colors");
|
|
2250
|
+
hasColor = true;
|
|
2251
|
+
} else undecided.push(node);
|
|
2252
|
+
} else if (CHANNEL_FUNCTIONS.has(name)) {
|
|
2253
|
+
checkChannelFunction(node, scope);
|
|
2254
|
+
hasColor = true;
|
|
2255
|
+
} else if (COMPOSING_FUNCTIONS.has(name)) {
|
|
2256
|
+
checkColors(node.children.toArray(), scope, "colors");
|
|
2257
|
+
hasColor = true;
|
|
2258
|
+
} else if (GRADIENT_FUNCTIONS.has(name)) checkGradient(node, scope);
|
|
2259
|
+
else checkColors(node.children.toArray(), scope, "unknown");
|
|
2260
|
+
}
|
|
2261
|
+
const isColor = oneColor && !hasColor;
|
|
2262
|
+
for (const node of undecided) {
|
|
2263
|
+
if (isColor) checkToken(node, scope, vars === "shorthand-color");
|
|
2264
|
+
checkColors(fallbackOf(node), scope, isColor ? "colors" : "unknown");
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
function checkChannelFunction(node, scope) {
|
|
2268
|
+
const [first, origin] = node.children.toArray();
|
|
2269
|
+
if (first?.type === "Identifier" && first.name.toLowerCase() === "from" && origin) checkColors([origin], scope, "colors");
|
|
2270
|
+
else reportRaw(scope, node);
|
|
2271
|
+
}
|
|
2272
|
+
function checkGradient(node, scope) {
|
|
2273
|
+
layersOf(node.children.toArray()).forEach((argument, index) => {
|
|
2274
|
+
checkColors(argument, scope, index === 0 && argument.some((child) => child.type === "Identifier" && !scope.restriction.keywords.has(child.name.toLowerCase()) && !isRawColorName(child, scope)) ? "unknown" : "stop-color");
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
function checkShadows(nodes, scope) {
|
|
2278
|
+
for (const layer of layersOf(nodes)) {
|
|
2279
|
+
const token = loneVar(layer);
|
|
2280
|
+
if (token) {
|
|
2281
|
+
checkToken(token, scope);
|
|
2282
|
+
checkShadows(fallbackOf(token), scope);
|
|
2283
|
+
} else if (layer.length !== 1 || !isKeyword(layer[0], scope.restriction)) reportRaw(scope, layer[0], layer[layer.length - 1]);
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* `font: <style, variant, weight, width> <size> / <line-height> <family>`. The
|
|
2288
|
+
* slash pins the size before it and the line height after it; without one only
|
|
2289
|
+
* raw values can be told apart.
|
|
2290
|
+
*/
|
|
2291
|
+
function checkFont(nodes, scope) {
|
|
2292
|
+
const slash = nodes.findIndex((node) => node.type === "Operator" && node.value === "/");
|
|
2293
|
+
const size = slash > 0 ? nodes[slash - 1] : void 0;
|
|
2294
|
+
switch (scope.restriction.category) {
|
|
2295
|
+
case "line-height":
|
|
2296
|
+
if (slash !== -1 && nodes[slash + 1]) checkQuantity(nodes[slash + 1], scope, "none");
|
|
2297
|
+
break;
|
|
2298
|
+
case "font-size":
|
|
2299
|
+
if (size) {
|
|
2300
|
+
checkQuantity(size, scope, "none");
|
|
2301
|
+
break;
|
|
2302
|
+
}
|
|
2303
|
+
for (const node of nodes) if (node.type === "Dimension" || node.type === "Percentage") checkQuantity(node, scope, "none");
|
|
2304
|
+
else if (isIdentifierIn(node, FONT_SIZE_KEYWORDS)) reportRaw(scope, node);
|
|
2305
|
+
break;
|
|
2306
|
+
case "font-weight": for (const node of size ? nodes.slice(0, slash - 1) : nodes) if (node.type === "Number") checkQuantity(node, scope, "none");
|
|
2307
|
+
else if (isIdentifierIn(node, FONT_WEIGHT_KEYWORDS)) reportRaw(scope, node);
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
/** A var() in `transition` or `animation` may be a time, an easing or a name; only raw times are told apart. */
|
|
2311
|
+
function checkTimes(nodes, scope) {
|
|
2312
|
+
for (const node of nodes) walk$1(node, (child) => {
|
|
2313
|
+
if (child.type === "Dimension" && TIME_UNITS.has(child.unit.toLowerCase())) checkQuantity(child, scope, "none");
|
|
2314
|
+
else if (child.type === "Function" && child.name.toLowerCase() === "var") checkTimes(fallbackOf(child), scope);
|
|
2315
|
+
});
|
|
2316
|
+
}
|
|
2317
|
+
/**
|
|
2318
|
+
* Report a `var()` of a custom property that is not a token of the category.
|
|
2319
|
+
* A name of the category the global CSS does not declare, and outside the
|
|
2320
|
+
* global CSS an internal name, are left to `checkReferences`.
|
|
2321
|
+
*/
|
|
2322
|
+
function checkToken(node, scope, inShorthand = false) {
|
|
2323
|
+
const name = node.children.first;
|
|
2324
|
+
if (name?.type !== "Identifier") return;
|
|
2325
|
+
const { category, hint } = scope.restriction;
|
|
2326
|
+
const own = categoryOf(name.name);
|
|
2327
|
+
if (own === category) return;
|
|
2328
|
+
const { tokens, global } = scope.context;
|
|
2329
|
+
if (own === null && !global && tokens.has(name.name)) return;
|
|
2330
|
+
report(scope, node, node, inShorthand ? `${name.name} is taken for the ${category} of this shorthand and is not a ${category} token; ${hint}, or write the longhand` : `${name.name} is not a ${category} token; ${hint}`);
|
|
2331
|
+
}
|
|
2332
|
+
/** The components of the fallback of a `var()`, which css-tree keeps as raw text. */
|
|
2333
|
+
function fallbackOf(node) {
|
|
2334
|
+
const [, , fallback] = node.children.toArray();
|
|
2335
|
+
if (fallback?.type !== "Raw" || !fallback.loc) return [];
|
|
2336
|
+
return parseComponents(fallback.value, fallback.loc.start) ?? [];
|
|
2337
|
+
}
|
|
2338
|
+
/** Whether the name of a var() says it is a token of the category, declared or misspelt. */
|
|
2339
|
+
function allowsReference(node, scope) {
|
|
2340
|
+
const name = node.children.first;
|
|
2341
|
+
return name?.type === "Identifier" && categoryOf(name.name) === scope.restriction.category;
|
|
2342
|
+
}
|
|
2343
|
+
function reportRaw(scope, first, last = first) {
|
|
2344
|
+
if (!first.loc || !last.loc) return;
|
|
2345
|
+
const raw = scope.text.slice(first.loc.start.offset, last.loc.end.offset).replace(/\s+/g, " ");
|
|
2346
|
+
const { category, hint } = scope.restriction;
|
|
2347
|
+
report(scope, first, last, `${raw} is a raw value for ${category}; ${hint}`);
|
|
2348
|
+
}
|
|
2349
|
+
function report(scope, first, last, message) {
|
|
2350
|
+
const rule = `tokens/${scope.restriction.category}`;
|
|
2351
|
+
scope.diagnostics.push(...diagnosticAt(scope.context.file, first, last, rule, message));
|
|
2352
|
+
}
|
|
2353
|
+
function diagnosticAt(file, first, last, rule, message) {
|
|
2354
|
+
if (!first.loc || !last.loc) return [];
|
|
2355
|
+
return [{
|
|
2356
|
+
file,
|
|
2357
|
+
line: first.loc.start.line,
|
|
2358
|
+
column: first.loc.start.column,
|
|
2359
|
+
endLine: last.loc.end.line,
|
|
2360
|
+
endColumn: last.loc.end.column,
|
|
2361
|
+
rule,
|
|
2362
|
+
message
|
|
2363
|
+
}];
|
|
2364
|
+
}
|
|
2365
|
+
function parseComponents(text, start) {
|
|
109
2366
|
try {
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
2367
|
+
const value = parse(text, {
|
|
2368
|
+
context: "value",
|
|
2369
|
+
positions: true,
|
|
2370
|
+
...start
|
|
2371
|
+
});
|
|
2372
|
+
return value.type === "Value" ? value.children.toArray() : null;
|
|
2373
|
+
} catch {
|
|
2374
|
+
return null;
|
|
114
2375
|
}
|
|
115
2376
|
}
|
|
2377
|
+
/** Split components at top-level commas: background layers, shadows, function arguments. */
|
|
2378
|
+
function layersOf(nodes) {
|
|
2379
|
+
const layers = [[]];
|
|
2380
|
+
for (const node of nodes) if (node.type === "Operator" && node.value === ",") layers.push([]);
|
|
2381
|
+
else layers[layers.length - 1].push(node);
|
|
2382
|
+
return layers.filter((layer) => layer.length > 0);
|
|
2383
|
+
}
|
|
2384
|
+
/** The var() a layer consists of, when it is nothing else: a whole shadow. */
|
|
2385
|
+
function loneVar(layer) {
|
|
2386
|
+
const [only] = layer;
|
|
2387
|
+
return layer.length === 1 && only.type === "Function" && only.name.toLowerCase() === "var" ? only : null;
|
|
2388
|
+
}
|
|
2389
|
+
function isReference(node) {
|
|
2390
|
+
return node.type === "Function" && ["var", "env"].includes(node.name.toLowerCase());
|
|
2391
|
+
}
|
|
2392
|
+
function isKeyword(node, restriction) {
|
|
2393
|
+
if (node.type !== "Identifier") return false;
|
|
2394
|
+
const name = node.name.toLowerCase();
|
|
2395
|
+
return CSS_WIDE_KEYWORDS.has(name) || restriction.keywords.has(name);
|
|
2396
|
+
}
|
|
2397
|
+
function isIdentifierIn(node, names) {
|
|
2398
|
+
return node.type === "Identifier" && names.has(node.name.toLowerCase());
|
|
2399
|
+
}
|
|
2400
|
+
/** Named and system colors, which the grammar knows; the category's own keywords are not raw. */
|
|
2401
|
+
function isRawColorName(node, scope) {
|
|
2402
|
+
if (scope.restriction.keywords.has(node.name.toLowerCase())) return false;
|
|
2403
|
+
return lexer.matchType("color", node).matched !== null;
|
|
2404
|
+
}
|
|
2405
|
+
function isZero(node) {
|
|
2406
|
+
return Number(node.value) === 0;
|
|
2407
|
+
}
|
|
116
2408
|
//#endregion
|
|
117
|
-
export {
|
|
2409
|
+
export { ConfigError, check, defineConfig, formatDiagnostic, formatGitHubAnnotation, generate, loadConfig };
|