designsnitch 0.4.0 → 0.6.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.
@@ -11,15 +11,17 @@ A skill is advice: an agent may or may not follow it. A hook is run by the agent
11
11
 
12
12
  ## What the hook does
13
13
 
14
- `npx designsnitch hook` checks only the files the agent just changed, and blocks only errors the change added. It compares each file with its version in git `HEAD`: errors that were already there do not block.
14
+ `npx designsnitch hook` checks only the files the agent just changed, and blocks only errors the change added. It compares each file with its version in git `HEAD`, and with what the working tree looked like when the session started: errors that were already there do not block, committed or not.
15
15
 
16
16
  | When it runs | What happens |
17
17
  | --- | --- |
18
18
  | Right after the agent edits a file | If that file has errors, the agent receives them with what to do next. |
19
- | When the agent is about to finish | If errors the agent can fix itself remain in the changed files, the agent is not allowed to finish. |
19
+ | When the session starts | The errors already in the changed files are noted, so they are not blamed on this session. Nothing is reported. |
20
+ | When the agent is about to finish | If `replace` errors, or files that cannot be parsed, remain in the changed files, the agent is not allowed to finish. |
20
21
 
21
22
  - Warnings never block.
22
23
  - Errors that need a person's decision (`ask`) are reported after an edit, but do not stop the agent from finishing. The agent has to stop in order to ask.
24
+ - Tags to move to a component (`migrate`) are reported after an edit, but do not stop the agent from finishing either. The tool cannot tell whether the component behaves like the tag, so that call is left to the agent and the user.
23
25
  - Files the agent did not touch are left alone. Errors that were already in the files it touched are reported only if the change added more of them.
24
26
 
25
27
  ## 1. Register the hook in Claude Code
@@ -47,6 +49,11 @@ If you need to do it by hand, this is what it adds to `.claude/settings.json`.
47
49
  {
48
50
  "hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
49
51
  }
52
+ ],
53
+ "SessionStart": [
54
+ {
55
+ "hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
56
+ }
50
57
  ]
51
58
  }
52
59
  }
@@ -75,6 +82,11 @@ It adds the hook to `.codex/hooks.json` and copies the skills into `.agents/skil
75
82
  {
76
83
  "hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
77
84
  }
85
+ ],
86
+ "SessionStart": [
87
+ {
88
+ "hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
89
+ }
78
90
  ]
79
91
  }
80
92
  }
@@ -106,6 +118,11 @@ It adds the hook to `.gemini/settings.json` and copies the skills into `.agents/
106
118
  {
107
119
  "hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
108
120
  }
121
+ ],
122
+ "SessionStart": [
123
+ {
124
+ "hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
125
+ }
109
126
  ]
110
127
  }
111
128
  }
@@ -122,7 +139,7 @@ Tell the user that Gemini CLI warns before it runs a new project hook, and that
122
139
  npx designsnitch install --agent grok
123
140
  ```
124
141
 
125
- It writes `.grok/hooks/designsnitch.json` with the same `PostToolUse` and `Stop` hooks as Claude Code (`timeout` in seconds), and copies the skills into `.grok/skills`. Grok Build sends the hook its input in camelCase (`hookEventName`, `toolInput`), which `designsnitch hook` understands.
142
+ It writes `.grok/hooks/designsnitch.json` with the same `PostToolUse` and `Stop` hooks as Claude Code, without `SessionStart`, which the xAI documentation does not confirm (`timeout` in seconds), and copies the skills into `.grok/skills`. Grok Build sends the hook its input in camelCase (`hookEventName`, `toolInput`), which `designsnitch hook` understands.
126
143
 
127
144
  Tell the user two things.
128
145
 
@@ -136,6 +153,7 @@ Tell the user two things.
136
153
  - `tool_input.file_path`: the file that was just edited. Without it, the files that git reports as changed are checked.
137
154
  - `hook_event_name` (or `hookEventName`): `Stop`, `SubagentStop` or `AfterAgent` means the agent is about to finish.
138
155
  - `stop_hook_active`: when true, the hook does not block again.
156
+ - `session_id` (or `sessionId`): lets the hook remember which errors were there before the session. `hook_event_name` `SessionStart` notes them and reports nothing.
139
157
 
140
158
  It exits with 2 and writes what to fix to stderr when it blocks, and exits with 0 otherwise. If the agent in use supports command hooks with these conventions, register the same command there. Check that agent's hook documentation for the file and the event names, and tell the user if you could not confirm that it works.
141
159
 
@@ -69,7 +69,7 @@ Then work out what each color of its own is for. `utilities` and `properties` sh
69
69
  | `bg`, or `background` properties | Background or surface |
70
70
  | A mix, or mostly `literals` | A general color such as a brand or chart color. Open the examples to see. |
71
71
 
72
- For `palette`, note which default palette colors the project relies on. They already work as classes and designsnitch does not flag them. Whether they belong to the design system is the user's call, so include them in the proposal as a question.
72
+ For `palette`, note which default palette colors the project relies on. If they carry most of the color uses, the default palette is the project's standard already. Do not copy palette colors into new hex tokens: that changes nothing on screen and doubles the names. Propose `"palette": "tailwind"` in `designsnitch.config.json` instead, and limit new tokens to colors outside the palette. If the palette is a minor part, whether it belongs to the design system is the user's call, so include it in the proposal as a question.
73
73
 
74
74
  ## 3. Propose
75
75
 
@@ -107,9 +107,9 @@ After the user approves, add the tokens to the CSS file that imports Tailwind (`
107
107
  }
