designsnitch 0.3.0 → 0.5.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/src/check.js CHANGED
@@ -1,15 +1,21 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { replacementNames } from "./config.js";
4
- import { normalizeHex } from "./core/color.js";
3
+ import { replacementNames, tokenSettings } from "./config.js";
4
+ import { findArbitraryColors, tokenToClass } from "./core/classes.js";
5
+ import { colorLabel, normalizeColor, parseColor } from "./core/color.js";
5
6
  import { findCssColors } from "./core/css.js";
7
+ import { cssColorPrefixes, recommendColorCandidate, selectColorTokens, tokenVar, utilityColorPrefixes } from "./core/tokens.js";
6
8
  import { createEngine } from "./engine.js";
7
9
  import { splitPaths } from "./files.js";
8
10
  import plugin from "./index.js";
9
11
  import { messages, resolveLang } from "./messages.js";
10
12
  import { loadTokens } from "./rules/load-tokens.js";
13
+ import uncheckedColors from "./rules/unchecked-colors.js";
11
14
 
12
15
  const RULE_PREFIX = "designsnitch/";
16
+ const UNCHECKED_RULE = "designsnitch-internal/unchecked-colors";
17
+ const internalPlugin = { rules: { "unchecked-colors": uncheckedColors } };
18
+ const MAX_DECISION_LOCATIONS = 5;
13
19
 
14
20
  /**
15
21
  * @typedef {object} Violation
@@ -23,12 +29,27 @@ const RULE_PREFIX = "designsnitch/";
23
29
  * @property {string} message
24
30
  * @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
25
31
  * @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
26
- * @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
27
- * replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
32
+ * @property {string | null} recommended 바로 바꿀 후보 또는 역할에 맞는 유일한 후보
33
+ * @property {"replace" | "migrate" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
34
+ * replace: found 를 candidates 의 값으로 바꿔도 화면과 동작이 같다 (후보가 하나뿐인 색 오류)
35
+ * migrate: raw 태그를 하나뿐인 후보 컴포넌트로 옮긴다. 컴포넌트를 읽고 props 와 스타일을 맞춰야 한다
28
36
  * ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
29
37
  * repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
30
38
  */
31
39
 
40
+ /**
41
+ * @typedef {object} Decision
42
+ * @property {string} id
43
+ * @property {string} rule
44
+ * @property {string} subject 정규화한 색 또는 꺾쇠로 감싼 태그 이름
45
+ * @property {number} uses 위반 횟수
46
+ * @property {number} files 위반이 있는 파일 수
47
+ * @property {Pick<Violation, "file" | "line" | "column">[]} locations 위반 위치 최대 다섯 곳
48
+ * @property {string[]} candidates
49
+ * @property {string | null} recommended 각 위치에서 추천이 같을 때 그 후보
50
+ * @property {("multiple-candidates" | "no-token" | "themed-token" | "class-only-token" | "dynamic-props")[]} reasons
51
+ */
52
+
32
53
  /**
33
54
  * 프로젝트를 검사한다. 프로젝트의 ESLint 설정은 쓰지 않고 designsnitch 규칙만 실행한다.
34
55
  * @param {object} options
@@ -36,74 +57,102 @@ const RULE_PREFIX = "designsnitch/";
36
57
  * @param {ReturnType<typeof import("./config.js").loadConfig>} options.config
37
58
  * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
38
59
  * @param {"en" | "ko"} [options.lang] 문장의 언어. 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
60
+ * @param {string} [options.sourceCwd] 임시 복사본을 검사할 때 원본 프로젝트 디렉터리
39
61
  * @returns {Promise<{
40
62
  * designSystem: { colorTokens: number, components: number, replacedTags: number },
41
63
  * problems: string[],
42
64
  * next: string[],
43
65
  * summary: { files: number, errors: number, warnings: number },
44
66
  * violations: Violation[],
67
+ * decisions: Decision[],
45
68
  * }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제,
46
69
  * next 는 이 결과를 받은 에이전트가 순서대로 할 일
47
70
  */
