@teacss/linter 0.0.0-stage → 0.10.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +457 -2
- package/dist/estree.d.ts +168 -0
- package/dist/estree.js +2 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/preset.d.ts +18 -0
- package/dist/preset.js +63 -0
- package/dist/project.d.ts +28 -0
- package/dist/project.js +128 -0
- package/dist/rules.d.ts +40 -0
- package/dist/rules.js +524 -0
- package/dist/sites.d.ts +42 -0
- package/dist/sites.js +383 -0
- package/dist/tokens.d.ts +15 -0
- package/dist/tokens.js +99 -0
- package/package.json +54 -4
package/dist/rules.js
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { OFFICIAL } from "./preset.js";
|
|
2
|
+
import { expandGroup, findSlot, readSettings } from "./project.js";
|
|
3
|
+
import { along, apart, Reader, unwrap } from "./sites.js";
|
|
4
|
+
import { conditionsOf, readTokens } from "./tokens.js";
|
|
5
|
+
const FILES = /\.[cm]?[jt]sx?$/;
|
|
6
|
+
const UNREADABLE_CLASS = "This class value cannot be read statically. Use string literals, cn() or recipe().";
|
|
7
|
+
const UNREADABLE_STYLE = "This style value cannot be read statically. Use classes, or an object literal that sets only the allowed properties.";
|
|
8
|
+
const DEFAULT_STYLE_ALLOW = ["--*"];
|
|
9
|
+
const CATEGORIES = ["layout", "spacing", "color", "typography", "shape", "effects", "motion", "unclassified"];
|
|
10
|
+
const VALUE_KINDS = ["step", "number", "percent", "variable", "literal", "arbitrary", "keyword"];
|
|
11
|
+
const COLOR_KINDS = ["role", "alias", "family", "literal", "keyword"];
|
|
12
|
+
const PLACEHOLDER = /\{\{(\w+)\}\}/g;
|
|
13
|
+
const TEXT = { type: "string", minLength: 1 };
|
|
14
|
+
const ALLOW = { type: "array", items: { type: "string" }, uniqueItems: true };
|
|
15
|
+
const PRESET = { enum: ["official"] };
|
|
16
|
+
const WITHOUT = { type: "array", items: { type: "string", minLength: 1 }, uniqueItems: true };
|
|
17
|
+
const closed = (properties, rest = {}) => ({ type: "object", properties, additionalProperties: false, ...rest });
|
|
18
|
+
const options = (names, properties = {}, rest = {}) => [closed({ ...properties, messages: closed(Object.fromEntries(names.map((name) => [name, TEXT]))) }, rest)];
|
|
19
|
+
let analyses = new Map();
|
|
20
|
+
const flatten = (text) => text.replace(/\r\n|[\r\n]/g, " ");
|
|
21
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
22
|
+
class OptionError extends Error {
|
|
23
|
+
}
|
|
24
|
+
function matcher(patterns, list = "allow") {
|
|
25
|
+
const tests = (Array.isArray(patterns) ? patterns : []).map((pattern) => {
|
|
26
|
+
const regex = /^\/(.+)\/([a-z]*)$/s.exec(pattern);
|
|
27
|
+
if (regex !== null) {
|
|
28
|
+
try {
|
|
29
|
+
return new RegExp(regex[1], regex[2]?.replace(/[gy]/g, ""));
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw new OptionError(`its ${list} pattern "${pattern}" is not a valid regular expression`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (!pattern.includes("*"))
|
|
36
|
+
return pattern;
|
|
37
|
+
return new RegExp(`^${pattern.split("*").map(escape).join(".*")}$`, "s");
|
|
38
|
+
});
|
|
39
|
+
return (...names) => names.some((name) => name !== null && tests.some((test) => (typeof test === "string" ? test === name : test.test(name))));
|
|
40
|
+
}
|
|
41
|
+
const conditional = (pattern) => pattern.startsWith("@") || pattern.startsWith("/^@");
|
|
42
|
+
function allowance(patterns) {
|
|
43
|
+
const conditions = matcher(patterns.filter(conditional));
|
|
44
|
+
return { names: matcher(patterns.filter((pattern) => !conditional(pattern))), condition: (raw) => conditions(`@${raw}`) };
|
|
45
|
+
}
|
|
46
|
+
function render(template, fallback, parts) {
|
|
47
|
+
const values = new Map([
|
|
48
|
+
["class", parts.class ?? ""],
|
|
49
|
+
["property", parts.property ?? ""],
|
|
50
|
+
["value", parts.value ?? ""],
|
|
51
|
+
["member", parts.member ?? ""],
|
|
52
|
+
["owner", parts.owner ?? ""],
|
|
53
|
+
["default", fallback],
|
|
54
|
+
]);
|
|
55
|
+
return flatten(template.replace(PLACEHOLDER, (whole, name) => values.get(name) ?? whole));
|
|
56
|
+
}
|
|
57
|
+
function phrases(context) {
|
|
58
|
+
const [{ messages = {} } = {}] = context.options;
|
|
59
|
+
return (name, fallback, parts = {}) => {
|
|
60
|
+
const template = messages[name];
|
|
61
|
+
return template === undefined ? fallback : render(template, fallback, parts);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function open(context, visit) {
|
|
65
|
+
analyses = new Map();
|
|
66
|
+
if (!FILES.test(context.filename))
|
|
67
|
+
return {};
|
|
68
|
+
const settings = readSettings(context.settings);
|
|
69
|
+
const slot = findSlot(context.filename, context.cwd, settings);
|
|
70
|
+
if (slot === null)
|
|
71
|
+
return {};
|
|
72
|
+
const note = settings.note === "" ? "" : ` ${settings.note}`;
|
|
73
|
+
const report = (start, end, message) => context.report({ message: `${message}${note}`, loc: { start: context.sourceCode.getLocFromIndex(start), end: context.sourceCode.getLocFromIndex(end) } });
|
|
74
|
+
const once = (key, message) => {
|
|
75
|
+
if (slot.reported.has(key))
|
|
76
|
+
return {};
|
|
77
|
+
slot.reported.add(key);
|
|
78
|
+
return { Program: () => report(0, 0, message) };
|
|
79
|
+
};
|
|
80
|
+
if (slot.project === null)
|
|
81
|
+
return slot.failure === null ? {} : once("load", `TeaCSS could not load the project for this file, so its classes are not checked: ${slot.failure}`);
|
|
82
|
+
try {
|
|
83
|
+
return visit({ project: slot.project, reader: new Reader(context.sourceCode, settings.functions), report });
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (!(error instanceof OptionError))
|
|
87
|
+
throw error;
|
|
88
|
+
return once(`${context.id} ${error.message}`, `${context.id} is not checked in this project: ${error.message}.`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function entriesOf(texts, project) {
|
|
92
|
+
const entries = [];
|
|
93
|
+
for (const text of texts) {
|
|
94
|
+
for (const token of readTokens(text.value, text.groups, expandGroup)) {
|
|
95
|
+
const [start, end] = text.locate(token.start, token.end);
|
|
96
|
+
entries.push({ text: token.text, start, end, group: token.group, path: text.path, class: null });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const classes = project.classify(entries.map((entry) => entry.text));
|
|
100
|
+
for (const [index, entry] of entries.entries())
|
|
101
|
+
entry.class = entry.group ? null : (classes[index] ?? null);
|
|
102
|
+
return entries;
|
|
103
|
+
}
|
|
104
|
+
function analyze(node, { project, reader }) {
|
|
105
|
+
const known = analyses.get(node);
|
|
106
|
+
if (known !== undefined)
|
|
107
|
+
return known;
|
|
108
|
+
const site = reader.site(node);
|
|
109
|
+
const analysis = site === null ? null : { entries: entriesOf(site.texts, project), unreadable: site.unreadable };
|
|
110
|
+
analyses.set(node, analysis);
|
|
111
|
+
return analysis;
|
|
112
|
+
}
|
|
113
|
+
function classRule(schema, messenger) {
|
|
114
|
+
return {
|
|
115
|
+
meta: { type: "problem", schema },
|
|
116
|
+
create: (context) => open(context, (file) => {
|
|
117
|
+
const messages = messenger(context, file.project, phrases(context));
|
|
118
|
+
const seen = new Set();
|
|
119
|
+
const visit = (node) => {
|
|
120
|
+
for (const entry of analyze(node, file)?.entries ?? []) {
|
|
121
|
+
const key = `${entry.start} ${entry.end} ${entry.group} ${entry.text}`;
|
|
122
|
+
if (seen.has(key))
|
|
123
|
+
continue;
|
|
124
|
+
seen.add(key);
|
|
125
|
+
for (const message of messages(entry))
|
|
126
|
+
file.report(entry.start, entry.end, message);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
return { JSXAttribute: visit, CallExpression: visit, TaggedTemplateExpression: visit };
|
|
130
|
+
}),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
const partsOf = (token) => ({ class: token.token, property: token.property, value: token.value?.raw });
|
|
134
|
+
const memberParts = (token, member) => ({ ...partsOf(member), class: token.token, member: member.token });
|
|
135
|
+
function judged(entry, accepts, phrase, judge) {
|
|
136
|
+
const token = entry.class;
|
|
137
|
+
if (token === null || accepts(token))
|
|
138
|
+
return [];
|
|
139
|
+
const own = judge(token);
|
|
140
|
+
const messages = own === null ? [] : [phrase(own.name, `"${token.token}" ${own.reason}. ${own.advice}`.trimEnd(), partsOf(token))];
|
|
141
|
+
for (const member of token.shortcut?.members ?? []) {
|
|
142
|
+
const verdict = accepts(member) ? null : judge(member);
|
|
143
|
+
if (verdict !== null)
|
|
144
|
+
messages.push(phrase("member", `"${token.token}" expands to "${member.token}", which ${verdict.reason}.`, memberParts(token, member)));
|
|
145
|
+
}
|
|
146
|
+
return messages;
|
|
147
|
+
}
|
|
148
|
+
const rawColor = (token) => token.color?.kind === "literal" || token.color?.kind === "family";
|
|
149
|
+
const noUnknownClasses = classRule(options(["unknown", "group"], { allow: ALLOW }), (context, _project, phrase) => {
|
|
150
|
+
const [{ allow = [] } = {}] = context.options;
|
|
151
|
+
const allowed = allowance(allow);
|
|
152
|
+
return (entry) => {
|
|
153
|
+
if (allowed.names(entry.text) || conditionsOf(entry.text).some(allowed.condition))
|
|
154
|
+
return [];
|
|
155
|
+
if (entry.group)
|
|
156
|
+
return [phrase("group", `"${entry.text}" is a variant group outside cn(), recipe() or a :css: string, so it generates no CSS.`, { class: entry.text })];
|
|
157
|
+
return entry.class === null ? [phrase("unknown", `"${entry.text}" is not a TeaCSS class and is not in the allow list.`, { class: entry.text })] : [];
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
const noArbitraryValues = classRule(options(["arbitrary", "literal", "condition", "member"], { preset: PRESET, without: WITHOUT, allow: ALLOW, conditions: { type: "boolean" } }), (context, project, phrase) => {
|
|
161
|
+
const [{ preset, without = [], allow = [], conditions = true } = {}] = context.options;
|
|
162
|
+
const allowed = allowance([...(preset === undefined ? [] : OFFICIAL.arbitrary.allow.filter((pattern) => !without.includes(pattern))), ...allow]);
|
|
163
|
+
const accepts = (token) => allowed.names(token.token, token.property);
|
|
164
|
+
return (entry) => judged(entry, accepts, phrase, (token) => {
|
|
165
|
+
const kind = token.value?.kind;
|
|
166
|
+
if (token.color === null && token.property !== null && (kind === "arbitrary" || kind === "literal") && !allowed.names(bare(token))) {
|
|
167
|
+
const example = project.example(token.property);
|
|
168
|
+
const instead = token.categories.includes("color") ? "a role or dictionary name with a step" : `a theme step or number${example === null ? "" : ` such as ${example}`}`;
|
|
169
|
+
return {
|
|
170
|
+
name: kind,
|
|
171
|
+
reason: kind === "arbitrary" ? "uses an arbitrary value" : "uses a literal value",
|
|
172
|
+
advice: `Use ${instead}, or allow "${token.property}:*" in teacss/no-arbitrary-values.`,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const unaccepted = token.conditions.some((condition) => condition.arbitrary && !allowed.condition(condition.raw));
|
|
176
|
+
return conditions && !rawColor(token) && unaccepted ? { name: "condition", reason: "uses an arbitrary condition", advice: "" } : null;
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
const STEPS = { type: "object", additionalProperties: { type: "array", items: { type: "string" }, uniqueItems: true } };
|
|
180
|
+
const noRawColors = classRule(options(["literal", "family", "step", "member"], { preset: PRESET, without: WITHOUT, allow: ALLOW, steps: STEPS }), (context, project, phrase) => {
|
|
181
|
+
const [own = {}] = context.options;
|
|
182
|
+
const without = matcher(own.without ?? [], "without");
|
|
183
|
+
const preset = own.preset === undefined ? [] : Object.entries(OFFICIAL.colors.steps).filter(([name]) => !without(name));
|
|
184
|
+
const steps = { ...Object.fromEntries(preset), ...own.steps };
|
|
185
|
+
const allowed = allowance(own.allow ?? []);
|
|
186
|
+
const accepts = (token) => allowed.names(token.token, bare(token), token.property) || token.conditions.some((condition) => allowed.condition(condition.raw));
|
|
187
|
+
return (entry) => judged(entry, accepts, phrase, (token) => {
|
|
188
|
+
const color = token.color;
|
|
189
|
+
if (color === null)
|
|
190
|
+
return null;
|
|
191
|
+
if (color.kind === "literal")
|
|
192
|
+
return { name: "literal", reason: "uses a literal color", advice: "Use a role or dictionary name with a step." };
|
|
193
|
+
if (color.kind === "family") {
|
|
194
|
+
const bound = project.boundTo(color.name ?? "");
|
|
195
|
+
return { name: "family", reason: `names the palette family "${color.name}"`, advice: `Use a role or dictionary name${bound.length === 0 ? "" : `: ${bound.join(", ")}`}.` };
|
|
196
|
+
}
|
|
197
|
+
const allowed = color.name === null ? undefined : (steps[color.name] ?? steps["*"]);
|
|
198
|
+
if (allowed === undefined || color.step === null || allowed.includes(color.step))
|
|
199
|
+
return null;
|
|
200
|
+
return { name: "step", reason: `uses step ${color.step} of "${color.name}"`, advice: `Allowed steps: ${allowed.join(", ")}.` };
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
const conditionsText = (token) => token.conditions.map((condition) => `@${condition.raw}`).join("");
|
|
204
|
+
function bare(token) {
|
|
205
|
+
const conditions = conditionsText(token);
|
|
206
|
+
const head = conditions !== "" && token.token.endsWith(conditions) ? token.token.slice(0, -conditions.length) : token.token;
|
|
207
|
+
return token.important && head.endsWith("!") ? head.slice(0, -1) : head;
|
|
208
|
+
}
|
|
209
|
+
function selector(option, list) {
|
|
210
|
+
if (typeof option === "string") {
|
|
211
|
+
const named = CATEGORIES.find((name) => name === option.trim().toLowerCase());
|
|
212
|
+
if (named !== undefined && named !== option)
|
|
213
|
+
throw new OptionError(`its ${list} selector "${option}" is not a category name; write "${named}"`);
|
|
214
|
+
if (named !== undefined)
|
|
215
|
+
return { category: named, matches: () => true, label: option, reason: () => `category ${option}`, message: null };
|
|
216
|
+
const pattern = matcher([option], list);
|
|
217
|
+
const matches = conditional(option) ? (token) => token.conditions.some((condition) => pattern(`@${condition.raw}`)) : (token) => pattern(bare(token), token.property);
|
|
218
|
+
return { category: null, matches, label: option, reason: () => `pattern ${option}`, message: null };
|
|
219
|
+
}
|
|
220
|
+
const { category, property, value, kind, color, declares, shortcut } = option;
|
|
221
|
+
const field = (pattern) => (pattern === undefined ? null : matcher([pattern], list));
|
|
222
|
+
const [properties, values, declarations, shortcuts] = [field(property), field(value), field(declares), field(shortcut)];
|
|
223
|
+
const declared = (token) => (token.kind === "utility" ? token.declares.find((name) => declarations?.(name)) : undefined);
|
|
224
|
+
const subject = [category, property, declares, shortcut === undefined ? undefined : `shortcut ${shortcut}`].filter((part) => part !== undefined).join(" ");
|
|
225
|
+
const qualifiers = [value === undefined ? undefined : `value ${value}`, kind === undefined ? undefined : `${kind} values`, color === undefined ? undefined : `${color} colors`].filter((part) => part !== undefined).join(" and ");
|
|
226
|
+
return {
|
|
227
|
+
category: category ?? null,
|
|
228
|
+
matches: (token) => (properties === null || properties(token.property)) &&
|
|
229
|
+
(values === null || values(token.value?.raw ?? null)) &&
|
|
230
|
+
(kind === undefined || token.value?.kind === kind) &&
|
|
231
|
+
(color === undefined || token.color?.kind === color) &&
|
|
232
|
+
(declarations === null || declared(token) !== undefined) &&
|
|
233
|
+
(shortcuts === null || (token.kind === "shortcut" && shortcuts(bare(token)))),
|
|
234
|
+
label: subject === "" || qualifiers === "" ? `${subject}${qualifiers}` : `${subject} with ${qualifiers}`,
|
|
235
|
+
reason: (token) => Object.entries({ category, property, value, kind, color, declares: declares === undefined ? undefined : (declared(token) ?? declares), shortcut })
|
|
236
|
+
.filter(([, text]) => text !== undefined)
|
|
237
|
+
.map(([name, text]) => `${name} ${text}`)
|
|
238
|
+
.join(", "),
|
|
239
|
+
message: option.message ?? null,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function policy(lists) {
|
|
243
|
+
const deny = (lists.deny ?? []).map((option) => selector(option, "deny"));
|
|
244
|
+
const allow = lists.allow?.map((option) => selector(option, "allow")) ?? null;
|
|
245
|
+
const labels = allow?.map(({ label }) => label) ?? [];
|
|
246
|
+
return {
|
|
247
|
+
allowed: allow === null ? null : labels.length === 0 ? "nothing" : labels.length > 8 ? `${labels.slice(0, 8).join(", ")} and ${labels.length - 8} more` : labels.join(", "),
|
|
248
|
+
judge: (token, listed) => {
|
|
249
|
+
const denied = deny.find(({ category, matches }) => (category === null || token.categories.includes(category)) && matches(token));
|
|
250
|
+
if (denied !== undefined)
|
|
251
|
+
return { denied, outside: [] };
|
|
252
|
+
if (!listed || allow === null || allow.some(({ category, matches }) => category === null && matches(token)))
|
|
253
|
+
return null;
|
|
254
|
+
const outside = token.categories.filter((name) => !allow.some(({ category, matches }) => category === name && matches(token)));
|
|
255
|
+
return token.categories.length > 0 && outside.length === 0 ? null : { denied: null, outside };
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
function why(token, { denied, outside }) {
|
|
260
|
+
if (denied !== null)
|
|
261
|
+
return denied.reason(token);
|
|
262
|
+
if (outside.length > 0)
|
|
263
|
+
return `${outside.length === 1 ? "category" : "categories"} ${outside.join(", ")}`;
|
|
264
|
+
return token.kind === "shortcut" ? "a shortcut" : "sets only custom properties";
|
|
265
|
+
}
|
|
266
|
+
const SELECTOR_FIELDS = { category: { enum: CATEGORIES }, property: TEXT, value: TEXT, kind: { enum: VALUE_KINDS }, color: { enum: COLOR_KINDS }, declares: TEXT, shortcut: TEXT };
|
|
267
|
+
const given = (names) => names.map((name) => ({ required: [name] }));
|
|
268
|
+
const SELECTOR_SHAPE = {
|
|
269
|
+
anyOf: given(Object.keys(SELECTOR_FIELDS)),
|
|
270
|
+
not: { required: ["shortcut"], anyOf: given(Object.keys(SELECTOR_FIELDS).filter((name) => name !== "shortcut")) },
|
|
271
|
+
};
|
|
272
|
+
const selectors = (extra) => ({ type: "array", items: { anyOf: [TEXT, closed({ ...SELECTOR_FIELDS, ...extra }, SELECTOR_SHAPE)] }, uniqueItems: true });
|
|
273
|
+
const LISTS = { allow: selectors({}), deny: selectors({ message: TEXT }) };
|
|
274
|
+
const noRestrictedClasses = classRule(options(["denied", "outside", "member"], LISTS, { anyOf: given(["allow", "deny"]) }), (context, _project, phrase) => {
|
|
275
|
+
const [lists = {}] = context.options;
|
|
276
|
+
if (lists.allow === undefined && (lists.deny ?? []).length === 0)
|
|
277
|
+
throw new OptionError("it needs an allow list or a deny list that is not empty");
|
|
278
|
+
const { judge, allowed } = policy(lists);
|
|
279
|
+
const state = (token, verdict) => `is ${verdict.denied === null ? "outside the allowed classes" : `denied by ${context.id}`} (${why(token, verdict)})`;
|
|
280
|
+
return (entry) => {
|
|
281
|
+
const token = entry.class;
|
|
282
|
+
if (token === null)
|
|
283
|
+
return [];
|
|
284
|
+
const own = judge(token, true);
|
|
285
|
+
if (token.shortcut?.origin !== "project" || (own !== null && own.denied !== null)) {
|
|
286
|
+
if (own === null)
|
|
287
|
+
return [];
|
|
288
|
+
const fallback = `"${token.token}" ${state(token, own)}.${own.denied === null ? ` Allowed: ${allowed}.` : ""}`;
|
|
289
|
+
const custom = own.denied?.message ?? null;
|
|
290
|
+
return [custom === null ? phrase(own.denied === null ? "outside" : "denied", fallback, partsOf(token)) : render(custom, fallback, partsOf(token))];
|
|
291
|
+
}
|
|
292
|
+
const messages = [];
|
|
293
|
+
for (const member of token.shortcut.members) {
|
|
294
|
+
const verdict = judge(member, own !== null);
|
|
295
|
+
if (verdict === null)
|
|
296
|
+
continue;
|
|
297
|
+
const expands = `"${token.token}" expands to "${member.token}"`;
|
|
298
|
+
const custom = verdict.denied?.message ?? null;
|
|
299
|
+
if (custom === null)
|
|
300
|
+
messages.push(phrase("member", `${expands}, which ${state(member, verdict)}.`, memberParts(token, member)));
|
|
301
|
+
else
|
|
302
|
+
messages.push(`${expands}: ${render(custom, `"${member.token}" ${state(member, verdict)}.`, { ...partsOf(member), member: member.token })}`);
|
|
303
|
+
}
|
|
304
|
+
return messages;
|
|
305
|
+
};
|
|
306
|
+
});
|
|
307
|
+
function blockOf(name) {
|
|
308
|
+
const at = name.indexOf("--");
|
|
309
|
+
return at > 0 ? name.slice(0, at) : name;
|
|
310
|
+
}
|
|
311
|
+
const NAMES = { type: "array", items: TEXT, uniqueItems: true, minItems: 2 };
|
|
312
|
+
const EXCLUSIVE = { type: "array", items: { anyOf: [NAMES, closed({ names: NAMES, conditions: { enum: ["same", "any"] } }, { required: ["names"] })] } };
|
|
313
|
+
const CONTRACT = { ...LISTS, message: TEXT };
|
|
314
|
+
const RESTYLE = {
|
|
315
|
+
preset: PRESET,
|
|
316
|
+
without: WITHOUT,
|
|
317
|
+
contracts: { type: "array", items: closed({ pattern: TEXT, ...CONTRACT, exclusive: EXCLUSIVE }, { required: ["pattern"], anyOf: given(["deny", "allow", "exclusive"]) }) },
|
|
318
|
+
components: { type: "array", items: closed({ name: TEXT, ...CONTRACT }, { required: ["name"], anyOf: given(["deny", "allow"]) }) },
|
|
319
|
+
requireBase: { type: "boolean" },
|
|
320
|
+
standalone: { type: "array", items: { anyOf: [TEXT, closed({ name: TEXT, beside: TEXT }, { required: ["name", "beside"] })] }, uniqueItems: true },
|
|
321
|
+
};
|
|
322
|
+
const noRestyle = {
|
|
323
|
+
meta: { type: "problem", schema: options(["restyle", "conflict", "base", "member"], RESTYLE, { anyOf: given(["preset", "contracts", "components", "requireBase"]) }) },
|
|
324
|
+
create: (context) => open(context, ({ project, reader, report }) => {
|
|
325
|
+
const phrase = phrases(context);
|
|
326
|
+
const [own = {}] = context.options;
|
|
327
|
+
const preset = own.preset === undefined ? {} : OFFICIAL.restyle;
|
|
328
|
+
const without = matcher(own.without ?? [], "without");
|
|
329
|
+
const group = (option) => (Array.isArray(option) ? { names: option, any: false } : { names: option.names, any: option.conditions === "any" });
|
|
330
|
+
const compile = (option, target, list) => ({ targets: matcher([target], list), policy: policy(option), exclusive: (option.exclusive ?? []).map(group), message: option.message ?? null });
|
|
331
|
+
const kept = (preset.contracts ?? []).filter(({ pattern = "" }) => !without(pattern)).map((option) => ({ ...option, exclusive: option.exclusive?.filter((names) => !group(names).names.some((name) => without(name))) }));
|
|
332
|
+
const contracts = [...kept, ...(own.contracts ?? [])].map((option) => compile(option, option.pattern ?? "", "contracts"));
|
|
333
|
+
const components = [...(preset.components ?? []), ...(own.components ?? [])].map((option) => compile(option, option.name ?? "", "components"));
|
|
334
|
+
const requireBase = own.requireBase ?? preset.requireBase ?? false;
|
|
335
|
+
const standalone = [...(preset.standalone ?? []), ...(own.standalone ?? [])].map((option) => (typeof option === "string" ? { name: matcher([option], "standalone"), beside: null } : { name: matcher([option.name], "standalone"), beside: matcher([option.beside], "standalone") }));
|
|
336
|
+
if (contracts.length === 0 && components.length === 0 && !requireBase)
|
|
337
|
+
throw new OptionError("it needs contracts, components, requireBase or a preset");
|
|
338
|
+
const seen = new Set();
|
|
339
|
+
const say = ({ token, entry, via }, name, verb, tail, owner, custom) => {
|
|
340
|
+
const direct = `"${token.token}" ${verb}`;
|
|
341
|
+
let message;
|
|
342
|
+
if (via === null)
|
|
343
|
+
message = custom === null ? phrase(name, `${direct}${tail}`, { ...partsOf(token), owner }) : render(custom, `${direct}${tail}`, { ...partsOf(token), owner });
|
|
344
|
+
else if (custom === null)
|
|
345
|
+
message = phrase("member", `"${via.token}" expands to "${token.token}", which ${verb}.`, { ...memberParts(via, token), owner });
|
|
346
|
+
else
|
|
347
|
+
message = `"${via.token}" expands to "${token.token}": ${render(custom, `${direct}.`, { ...partsOf(token), member: token.token, owner })}`;
|
|
348
|
+
const key = `${entry.start} ${entry.end} ${message}`;
|
|
349
|
+
if (seen.has(key))
|
|
350
|
+
return;
|
|
351
|
+
seen.add(key);
|
|
352
|
+
report(entry.start, entry.end, message);
|
|
353
|
+
};
|
|
354
|
+
const restyle = (unit, owner, contract, judged) => {
|
|
355
|
+
const verdict = contract.policy.judge(unit.token, true);
|
|
356
|
+
if (verdict === null)
|
|
357
|
+
return;
|
|
358
|
+
judged.add(unit);
|
|
359
|
+
const allowed = contract.policy.allowed === null ? "" : ` Allowed with ${owner}: ${contract.policy.allowed}.`;
|
|
360
|
+
say(unit, "restyle", `restyles ${owner} (${why(unit.token, verdict)})`, `.${allowed}`, owner, verdict.denied?.message ?? contract.message);
|
|
361
|
+
};
|
|
362
|
+
const check = (list) => {
|
|
363
|
+
const units = [];
|
|
364
|
+
for (const entry of entriesOf(list.texts, project)) {
|
|
365
|
+
if (entry.class === null)
|
|
366
|
+
continue;
|
|
367
|
+
units.push({ token: entry.class, entry, via: null });
|
|
368
|
+
if (entry.class.shortcut?.origin === "project")
|
|
369
|
+
for (const member of entry.class.shortcut.members)
|
|
370
|
+
units.push({ token: member, entry, via: entry.class });
|
|
371
|
+
}
|
|
372
|
+
const leaves = units.filter(({ token }) => token.shortcut?.origin !== "project");
|
|
373
|
+
const names = [...new Set(units.map(({ token }) => bare(token)))];
|
|
374
|
+
const judged = new Set();
|
|
375
|
+
for (const contract of contracts) {
|
|
376
|
+
const subjects = units.filter(({ token }) => token.kind === "shortcut" && contract.targets(bare(token)));
|
|
377
|
+
const blocks = subjects.map(({ token }) => blockOf(bare(token)));
|
|
378
|
+
for (const unit of subjects.length === 0 ? [] : leaves) {
|
|
379
|
+
const name = bare(unit.token);
|
|
380
|
+
if (subjects.some((subject) => subject === unit || subject.token === unit.via))
|
|
381
|
+
continue;
|
|
382
|
+
if (unit.token.kind === "shortcut" && blocks.some((block) => name === block || name.startsWith(`${block}-`)))
|
|
383
|
+
continue;
|
|
384
|
+
const owner = subjects.find((subject) => !apart(subject.entry.path, unit.entry.path));
|
|
385
|
+
if (owner !== undefined)
|
|
386
|
+
restyle(unit, bare(owner.token), contract, judged);
|
|
387
|
+
}
|
|
388
|
+
for (const { names: group, any } of contract.exclusive) {
|
|
389
|
+
const earlier = [];
|
|
390
|
+
for (const unit of units) {
|
|
391
|
+
const name = bare(unit.token);
|
|
392
|
+
if (!group.includes(name))
|
|
393
|
+
continue;
|
|
394
|
+
const other = earlier.find(({ token, entry }) => bare(token) !== name && along(entry.path, unit.entry.path) && (any || conditionsText(token) === conditionsText(unit.token)));
|
|
395
|
+
earlier.push(unit);
|
|
396
|
+
if (other === undefined)
|
|
397
|
+
continue;
|
|
398
|
+
judged.add(unit);
|
|
399
|
+
say(unit, "conflict", `conflicts with "${other.token.token}"`, `: write one of ${group.join(", ")}.`, "", null);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (list.element !== null)
|
|
404
|
+
for (const component of components)
|
|
405
|
+
if (component.targets(list.element))
|
|
406
|
+
for (const unit of leaves)
|
|
407
|
+
restyle(unit, `<${list.element}>`, component, judged);
|
|
408
|
+
if (!requireBase || !list.complete)
|
|
409
|
+
return;
|
|
410
|
+
for (const unit of leaves) {
|
|
411
|
+
const name = bare(unit.token);
|
|
412
|
+
const block = blockOf(name);
|
|
413
|
+
if (unit.token.shortcut?.origin !== "preset" || block === name || names.includes(block) || judged.has(unit))
|
|
414
|
+
continue;
|
|
415
|
+
if (standalone.some((entry) => entry.name(name) && (entry.beside === null || entry.beside(...names))))
|
|
416
|
+
continue;
|
|
417
|
+
if (project.classify([block])[0]?.kind === "shortcut")
|
|
418
|
+
say(unit, "base", `needs its base class "${block}" in the same class list`, ".", block, null);
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
const found = new Map();
|
|
422
|
+
const visit = (node) => {
|
|
423
|
+
found.set(node, reader.lists(node));
|
|
424
|
+
};
|
|
425
|
+
return {
|
|
426
|
+
JSXAttribute: visit,
|
|
427
|
+
CallExpression: visit,
|
|
428
|
+
TaggedTemplateExpression: visit,
|
|
429
|
+
"Program:exit": () => {
|
|
430
|
+
const inlined = new Set([...found.values()].flat().flatMap((list) => list.inlined));
|
|
431
|
+
for (const [node, lists] of found)
|
|
432
|
+
if (!inlined.has(node))
|
|
433
|
+
for (const list of lists)
|
|
434
|
+
check(list);
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}),
|
|
438
|
+
};
|
|
439
|
+
const requireStaticClasses = {
|
|
440
|
+
meta: { type: "problem", schema: options(["unreadable"]) },
|
|
441
|
+
create: (context) => open(context, (file) => {
|
|
442
|
+
const message = phrases(context)("unreadable", UNREADABLE_CLASS);
|
|
443
|
+
const visit = (node) => {
|
|
444
|
+
for (const unreadable of analyze(node, file)?.unreadable ?? [])
|
|
445
|
+
file.report(unreadable.start, unreadable.end, message);
|
|
446
|
+
};
|
|
447
|
+
return { JSXAttribute: visit, CallExpression: visit, TaggedTemplateExpression: visit };
|
|
448
|
+
}),
|
|
449
|
+
};
|
|
450
|
+
function cssProperty(name) {
|
|
451
|
+
if (name.startsWith("--"))
|
|
452
|
+
return name;
|
|
453
|
+
return name.replace(/^ms(?=[A-Z])/, "-ms").replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
454
|
+
}
|
|
455
|
+
const noInlineStyles = {
|
|
456
|
+
meta: { type: "problem", schema: options(["property", "unreadable"], { allow: ALLOW }) },
|
|
457
|
+
create: (context) => open(context, ({ reader, report }) => {
|
|
458
|
+
const phrase = phrases(context);
|
|
459
|
+
const unreadable = phrase("unreadable", UNREADABLE_STYLE);
|
|
460
|
+
const [{ allow = DEFAULT_STYLE_ALLOW } = {}] = context.options;
|
|
461
|
+
const allowed = matcher(allow);
|
|
462
|
+
const only = allow.length === 1 && allow[0] === "--*" ? "only custom properties (--*) are allowed here" : `allowed here: ${allow.length === 0 ? "nothing" : allow.join(", ")}`;
|
|
463
|
+
const sets = (node, name) => {
|
|
464
|
+
if (!allowed(name))
|
|
465
|
+
report(node.start, node.end, phrase("property", `Inline style sets "${name}". Use classes; ${only}.`, { property: name }));
|
|
466
|
+
};
|
|
467
|
+
const read = (expression, follow) => {
|
|
468
|
+
const node = unwrap(expression);
|
|
469
|
+
const binding = node.type === "Identifier" && follow ? reader.bind(node) : null;
|
|
470
|
+
if (binding?.kind === "const")
|
|
471
|
+
read(binding.init, false);
|
|
472
|
+
else if (node.type === "ConditionalExpression") {
|
|
473
|
+
read(node.consequent, follow);
|
|
474
|
+
read(node.alternate, follow);
|
|
475
|
+
}
|
|
476
|
+
else if (node.type === "LogicalExpression") {
|
|
477
|
+
if (node.operator !== "&&")
|
|
478
|
+
read(node.left, follow);
|
|
479
|
+
read(node.right, follow);
|
|
480
|
+
}
|
|
481
|
+
else if (node.type === "ObjectExpression") {
|
|
482
|
+
for (const property of node.properties) {
|
|
483
|
+
const key = property.type === "Property" ? unwrap(property.key) : null;
|
|
484
|
+
if (property.type === "SpreadElement")
|
|
485
|
+
read(property.argument, follow);
|
|
486
|
+
else if (key?.type === "Identifier" && !property.computed)
|
|
487
|
+
sets(key, cssProperty(key.name));
|
|
488
|
+
else if (key?.type === "Literal" && typeof key.value === "string")
|
|
489
|
+
sets(key, cssProperty(key.value));
|
|
490
|
+
else
|
|
491
|
+
report(property.key.start, property.key.end, unreadable);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
else if (node.type === "Literal") {
|
|
495
|
+
if (typeof node.value !== "string")
|
|
496
|
+
return;
|
|
497
|
+
for (const declaration of node.value.split(";")) {
|
|
498
|
+
const name = declaration.slice(0, Math.max(0, declaration.indexOf(":"))).trim();
|
|
499
|
+
if (name !== "")
|
|
500
|
+
sets(node, name);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
else if ((node.type !== "Identifier" || node.name !== "undefined") && !reader.fromParameter(node))
|
|
504
|
+
report(node.start, node.end, unreadable);
|
|
505
|
+
};
|
|
506
|
+
return {
|
|
507
|
+
JSXAttribute(node) {
|
|
508
|
+
if (node.type !== "JSXAttribute" || node.name.type !== "JSXIdentifier" || node.name.name !== "style" || node.value === null)
|
|
509
|
+
return;
|
|
510
|
+
read(node.value.type === "JSXExpressionContainer" ? node.value.expression : node.value, true);
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
}),
|
|
514
|
+
};
|
|
515
|
+
export const rules = {
|
|
516
|
+
"no-unknown-classes": noUnknownClasses,
|
|
517
|
+
"no-arbitrary-values": noArbitraryValues,
|
|
518
|
+
"no-raw-colors": noRawColors,
|
|
519
|
+
"no-restricted-classes": noRestrictedClasses,
|
|
520
|
+
"no-restyle": noRestyle,
|
|
521
|
+
"no-inline-styles": noInlineStyles,
|
|
522
|
+
"require-static-classes": requireStaticClasses,
|
|
523
|
+
};
|
|
524
|
+
//# sourceMappingURL=rules.js.map
|
package/dist/sites.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Identifier, Node, SourceCode } from "./estree.js";
|
|
2
|
+
export interface ClassText {
|
|
3
|
+
value: string;
|
|
4
|
+
node: Node;
|
|
5
|
+
groups: boolean;
|
|
6
|
+
path: string;
|
|
7
|
+
locate(start: number, end: number): [number, number];
|
|
8
|
+
}
|
|
9
|
+
export interface Site {
|
|
10
|
+
texts: ClassText[];
|
|
11
|
+
unreadable: Node[];
|
|
12
|
+
}
|
|
13
|
+
export interface ClassList {
|
|
14
|
+
texts: ClassText[];
|
|
15
|
+
complete: boolean;
|
|
16
|
+
inlined: Node[];
|
|
17
|
+
element: string | null;
|
|
18
|
+
}
|
|
19
|
+
export declare function along(a: string, b: string): boolean;
|
|
20
|
+
export declare function apart(a: string, b: string): boolean;
|
|
21
|
+
export type Binding = {
|
|
22
|
+
kind: "parameter";
|
|
23
|
+
fallback: Node | null;
|
|
24
|
+
} | {
|
|
25
|
+
kind: "const";
|
|
26
|
+
init: Node;
|
|
27
|
+
} | {
|
|
28
|
+
kind: "import";
|
|
29
|
+
} | {
|
|
30
|
+
kind: "other";
|
|
31
|
+
};
|
|
32
|
+
export declare function unwrap(node: Node): Node;
|
|
33
|
+
export declare class Reader {
|
|
34
|
+
#private;
|
|
35
|
+
constructor(source: SourceCode, functions: ReadonlySet<string>);
|
|
36
|
+
site(node: Node): Site | null;
|
|
37
|
+
lists(node: Node): ClassList[];
|
|
38
|
+
bind(node: Identifier, depth?: number): Binding;
|
|
39
|
+
fromParameter(node: Node, depth?: number): boolean;
|
|
40
|
+
resolve(node: Node): Node;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=sites.d.ts.map
|