108
108
  ```
109
109
 
110
- Write the values as hex. designsnitch reads hex values and `var()` references to hex values, and nothing else.
110
+ Write the values as hex, the form the code already uses. designsnitch reads hex, `rgb()`, `hsl()` and `oklch()` values, and `var()` references to them.
111
111
 
112
- If the project uses Tailwind v3 (a `tailwind.config.js` and no `@theme`), stop and tell the user: designsnitch does not read v3 config yet.
112
+ If the project uses Tailwind v3 (a `tailwind.config.js` and no `@theme`), there is no `@theme` to write to. Propose the same tokens as entries of `theme.extend.colors` in `tailwind.config.js` instead, and add them after the user approves.
113
113
 
114
114
  ## 5. Point the config at the tokens
115
115
 
@@ -7,14 +7,15 @@ description: Set up designsnitch in a React/Next.js + Tailwind project. Finds th
7
7
 
8
8
  designsnitch needs to know where the project's design system lives. Read the codebase, write that down in `designsnitch.config.json`, and then make the ESLint plugin use it. The CLI and the plugin read the same file.
9
9
 
10
- Only create the file when it is missing. If it already exists and seems wrong, explain why and ask the user before changing it: this file is the standard the code is judged against.
10
+ Create the file when it is missing. This does not need the user's approval: it only records where the existing standard is. If it already exists and seems wrong, explain why and ask the user before changing it: this file is the standard the code is judged against.
11
11
 
12
12
  ## 0. Check that the project is supported, and install the package
13
13
 
14
- designsnitch supports React or Next.js projects that use Tailwind CSS v4. Look at `package.json` and the global CSS file.
14
+ designsnitch supports React or Next.js projects that use Tailwind CSS. Look at `package.json` and the global CSS file.
15
15
 
16
- - Tailwind v4 has `tailwindcss` version 4 in `package.json` and `@import "tailwindcss"` in a CSS file.
17
- - If the project uses Tailwind v3 (a `tailwind.config.js` with a `theme` section and no `@theme` in CSS), or does not use Tailwind or React at all, stop and tell the user that designsnitch does not support it yet.
16
+ - Tailwind v4 has `tailwindcss` version 4 in `package.json` and `@import "tailwindcss"` in a CSS file. This is the full case.
17
+ - Tailwind v3 has `tailwindcss` version 3, `@tailwind base` in a CSS file and its colors in `tailwind.config.js`. It is checked too: point `tokens` at the CSS file, and the `tailwind.config.js` in the same directory as `designsnitch.config.json` is read. Tell the user what is different: v3 has no CSS variables for its colors, so colors written by hand in CSS declarations and inline styles are reported without a candidate, and the `designsnitch-palette` skill, which writes `@theme` tokens, does not apply. New colors go into `tailwind.config.js`, with the user's approval.
18
+ - If the project does not use Tailwind or React at all, stop and tell the user that designsnitch does not support it yet.
18
19
 
19
20
  Then make sure the package is a dependency of the project. The commands below and the agent hook both run `npx designsnitch`, which should use the project's own copy.
20
21
 
@@ -26,9 +27,11 @@ npm install --save-dev designsnitch
26
27
 
27
28
  It is the CSS file with an `@theme` block or `--color-*` variables, usually `app/globals.css` or `src/app/globals.css`. If you cannot tell which CSS file is the right one, ask the user.
28
29
 
29
- designsnitch reads a variable as a color token only when its name starts with `--color-` and its value is a hex color or a `var()` that leads to one. Two cases need a decision before you go on.
30
+ designsnitch reads a variable as a color token only when its name starts with `--color-` and its value is a hex, `rgb()`, `hsl()` or `oklch()` color, or a `var()` that leads to one. It also reads `@theme` tokens from CSS files the token CSS imports, and colors from a JavaScript config the token CSS loads with `@config`. Point `tokens` at the CSS file that imports Tailwind, and the rest is found from there. Some cases need a decision before you go on.
30
31
 
31
- **The project has no color variables at all.** There are no color tokens yet. Follow the `designsnitch-palette` skill to create them from the colors the code already uses, then continue here.
32
+ **The project uses Tailwind's default palette as its colors.** Run `npx designsnitch colors --format json`. If most uses are in `palette` (classes such as `bg-slate-100`) and few are hex colors, the project already has a standard: the default palette. Do not turn palette colors into new hex tokens. Propose `"palette": "tailwind"` in the config instead, which makes the default palette part of the standard and flags hex colors that duplicate it. Tell the user what this means, and add it after they agree. Colors that are not in the palette can still get project tokens through the `designsnitch-palette` skill.
33
+
34
+ **The project has no color variables at all, and does not rely on the default palette.** There are no color tokens yet. Follow the `designsnitch-palette` skill to create them from the colors the code already uses, then continue here.
32
35
 
33
36
  **The project has color variables under other names**, such as `--ink` or `--brand` in `:root`. These are the project's tokens, but designsnitch cannot see them. Do not create a second set of tokens next to them. Propose to the user that the existing variables be exposed as tokens by referencing them from `@theme`:
34
37
 
@@ -94,7 +97,7 @@ npx designsnitch check --format json
94
97
 
95
98
  Look at `designSystem` and `problems` in the result.
96
99
 
97
- - `designSystem.colorTokens` should match the number of `--color-*` tokens in the CSS. A 0 means the path is wrong or the tokens are in a format that cannot be read (only hex values and `var()` references to hex values are read).
100
+ - `designSystem.colorTokens` should match the number of `--color-*` tokens in the CSS. A 0 means the path is wrong or the tokens are in a format that cannot be read (hex, `rgb()`, `hsl()` and `oklch()` values, and `var()` references to them are read). A non-empty `problems` about a Tailwind config means the JavaScript config could not be loaded: its dependencies may not be installed.
98
101
  - `designSystem.components` should match the number of components you listed.
99
102
  - `problems` should be empty.
100
103
  - Exit code 2 with a message about a missing path means a path in the config is wrong.
package/src/check.js CHANGED
@@ -2,19 +2,27 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { replacementNames, tokenSettings } from "./config.js";
4
4
  import { findArbitraryColors, tokenToClass } from "./core/classes.js";
5
- import { normalizeHex } from "./core/color.js";
5
+ import { colorLabel, parseColor } from "./core/color.js";
6
6
  import { findCssColors } from "./core/css.js";
7
- import { cssColorPrefixes, recommendColorCandidate, selectColorTokens, utilityColorPrefixes } from "./core/tokens.js";
7
+ import {
8
+ cssColorPrefixes,
9
+ lookupColor,
10
+ recommendColorCandidate,
11
+ selectColorTokens,
12
+ tokenClass,
13
+ tokenValue,
14
+ utilityColorPrefixes,
15
+ } from "./core/tokens.js";
8
16
  import { createEngine } from "./engine.js";
9
17
  import { splitPaths } from "./files.js";
10
18
  import plugin from "./index.js";
11
19
  import { messages, resolveLang } from "./messages.js";
12
20
  import { loadTokens } from "./rules/load-tokens.js";
13
- import uncheckedHex from "./rules/unchecked-hex.js";
21
+ import uncheckedColors from "./rules/unchecked-colors.js";
14
22
 
15
23
  const RULE_PREFIX = "designsnitch/";
16
- const UNCHECKED_RULE = "designsnitch-internal/unchecked-hex";
17
- const internalPlugin = { rules: { "unchecked-hex": uncheckedHex } };
24
+ const UNCHECKED_RULE = "designsnitch-internal/unchecked-colors";
25
+ const internalPlugin = { rules: { "unchecked-colors": uncheckedColors } };
18
26
  const MAX_DECISION_LOCATIONS = 5;
19
27
 
20
28
  /**
@@ -30,8 +38,9 @@ const MAX_DECISION_LOCATIONS = 5;
30
38
  * @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
31
39
  * @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
32
40
  * @property {string | null} recommended 바로 바꿀 후보 또는 역할에 맞는 유일한 후보
33
- * @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
34
- * replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
41
+ * @property {"replace" | "migrate" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
42
+ * replace: found 를 candidates 의 값으로 바꿔도 화면과 동작이 같다 (후보가 하나뿐인 색 오류)
43
+ * migrate: raw 태그를 하나뿐인 후보 컴포넌트로 옮긴다. 컴포넌트를 읽고 props 와 스타일을 맞춰야 한다
35
44
  * ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
36
45
  * repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
37
46
  */
@@ -46,7 +55,7 @@ const MAX_DECISION_LOCATIONS = 5;
46
55
  * @property {Pick<Violation, "file" | "line" | "column">[]} locations 위반 위치 최대 다섯 곳
47
56
  * @property {string[]} candidates
48
57
  * @property {string | null} recommended 각 위치에서 추천이 같을 때 그 후보
49
- * @property {("multiple-candidates" | "no-token" | "themed-token" | "dynamic-props")[]} reasons
58
+ * @property {("multiple-candidates" | "no-token" | "themed-token" | "class-only-token" | "translucent" | "not-a-style" | "dynamic-props")[]} reasons
50
59
  */
51
60
 
52
61
  /**
@@ -82,8 +91,8 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
82
91
  }
83
92
  }
84
93
  const designSystem = describeDesignSystem(tokens, config);
85
- const problems = [];
86
- if (designSystem.colorTokens === 0) {
94
+ const problems = [...tokens.problems];
95
+ if (designSystem.colorTokens + designSystem.paletteColors === 0) {
87
96
  problems.push(m.noColorTokens({ tokens: tokenSettings(config.tokens).file }));
88
97
  }
89
98
 
@@ -100,21 +109,22 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
100
109
  },
101
110
  });
102
111
  const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
103
- // 검사하지 못한 hex 색은 위반이 아니라 개수로만 알린다. 놓친 것이 있다는 사실을 숨기지 않기 위해서다.
112
+ // 검사하지 못한 색은 위반이 아니라 개수로만 알린다. 놓친 것이 있다는 사실을 숨기지 않기 위해서다.
104
113
  const uncheckedFiles = results
114
+ // 토큰을 정의하는 파일(tailwind.config.js)의 색은 놓친 색이 아니다.
115
+ .filter((result) => !tokens.files.has(realPath(result.filePath)))
105
116
  .map((result) => result.messages.filter((message) => message.ruleId === UNCHECKED_RULE).length)
106
117
  .filter((n) => n > 0);
107
- const unchecked = { hexColors: uncheckedFiles.reduce((a, b) => a + b, 0), files: uncheckedFiles.length };
118
+ const unchecked = { colors: uncheckedFiles.reduce((a, b) => a + b, 0), files: uncheckedFiles.length };
108
119
  const scriptViolations = results.flatMap((result) => {
109
120
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
110
121
  return result.messages
111
122
  .filter(isOurs)
112
123
  .map((message) => toViolation(file, result.source, message, config));
113
124
  });
114
- const tokenFile = path.resolve(root, tokenSettings(config.tokens).file);
115
125
  const cssViolations = cssFiles.flatMap((file) => {
116
126
  const source = fs.readFileSync(path.resolve(cwd, file), "utf8");
117
- const skipCustomProperties = path.resolve(sourceCwd, file) === tokenFile;
127
+ const skipCustomProperties = tokens.files.has(realPath(path.resolve(sourceCwd, file)));
118
128
  return checkCss(file, source, tokens, m, { skipCustomProperties });
119
129
  });
120
130
 
@@ -122,7 +132,7 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
122
132
  .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
123
133
  .map((finding) => {
124
134
  const action = actionFor(finding, finding.messageId);
125
- const recommended = action === "replace" ? finding.candidates[0] : finding.recommended ?? null;
135
+ const recommended = action === "replace" || action === "migrate" ? finding.candidates[0] : finding.recommended ?? null;
126
136
  return { ...finding, action, recommended };
127
137
  });
128
138
  const violations = findings.map(({ messageId, ...violation }) => violation);
@@ -144,7 +154,7 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
144
154
  }
145
155
 
146
156
  /**
147
- * CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
157
+ * CSS 파일 하나의 색을 토큰과 비교한다. 대체 후보는 선언에서는 var(--토큰), @apply 에서는 토큰 클래스다.
148
158
  * @returns {(Omit<Violation, "action" | "recommended"> & { recommended?: string | null, messageId?: string })[]}
149
159
  */
150
160
  function checkCss(file, source, tokens, m, options) {
@@ -170,12 +180,33 @@ function checkCss(file, source, tokens, m, options) {
170
180
 
171
181
  return colors
172
182
  .filter((color) => !color.disabled)
173
- .map(({ value, prop, disabled, ...location }) => {
174
- const prefixes = cssColorPrefixes(prop);
175
- const tokenNames = selectColorTokens(tokens.colors.get(normalizeHex(value)) ?? [], tokens.prefer, prefixes);
176
- const candidates = tokenNames.map((name) => `var(${name})`);
183
+ .map(({ value, prop, utility, text, disabled, ...location }) => {
184
+ // @apply 의 클래스는 JS 의 클래스처럼 토큰 클래스로, 선언의 값은 var(--토큰) 으로 바꾼다.
185
+ const found = text ?? value;
186
+ const prefixes = utility ? utilityColorPrefixes(utility) : cssColorPrefixes(prop);
187
+ const { names: known, opacity } = lookupColor(tokens.colors, value);
188
+ const toCandidate = (name) =>
189
+ utility ? tokenClass(utility, name, opacity) : tokenValue(name, tokens.prefix, opacity);
190
+ // 클래스로만 쓸 수 있는 토큰은 선언의 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
191
+ const usable = utility ? known : known.filter((name) => !tokens.classOnly.has(name));
192
+ if (known.length > 0 && usable.length === 0) {
193
+ return {
194
+ file,
195
+ ...location,
196
+ rule: "color-use-token",
197
+ severity: "error",
198
+ messageId: "useTokenClassOnly",
199
+ message: m.useTokenClassOnly({ found, tokens: known.join(", ") }),
200
+ found,
201
+ candidates: [],
202
+ recommended: null,
203
+ };
204
+ }
205
+ const tokenNames = selectColorTokens(usable, tokens.prefer, prefixes);
206
+ const candidates = tokenNames.map(toCandidate);
177
207
  const recommendedToken = recommendColorCandidate(tokenNames, prefixes);
178
- const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
208
+ const messageId =
209
+ opacity !== null ? "useTokenAlpha" : tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
179
210
  return {
180
211
  file,
181
212
  ...location,
@@ -185,35 +216,46 @@ function checkCss(file, source, tokens, m, options) {
185
216
  severity: "error",
186
217
  messageId,
187
218
  message: m[messageId]({
188
- found: value,
219
+ found,
189
220
  tokens: tokenNames.join(", "),
190
221
  candidates: candidates.join(", "),
222
+ opacity,
191
223
  }),
192
224
  }
193
225
  : {
194
226
  rule: "color-unknown",
195
227
  severity: "warning",
196
- message: m.unknownCssColor({ value }),
228
+ message: utility ? m.unknownColor({ found }) : m.unknownCssColor({ value }),
197
229
  }),
198
- found: value,
230
+ found,
199
231
  candidates,
200
- recommended: recommendedToken ? `var(${recommendedToken})` : null,
232
+ recommended: recommendedToken ? toCandidate(recommendedToken) : null,
201
233
  };
202
234
  });
203
235
  }
204
236
 
237
+ function realPath(file) {
238
+ try {
239
+ return fs.realpathSync(file);
240
+ } catch {
241
+ return file; // HEAD 비교처럼 원본 위치에 파일이 없을 수 있다
242
+ }
243
+ }
244
+
205
245
  function actionFor({ rule, severity, candidates }, messageId) {
206
246
  if (rule === "parse-error") return "repair";
207
- if (messageId === "useComponentAsk" || messageId === "useTokenThemed") return "ask";
208
- return severity === "error" && candidates.length === 1 ? "replace" : "ask";
247
+ // 반투명한 색은 불투명도를 반올림해 후보를 내므로, 바꿔도 같은 색이라고 보장할 수 없다.
248
+ // 스타일이 아닌 자리의 색은 var() 가 통하는지 알 수 없다.
249
+ if (["useComponentAsk", "useTokenThemed", "useTokenAlpha", "useTokenData"].includes(messageId)) return "ask";
250
+ if (severity !== "error" || candidates.length !== 1) return "ask";
251
+ // 컴포넌트는 props 와 기본 스타일이 태그와 다를 수 있어서, 바꿔도 같다고 보장할 수 없다.
252
+ return rule === "use-ds-component" ? "migrate" : "replace";
209
253
  }
210
254
 
211
255
  function decisionSubject({ rule, found }) {
212
256
  if (rule === "use-ds-component") return `<${found}>`;
213
- const value = found.startsWith("#") ? found : findArbitraryColors(found)[0]?.value;
214
- if (!value) return found;
215
- const hex = value.toLowerCase();
216
- return normalizeHex(hex) ?? (hex.length === 5 ? hex.replace(/[0-9a-f]/g, "$&$&") : hex);
257
+ const value = parseColor(found) ? found : findArbitraryColors(found)[0]?.value;
258
+ return value ? colorLabel(value) : found;
217
259
  }
218
260
 
219
261
  /**
@@ -241,6 +283,9 @@ function groupDecisions(violations) {
241
283
  if (candidates.length > 1) decision.reasons.add("multiple-candidates");
242
284
  if (rule === "color-unknown") decision.reasons.add("no-token");
243
285
  if (messageId === "useTokenThemed") decision.reasons.add("themed-token");
286
+ if (messageId === "useTokenClassOnly") decision.reasons.add("class-only-token");
287
+ if (messageId === "useTokenAlpha") decision.reasons.add("translucent");
288
+ if (messageId === "useTokenData") decision.reasons.add("not-a-style");
244
289
  if (messageId === "useComponentAsk") decision.reasons.add("dynamic-props");
245
290
  }
246
291
 
@@ -264,13 +309,13 @@ function groupDecisions(violations) {
264
309
  */
265
310
  export function nextSteps(designSystem, violations, lang, decisions) {
266
311
  const m = messages(lang);
267
- const noColorTokens = designSystem.colorTokens === 0;
312
+ const noColorTokens = designSystem.colorTokens + (designSystem.paletteColors ?? 0) === 0;
268
313
  // 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
269
314
  const actionable = noColorTokens
270
315
  ? violations.filter((v) => !v.rule.startsWith("color-"))
271
316
  : violations;
272
317
  const count = (action) => actionable.filter((v) => v.action === action).length;
273
- const [repair, replace] = ["repair", "replace"].map(count);
318
+ const [repair, replace, migrate] = ["repair", "replace", "migrate"].map(count);
274
319
  const ask = decisions === undefined
275
320
  ? count("ask")
276
321
  : decisions.filter((decision) => !noColorTokens || !decision.rule.startsWith("color-")).length;
@@ -279,17 +324,19 @@ export function nextSteps(designSystem, violations, lang, decisions) {
279
324
  if (noColorTokens) steps.push(m.nextNoTokens());
280
325
  if (repair > 0) steps.push(m.nextRepair(repair));
281
326
  if (replace > 0) steps.push(m.nextReplace(replace));
327
+ if (migrate > 0) steps.push(m.nextMigrate(migrate));
282
328
  if (ask > 0) steps.push(decisions === undefined ? m.hookNextAsk(ask) : m.nextAsk(ask));
283
- if (repair + replace > 0) steps.push(m.nextRerun());
329
+ if (repair + replace + migrate > 0) steps.push(m.nextRerun());
284
330
 
285
331
  return steps.length > 0 ? steps : [m.nextNone()];
286
332
  }
287
333
 
288
334
  function describeDesignSystem(tokens, config) {
289
- const countNames = (map) => new Set([...map.values()].flat()).size;
290
335
  const replaces = Object.values(config.components?.replaces ?? {});
336
+ const names = new Set([...tokens.colors.values()].flat());
291
337
  return {
292
- colorTokens: countNames(tokens.colors),
338
+ colorTokens: [...names].filter((name) => !tokens.paletteNames.has(name)).length,
339
+ paletteColors: tokens.paletteNames.size,
293
340
  components: new Set(replaces.flatMap(replacementNames)).size,
294
341
  replacedTags: replaces.length,
295
342
  };
package/src/cli.js CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { check } from "./check.js";
5
5
  import { collectColors } from "./colors.js";
6
- import { CONFIG_FILE, loadConfig, tokenSettings } from "./config.js";
6
+ import { CONFIG_FILE, loadConfig } from "./config.js";
7
7
  import { formatColorsText, formatText } from "./format.js";
8
8
  import { runHook } from "./hook.js";
9
9
  import { AGENT_CHOICES, install } from "./install.js";
@@ -29,9 +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 tokenFile = config ? path.resolve(config.root, tokenSettings(config.tokens).file) : undefined;
34
- const result = await collectColors({ cwd, paths, tokens, tokenFile });
32
+ const tokens = config ? loadTokens({ designsnitch: { ...config, lang } }, cwd) : undefined;
33
+ const result = await collectColors({ cwd, paths, tokens: tokens?.colors, tokenFiles: tokens?.files });
35
34
  return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
36
35
  },
37
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,7 +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 를 붙인다
64
- * @param {string} [options.tokenFile] 사용자 정의 속성 선언을 건너뛸 토큰 CSS 의 절대 경로
65
+ * @param {Set<string>} [options.tokenFiles] 토큰을 정의하는 파일들의 절대 경로. CSS 는 변수 선언을, JS 설정은 통째로 건너뛴다
65
66
  * @returns {Promise<{
66
67
  * summary: { files: number, colors: number, paletteColors: number, uses: number },
67
68
  * colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
@@ -69,7 +70,7 @@ const collectRule = {
69
70
  * }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
70
71
  * literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
71
72
  */
72
- export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
73
+ export async function collectColors({ cwd, paths = ["."], tokens, tokenFiles }) {
73
74
  const eslint = createEngine({
74
75
  cwd,
75
76
  // 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
@@ -86,6 +87,8 @@ export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
86
87
  /** @type {{ file: string, line: number, kind: "hex" | "palette", key: string, utility?: string | null, prop?: string }[]} */
87
88
  const uses = [];
88
89
  for (const result of results) {
90
+ // 토큰을 정의하는 파일(tailwind.config.js)의 색은 코드가 쓰는 색이 아니다.
91
+ if (tokenFiles?.has(fs.realpathSync(result.filePath))) continue;
89
92
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
90
93
  for (const message of result.messages) {
91
94
  if (message.ruleId !== RULE_ID) continue;
@@ -96,12 +99,12 @@ export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
96
99
  const absolute = path.resolve(cwd, file);
97
100
  let found;
98
101
  try {
99
- found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: absolute === tokenFile });
102
+ found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: tokenFiles?.has(fs.realpathSync(absolute)) ?? false });
100
103
  } catch {
101
104
  continue; // 읽지 못한 CSS 는 건너뛴다
102
105
  }
103
- for (const { line, value, prop } of found) {
104
- 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 });
105
108
  }
106
109
  }
107
110
  uses.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
package/src/config.js CHANGED
@@ -71,6 +71,7 @@ export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
71
71
  if (tokenField === "tokens") throw new Error(m.configNoTokens({ file }));
72
72
  if (tokenField) throw new Error(m.invalidTokenSetting({ field: tokenField, file }));
73
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 }));
74
75
  if (config.components !== undefined) validateComponents(config.components, file, m);
75
76
  return { ...config, root: path.dirname(file) };
76
77
  }
@@ -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" */
@@ -44,15 +48,3 @@ export function findPaletteClasses(text) {
44
48
  name: match[2],
45
49
  }));
46
50
  }
47
-
48
- // 예: "#3B82F6", "1px solid #fff". bg-[#fff] 의 hex 도 걸리므로 클래스 검사와 겹치지 않게 쓴다.
49
- const HEX_COLOR = /(?<![\w&#])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
50
-
51
- /**
52
- * 문자열에서 hex 색 자체를 찾는다.
53
- * @param {string} text
54
- * @returns {{ index: number, text: string, value: string }[]}
55
- */
56
- export function findHexColors(text) {
57
- return [...text.matchAll(HEX_COLOR)].map((match) => ({ index: match.index, text: match[0], value: match[0] }));
58
- }