48
- export async function check({ cwd, config, paths = ["."], lang }) {
71
+ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd }) {
49
72
  lang = resolveLang(lang, config.lang);
50
73
  const m = messages(lang);
74
+ const root = path.resolve(sourceCwd, config.root ?? ".");
51
75
  // 규칙도 같은 언어를 쓰도록 설정에 실어 보낸다.
52
- const settings = { designsnitch: { ...config, lang } };
76
+ const settings = { designsnitch: { ...config, root, lang } };
53
77
  // 설정에 문제가 있으면 파일을 검사하기 전에 알린다.
54
78
  const tokens = loadTokens(settings, cwd);
55
79
  if (config.components) {
56
- const dir = path.resolve(cwd, config.components.path);
80
+ const dir = path.resolve(root, config.components.path);
57
81
  if (!fs.existsSync(dir)) {
58
82
  throw new Error(m.componentsDirMissing({ dir }));
59
83
  }
60
84
  }
61
85
  const designSystem = describeDesignSystem(tokens, config);
62
- const problems = [];
63
- if (designSystem.colorTokens === 0) {
64
- problems.push(m.noColorTokens({ tokens: config.tokens }));
86
+ const problems = [...tokens.problems];
87
+ if (designSystem.colorTokens + designSystem.paletteColors === 0) {
88
+ problems.push(m.noColorTokens({ tokens: tokenSettings(config.tokens).file }));
65
89
  }
66
90
 
67
91
  const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
68
92
 
69
93
  // JS, TS 는 ESLint 로 규칙을 실행하고, CSS 는 직접 읽는다.
70
- const eslint = createEngine({ cwd, config: { ...plugin.configs.recommended, settings } });
94
+ const recommended = plugin.configs.recommended;
95
+ const eslint = createEngine({
96
+ cwd,
97
+ config: {
98
+ plugins: { ...recommended.plugins, "designsnitch-internal": internalPlugin },
99
+ rules: { ...recommended.rules, [UNCHECKED_RULE]: "warn" },
100
+ settings,
101
+ },
102
+ });
71
103
  const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
104
+ // 검사하지 못한 색은 위반이 아니라 개수로만 알린다. 놓친 것이 있다는 사실을 숨기지 않기 위해서다.
105
+ const uncheckedFiles = results
106
+ // 토큰을 정의하는 파일(tailwind.config.js)의 색은 놓친 색이 아니다.
107
+ .filter((result) => !tokens.files.has(realPath(result.filePath)))
108
+ .map((result) => result.messages.filter((message) => message.ruleId === UNCHECKED_RULE).length)
109
+ .filter((n) => n > 0);
110
+ const unchecked = { colors: uncheckedFiles.reduce((a, b) => a + b, 0), files: uncheckedFiles.length };
72
111
  const scriptViolations = results.flatMap((result) => {
73
112
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
74
113
  return result.messages
75
114
  .filter(isOurs)
76
115
  .map((message) => toViolation(file, result.source, message, config));
77
116
  });
78
- const cssViolations = cssFiles.flatMap((file) =>
79
- checkCss(file, fs.readFileSync(path.resolve(cwd, file), "utf8"), tokens, m),
80
- );
117
+ const cssViolations = cssFiles.flatMap((file) => {
118
+ const source = fs.readFileSync(path.resolve(cwd, file), "utf8");
119
+ const skipCustomProperties = tokens.files.has(realPath(path.resolve(sourceCwd, file)));
120
+ return checkCss(file, source, tokens, m, { skipCustomProperties });
121
+ });
81
122
 
82
- const violations = [...scriptViolations, ...cssViolations]
123
+ const findings = [...scriptViolations, ...cssViolations]
83
124
  .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
84
- .map(({ messageId, ...violation }) => ({ ...violation, action: actionFor(violation, messageId) }));
125
+ .map((finding) => {
126
+ const action = actionFor(finding, finding.messageId);
127
+ const recommended = action === "replace" || action === "migrate" ? finding.candidates[0] : finding.recommended ?? null;
128
+ return { ...finding, action, recommended };
129
+ });
130
+ const violations = findings.map(({ messageId, ...violation }) => violation);
131
+ const decisions = groupDecisions(findings);
85
132
 
86
133
  return {
87
134
  designSystem,
88
135
  problems,
89
- next: nextSteps(designSystem, violations, lang),
136
+ next: nextSteps(designSystem, violations, lang, decisions),
90
137
  summary: {
91
138
  files: results.length + cssFiles.length,
92
139
  errors: violations.filter((v) => v.severity === "error").length,
93
140
  warnings: violations.filter((v) => v.severity === "warning").length,
94
141
  },
95
142
  violations,
143
+ decisions,
144
+ unchecked,
96
145
  };
97
146
  }
98
147
 
99
148
  /**
100
- * CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
101
- * @returns {(Omit<Violation, "action"> & { messageId?: string })[]}
149
+ * CSS 파일 하나의 색을 토큰과 비교한다. 대체 후보는 선언에서는 var(--토큰), @apply 에서는 토큰 클래스다.
150
+ * @returns {(Omit<Violation, "action" | "recommended"> & { recommended?: string | null, messageId?: string })[]}
102
151
  */
103
- function checkCss(file, source, tokens, m) {
152
+ function checkCss(file, source, tokens, m, options) {
104
153
  let colors;
105
154
  try {
106
- colors = findCssColors(source);
155
+ colors = findCssColors(source, options);
107
156
  } catch (error) {
108
157
  const at = { line: error.line ?? 1, column: error.column ?? 1 };
109
158
  return [
@@ -123,9 +172,30 @@ function checkCss(file, source, tokens, m) {
123
172
 
124
173
  return colors
125
174
  .filter((color) => !color.disabled)
126
- .map(({ value, prop, disabled, ...location }) => {
127
- const tokenNames = tokens.colors.get(normalizeHex(value)) ?? [];
128
- const candidates = tokenNames.map((name) => `var(${name})`);
175
+ .map(({ value, prop, utility, text, disabled, ...location }) => {
176
+ // @apply 의 클래스는 JS 의 클래스처럼 토큰 클래스로, 선언의 값은 var(--토큰) 으로 바꾼다.
177
+ const found = text ?? value;
178
+ const prefixes = utility ? utilityColorPrefixes(utility) : cssColorPrefixes(prop);
179
+ const toCandidate = (name) => (utility ? tokenToClass(utility, name) : tokenVar(name, tokens.prefix));
180
+ const known = tokens.colors.get(normalizeColor(value)) ?? [];
181
+ // 클래스로만 쓸 수 있는 토큰은 선언의 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
182
+ const usable = utility ? known : known.filter((name) => !tokens.classOnly.has(name));
183
+ if (known.length > 0 && usable.length === 0) {
184
+ return {
185
+ file,
186
+ ...location,
187
+ rule: "color-use-token",
188
+ severity: "error",
189
+ messageId: "useTokenClassOnly",
190
+ message: m.useTokenClassOnly({ found, tokens: known.join(", ") }),
191
+ found,
192
+ candidates: [],
193
+ recommended: null,
194
+ };
195
+ }
196
+ const tokenNames = selectColorTokens(usable, tokens.prefer, prefixes);
197
+ const candidates = tokenNames.map(toCandidate);
198
+ const recommendedToken = recommendColorCandidate(tokenNames, prefixes);
129
199
  const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
130
200
  return {
131
201
  file,
@@ -136,7 +206,7 @@ function checkCss(file, source, tokens, m) {
136
206
  severity: "error",
137
207
  messageId,
138
208
  message: m[messageId]({
139
- found: value,
209
+ found,
140
210
  tokens: tokenNames.join(", "),
141
211
  candidates: candidates.join(", "),
142
212
  }),
@@ -144,18 +214,74 @@ function checkCss(file, source, tokens, m) {
144
214
  : {
145
215
  rule: "color-unknown",
146
216
  severity: "warning",
147
- message: m.unknownCssColor({ value }),
217
+ message: utility ? m.unknownColor({ found }) : m.unknownCssColor({ value }),
148
218
  }),
149
- found: value,
219
+ found,
150
220
  candidates,
221
+ recommended: recommendedToken ? toCandidate(recommendedToken) : null,
151
222
  };
152
223
  });
153
224
  }
154
225
 
226
+ function realPath(file) {
227
+ try {
228
+ return fs.realpathSync(file);
229
+ } catch {
230
+ return file; // HEAD 비교처럼 원본 위치에 파일이 없을 수 있다
231
+ }
232
+ }
233
+
155
234
  function actionFor({ rule, severity, candidates }, messageId) {
156
235
  if (rule === "parse-error") return "repair";
157
236
  if (messageId === "useComponentAsk" || messageId === "useTokenThemed") return "ask";
158
- return severity === "error" && candidates.length === 1 ? "replace" : "ask";
237
+ if (severity !== "error" || candidates.length !== 1) return "ask";
238
+ // 컴포넌트는 props 와 기본 스타일이 태그와 다를 수 있어서, 바꿔도 같다고 보장할 수 없다.
239
+ return rule === "use-ds-component" ? "migrate" : "replace";
240
+ }
241
+
242
+ function decisionSubject({ rule, found }) {
243
+ if (rule === "use-ds-component") return `<${found}>`;
244
+ const value = parseColor(found) ? found : findArbitraryColors(found)[0]?.value;
245
+ return value ? colorLabel(value) : found;
246
+ }
247
+
248
+ /**
249
+ * @param {(Violation & { messageId?: string })[]} violations
250
+ * @returns {Decision[]}
251
+ */
252
+ function groupDecisions(violations) {
253
+ /** @type {Map<string, Omit<Decision, "id" | "files" | "reasons"> & { files: Set<string>, reasons: Set<Decision["reasons"][number]> }>} */
254
+ const byQuestion = new Map();
255
+ for (const violation of violations) {
256
+ if (violation.action !== "ask") continue;
257
+ const { rule, candidates, recommended, messageId, file, line, column } = violation;
258
+ const subject = decisionSubject(violation);
259
+ // 역할 때문에 순서만 다른 후보는 같은 질문으로 묶는다.
260
+ const key = JSON.stringify([rule, subject, [...candidates].sort()]);
261
+ let decision = byQuestion.get(key);
262
+ if (!decision) {
263
+ decision = { rule, subject, uses: 0, files: new Set(), locations: [], candidates, recommended, reasons: new Set() };
264
+ byQuestion.set(key, decision);
265
+ }
266
+ decision.uses += 1;
267
+ decision.files.add(file);
268
+ if (decision.locations.length < MAX_DECISION_LOCATIONS) decision.locations.push({ file, line, column });
269
+ if (decision.recommended !== recommended) decision.recommended = null;
270
+ if (candidates.length > 1) decision.reasons.add("multiple-candidates");
271
+ if (rule === "color-unknown") decision.reasons.add("no-token");
272
+ if (messageId === "useTokenThemed") decision.reasons.add("themed-token");
273
+ if (messageId === "useTokenClassOnly") decision.reasons.add("class-only-token");
274
+ if (messageId === "useComponentAsk") decision.reasons.add("dynamic-props");
275
+ }
276
+
277
+ return [...byQuestion.values()]
278
+ .sort((a, b) => b.uses - a.uses)
279
+ .map(({ files, reasons, ...decision }, index) => ({
280
+ id: `decision-${index + 1}`,
281
+ ...decision,
282
+ files: files.size,
283
+ reasons: [...reasons],
284
+ }));
159
285
  }
160
286
 
161
287
  /**
@@ -163,33 +289,39 @@ function actionFor({ rule, severity, candidates }, messageId) {
163
289
  * @param {{ colorTokens: number }} designSystem
164
290
  * @param {Violation[]} violations action 이 붙은 위반들
165
291
  * @param {"en" | "ko"} [lang]
292
+ * @param {Decision[]} [decisions] check 결과의 결정 목록. 훅은 위반만 보여 준다
166
293
  * @returns {string[]}
167
294
  */
168
- export function nextSteps(designSystem, violations, lang) {
295
+ export function nextSteps(designSystem, violations, lang, decisions) {
169
296
  const m = messages(lang);
170
- const noColorTokens = designSystem.colorTokens === 0;
297
+ const noColorTokens = designSystem.colorTokens + (designSystem.paletteColors ?? 0) === 0;
171
298
  // 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
172
299
  const actionable = noColorTokens
173
300
  ? violations.filter((v) => !v.rule.startsWith("color-"))
174
301
  : violations;
175
302
  const count = (action) => actionable.filter((v) => v.action === action).length;
176
- const [repair, replace, ask] = ["repair", "replace", "ask"].map(count);
303
+ const [repair, replace, migrate] = ["repair", "replace", "migrate"].map(count);
304
+ const ask = decisions === undefined
305
+ ? count("ask")
306
+ : decisions.filter((decision) => !noColorTokens || !decision.rule.startsWith("color-")).length;
177
307
  const steps = [];
178
308
 
179
309
  if (noColorTokens) steps.push(m.nextNoTokens());
180
310
  if (repair > 0) steps.push(m.nextRepair(repair));
181
311
  if (replace > 0) steps.push(m.nextReplace(replace));
182
- if (ask > 0) steps.push(m.nextAsk(ask));
183
- if (repair + replace > 0) steps.push(m.nextRerun());
312
+ if (migrate > 0) steps.push(m.nextMigrate(migrate));
313
+ if (ask > 0) steps.push(decisions === undefined ? m.hookNextAsk(ask) : m.nextAsk(ask));
314
+ if (repair + replace + migrate > 0) steps.push(m.nextRerun());
184
315
 
185
316
  return steps.length > 0 ? steps : [m.nextNone()];
186
317
  }
187
318
 
188
319
  function describeDesignSystem(tokens, config) {
189
- const countNames = (map) => new Set([...map.values()].flat()).size;
190
320
  const replaces = Object.values(config.components?.replaces ?? {});
321
+ const names = new Set([...tokens.colors.values()].flat());
191
322
  return {
192
- colorTokens: countNames(tokens.colors),
323
+ colorTokens: [...names].filter((name) => !tokens.paletteNames.has(name)).length,
324
+ paletteColors: tokens.paletteNames.size,
193
325
  components: new Set(replaces.flatMap(replacementNames)).size,
194
326
  replacedTags: replaces.length,
195
327
  };
@@ -216,6 +348,13 @@ function toViolation(file, source, message, config) {
216
348
  candidates = replacementNames(config.components?.replaces?.[found]);
217
349
  }
218
350
 
351
+ let recommended = null;
352
+ const color = rule === "color-use-token" && findArbitraryColors(found)[0];
353
+ if (color) {
354
+ const prefixes = utilityColorPrefixes(color.utility).map((prefix) => tokenToClass(color.utility, prefix));
355
+ recommended = recommendColorCandidate(candidates, prefixes);
356
+ }
357
+
219
358
  return {
220
359
  file,
221
360
  line: message.line,
@@ -228,6 +367,7 @@ function toViolation(file, source, message, config) {
228
367
  messageId: message.messageId,
229
368
  found,
230
369
  candidates,
370
+ recommended,
231
371
  };
232
372
  }
233
373
 
package/src/cli.js CHANGED
@@ -29,8 +29,8 @@ const COMMANDS = {
29
29
  const hasConfig = configPath !== undefined || fs.existsSync(path.resolve(cwd, CONFIG_FILE));
30
30
  const config = hasConfig ? loadConfig(cwd, configPath, resolveLang(flagLang)) : undefined;
31
31
  const lang = resolveLang(flagLang, config?.lang);
32
- const tokens = config ? loadTokens({ designsnitch: { ...config, lang } }, cwd).colors : undefined;
33
- const result = await collectColors({ cwd, paths, tokens });
32
+ const tokens = config ? loadTokens({ designsnitch: { ...config, lang } }, cwd) : undefined;
33
+ const result = await collectColors({ cwd, paths, tokens: tokens?.colors, tokenFiles: tokens?.files });
34
34
  return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
35
35
  },
36
36
 
package/src/colors.js CHANGED
@@ -1,23 +1,21 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { findArbitraryColors, findPaletteClasses } from "./core/classes.js";
4
- import { normalizeHex } from "./core/color.js";
4
+ import { colorLabel, isColorProperty, isNamedColor, parseColor } from "./core/color.js";
5
5
  import { findCssColors } from "./core/css.js";
6
6
  import { createEngine } from "./engine.js";
7
7
  import { splitPaths } from "./files.js";
8
8
  import { visitStrings } from "./rules/visit-strings.js";
9
+ import { inlineStyleProperty } from "./rules/visit-style.js";
9
10
 
10
11
  const RULE_ID = "designsnitch-internal/collect-colors";
11
- const HEX_LITERAL = /^#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})$/i;
12
12
  const MAX_EXAMPLES = 3;
13
13
 
14
- // 알파가 붙은 hex 는 6자리로 펼칠 수 없으니 소문자로만 맞춘다.
15
- const colorKey = (hex) => normalizeHex(hex) ?? hex.toLowerCase();
16
14
 
17
15
  const findColors = (text) => [
18
16
  ...findArbitraryColors(text).map((found) => ({
19
17
  ...found,
20
- payload: { kind: "hex", key: colorKey(found.value), utility: found.utility },
18
+ payload: { kind: "hex", key: colorLabel(found.value), utility: found.utility },
21
19
  })),
22
20
  ...findPaletteClasses(text).map((found) => ({
23
21
  ...found,
@@ -36,9 +34,12 @@ const collectRule = {
36
34
  return {
37
35
  ...visitor,
38
36
  Literal(node) {
39
- // 문자열 전체가 hex 색인 경우. 예: style={{ color: "#3B82F6" }}
40
- if (typeof node.value === "string" && HEX_LITERAL.test(node.value)) {
41
- report(node.loc, { kind: "hex", key: colorKey(node.value), utility: null });
37
+ // 문자열 전체가 색인 경우. 예: style={{ color: "#3B82F6" }}
38
+ // 색 이름은 인라인 스타일의 색 속성에서만 색으로 센다. 다른 곳에서는 그냥 단어일 수 있다.
39
+ const isColor = (value) =>
40
+ parseColor(value) !== null && (!isNamedColor(value) || isColorProperty(inlineStyleProperty(node) ?? ""));
41
+ if (typeof node.value === "string" && isColor(node.value)) {
42
+ report(node.loc, { kind: "hex", key: colorLabel(node.value), utility: null });
42
43
  return;
43
44
  }
44
45
  visitor.Literal(node);
@@ -61,6 +62,7 @@ const collectRule = {
61
62
  * @param {string} options.cwd 프로젝트 디렉터리
62
63
  * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
63
64
  * @param {Map<string, string[]>} [options.tokens] 색 값 → 토큰 이름들. 주면 색마다 tokens 를 붙인다
65
+ * @param {Set<string>} [options.tokenFiles] 토큰을 정의하는 파일들의 절대 경로. CSS 는 변수 선언을, JS 설정은 통째로 건너뛴다
64
66
  * @returns {Promise<{
65
67
  * summary: { files: number, colors: number, paletteColors: number, uses: number },
66
68
  * colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
@@ -68,7 +70,7 @@ const collectRule = {
68
70
  * }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
69
71
  * literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
70
72
  */
71
- export async function collectColors({ cwd, paths = ["."], tokens }) {
73
+ export async function collectColors({ cwd, paths = ["."], tokens, tokenFiles }) {
72
74
  const eslint = createEngine({
73
75
  cwd,
74
76
  // 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
@@ -85,6 +87,8 @@ export async function collectColors({ cwd, paths = ["."], tokens }) {
85
87
  /** @type {{ file: string, line: number, kind: "hex" | "palette", key: string, utility?: string | null, prop?: string }[]} */
86
88
  const uses = [];
87
89
  for (const result of results) {
90
+ // 토큰을 정의하는 파일(tailwind.config.js)의 색은 코드가 쓰는 색이 아니다.
91
+ if (tokenFiles?.has(fs.realpathSync(result.filePath))) continue;
88
92
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
89
93
  for (const message of result.messages) {
90
94
  if (message.ruleId !== RULE_ID) continue;
@@ -92,14 +96,15 @@ export async function collectColors({ cwd, paths = ["."], tokens }) {
92
96
  }
93
97
  }
94
98
  for (const file of cssFiles) {
99
+ const absolute = path.resolve(cwd, file);
95
100
  let found;
96
101
  try {
97
- found = findCssColors(fs.readFileSync(path.resolve(cwd, file), "utf8"));
102
+ found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: tokenFiles?.has(fs.realpathSync(absolute)) ?? false });
98
103
  } catch {
99
104
  continue; // 읽지 못한 CSS 는 건너뛴다
100
105
  }
101
- for (const { line, value, prop } of found) {
102
- uses.push({ file, line, kind: "hex", key: colorKey(value), prop });
106
+ for (const { line, value, prop, utility } of found) {
107
+ uses.push({ file, line, kind: "hex", key: colorLabel(value), prop, utility });
103
108
  }
104
109
  }
105
110
  uses.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
package/src/config.js CHANGED
@@ -13,6 +13,26 @@ const EXAMPLE = `{
13
13
  }`;
14
14
 
15
15
  /** @typedef {string | string[] | { component: string | string[], when?: Record<string, (string | null)[]> }} Replacement */
16
+ /** @typedef {string | { file: string, exclude?: string[], prefer?: string[] }} TokenSettings */
17
+
18
+ /** @param {TokenSettings} tokens */
19
+ export function tokenSettings(tokens) {
20
+ return typeof tokens === "string" ? { file: tokens } : tokens;
21
+ }
22
+
23
+ export function invalidTokenField(tokens) {
24
+ if (typeof tokens === "string") return tokens.length > 0 ? null : "tokens";
25
+ if (!isRecord(tokens)) return "tokens";
26
+ if (typeof tokens.file !== "string" || tokens.file.length === 0) return "tokens.file";
27
+ if (tokens.exclude !== undefined && !isPatternList(tokens.exclude, /^[^*]*\*?$/)) return "tokens.exclude";
28
+ if (tokens.prefer !== undefined && !isPatternList(tokens.prefer, /^[^*]+$/)) return "tokens.prefer";
29
+ return null;
30
+ }
31
+
32
+ function isPatternList(values, pattern) {
33
+ return Array.isArray(values) &&
34
+ values.every((value) => typeof value === "string" && value.length > 0 && pattern.test(value));
35
+ }
16
36
 
17
37
  /** @param {Replacement} [replacement] */
18
38
  export function replacementNames(replacement) {
@@ -27,7 +47,7 @@ export function replacementNames(replacement) {
27
47
  * @param {string} cwd 프로젝트 디렉터리
28
48
  * @param {string} [configPath] cwd 기준 설정 파일 경로
29
49
  * @param {"en" | "ko"} [lang] 오류 문장의 언어
30
- * @returns {{ tokens: string, lang?: "en" | "ko", components?: { path: string, replaces: Record<string, Replacement> } }}
50
+ * @returns {{ tokens: TokenSettings, root: string, lang?: "en" | "ko", components?: { path: string, replaces: Record<string, Replacement> } }}
31
51
  */
32
52
  export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
33
53
  const m = messages(lang);
@@ -47,10 +67,13 @@ export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
47
67
  throw new Error(m.configUnreadable({ file, reason: error.message }));
48
68
  }
49
69
 
50
- if (typeof config?.tokens !== "string") throw new Error(m.configNoTokens({ file }));
70
+ const tokenField = invalidTokenField(config?.tokens);
71
+ if (tokenField === "tokens") throw new Error(m.configNoTokens({ file }));
72
+ if (tokenField) throw new Error(m.invalidTokenSetting({ field: tokenField, file }));
51
73
  if (config.lang !== undefined && !isLang(config.lang)) throw new Error(m.configBadLang({ file }));
74
+ if (config.palette !== undefined && config.palette !== "tailwind") throw new Error(m.configBadPalette({ file }));
52
75
  if (config.components !== undefined) validateComponents(config.components, file, m);
53
- return config;
76
+ return { ...config, root: path.dirname(file) };
54
77
  }
55
78
 
56
79
  function validateComponents(components, file, m) {
@@ -1,19 +1,23 @@
1
- // 예: bg-[#3B82F6], ring-offset-[#fff]
1
+ import { parseColor } from "./color.js";
2
+
3
+ // 예: bg-[#3B82F6], ring-offset-[#fff], text-[rgb(59,130,246)], bg-[oklch(62.3%_0.214_259.815)], bg-[white]
2
4
  const ARBITRARY_COLOR =
3
- /(?<![\w-])([a-z][a-z0-9]*(?:-[a-z0-9]+)*)-\[(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4}))\]/gi;
5
+ /(?<![\w-])([a-z][a-z0-9]*(?:-[a-z0-9]+)*)-\[(#[0-9a-f]{3,8}|(?:rgba?|hsla?|oklch|hwb|lab|lch|oklab|color)\([^()[\]\s]*\)|[a-z]+)\]/gi;
4
6
 
5
7
  /**
6
- * 문자열에서 hex를 임의 값으로 쓴 Tailwind 클래스를 찾는다.
8
+ * 문자열에서 색을 임의 값으로 쓴 Tailwind 클래스를 찾는다.
7
9
  * @param {string} text
8
10
  * @returns {{ index: number, text: string, utility: string, value: string }[]}
9
11
  */
10
12
  export function findArbitraryColors(text) {
11
- return [...text.matchAll(ARBITRARY_COLOR)].map((match) => ({
12
- index: match.index,
13
- text: match[0],
14
- utility: match[1],
15
- value: match[2],
16
- }));
13
+ return [...text.matchAll(ARBITRARY_COLOR)]
14
+ .filter((match) => parseColor(match[2]) !== null)
15
+ .map((match) => ({
16
+ index: match.index,
17
+ text: match[0],
18
+ utility: match[1],
19
+ value: match[2],
20
+ }));
17
21
  }
18
22
 
19
23
  /** 예: ("bg", "--color-primary-500") → "bg-primary-500" */