designsnitch 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +471 -0
- package/README.md +335 -244
- package/bin/designsnitch.js +73 -13
- package/package.json +4 -4
- package/skills/designsnitch-check/SKILL.md +107 -0
- package/skills/designsnitch-eslint/SKILL.md +128 -0
- package/skills/designsnitch-hooks/SKILL.md +165 -0
- package/skills/designsnitch-palette/SKILL.md +140 -0
- package/skills/designsnitch-setup/SKILL.md +115 -0
- package/src/check.js +128 -42
- package/src/cli.js +66 -25
- package/src/colors.js +166 -0
- package/src/config.js +39 -22
- package/src/core/classes.js +14 -10
- package/src/core/css.js +54 -0
- package/src/core/tokens.js +27 -51
- package/src/engine.js +37 -0
- package/src/files.js +46 -0
- package/src/format.js +44 -19
- package/src/hook.js +163 -0
- package/src/index.js +4 -7
- package/src/install.js +153 -0
- package/src/messages.js +275 -0
- package/src/rules/color-unknown.js +17 -6
- package/src/rules/color-use-token.js +23 -12
- package/src/rules/load-tokens.js +25 -19
- package/src/rules/suggest.js +12 -4
- package/src/rules/use-ds-component.js +34 -10
- package/skills/designsnitch/SKILL.md +0 -107
- package/src/core/scale.js +0 -71
- package/src/rules/scale-labels.js +0 -6
- package/src/rules/scale-unknown.js +0 -43
- package/src/rules/scale-use-token.js +0 -38
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: designsnitch-setup
|
|
3
|
+
description: Set up designsnitch in a React/Next.js + Tailwind project. Finds the token CSS and the shared component directory in the codebase, writes designsnitch.config.json, and wires the rules into ESLint. Use when `designsnitch check` reports that the config file is missing, or when the user asks to set up designsnitch in a project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# designsnitch-setup
|
|
7
|
+
|
|
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
|
+
|
|
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.
|
|
11
|
+
|
|
12
|
+
## 0. Check that the project is supported, and install the package
|
|
13
|
+
|
|
14
|
+
designsnitch supports React or Next.js projects that use Tailwind CSS v4. Look at `package.json` and the global CSS file.
|
|
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.
|
|
18
|
+
|
|
19
|
+
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
|
+
```sh
|
|
22
|
+
npm install --save-dev designsnitch
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## 1. Find the token CSS
|
|
26
|
+
|
|
27
|
+
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
|
+
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
|
+
|
|
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
|
+
|
|
33
|
+
**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
|
+
|
|
35
|
+
```css
|
|
36
|
+
@theme {
|
|
37
|
+
--color-ink: var(--ink);
|
|
38
|
+
--color-brand: var(--brand);
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Tell the user what this changes: the values stay where they are, Tailwind gains classes such as `text-ink` and `bg-brand`, and designsnitch can then tell when code writes those colors by hand. This edits the token CSS, so make the change only after the user agrees.
|
|
43
|
+
|
|
44
|
+
## 2. Find the shared component directory
|
|
45
|
+
|
|
46
|
+
It is where basic UI components such as buttons and inputs live, usually `components/ui`.
|
|
47
|
+
|
|
48
|
+
If the project has no such directory, leave `components` out of the config. The component check is then skipped.
|
|
49
|
+
|
|
50
|
+
## 3. List the raw tags each component replaces
|
|
51
|
+
|
|
52
|
+
Read the files in that directory and find the components whose root element is a raw tag such as `button`, `input`, `select`, `textarea` or `dialog`. Use the exported component names. If several components replace the same tag, list them all.
|
|
53
|
+
|
|
54
|
+
Leave out components that only happen to contain a raw tag deep inside, such as a modal that has a close button. List the components a developer should reach for instead of writing the tag.
|
|
55
|
+
|
|
56
|
+
Check which variants of the tag each component covers. An `Input` built for text fields does not replace `<input type="file">`, `<input type="range">` or a checkbox. When a component covers only some variants, write it with `when`, listing the attribute values it covers (`null` means the attribute is absent). Read the component's props and its root element to decide. If you cannot tell, leave `when` out and tell the user which variants you were unsure about.
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
"input": { "component": "Input", "when": { "type": ["text", "email", "password", null] } }
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## 4. Write the file
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
{
|
|
66
|
+
"tokens": "./src/app/globals.css",
|
|
67
|
+
"components": {
|
|
68
|
+
"path": "./src/components/ui",
|
|
69
|
+
"replaces": {
|
|
70
|
+
"button": ["SolidButton", "GlassButton", "IconButton"],
|
|
71
|
+
"input": { "component": "Input", "when": { "type": ["text", "email", "password", null] } }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Paths are relative to the project root.
|
|
78
|
+
|
|
79
|
+
Messages are in English by default. If the user works in Korean, add `"lang": "ko"` to the file so that the CLI, the ESLint plugin and the hook speak Korean.
|
|
80
|
+
|
|
81
|
+
## 5. Verify
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
npx designsnitch check --format json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Look at `designSystem` and `problems` in the result.
|
|
88
|
+
|
|
89
|
+
- `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).
|
|
90
|
+
- `designSystem.components` should match the number of components you listed.
|
|
91
|
+
- `problems` should be empty.
|
|
92
|
+
- Exit code 2 with a message about a missing path means a path in the config is wrong.
|
|
93
|
+
|
|
94
|
+
Fix the config until these hold. Ignore the violations for now: fixing them is the job of the `designsnitch-check` skill.
|
|
95
|
+
|
|
96
|
+
## 6. Wire the ESLint plugin
|
|
97
|
+
|
|
98
|
+
Follow the `designsnitch-eslint` skill now. It puts the rules into the project's ESLint, and installs ESLint if the project has none. Setup is not finished until this is done: the config file alone does not block anything.
|
|
99
|
+
|
|
100
|
+
## 7. Register the agent hook
|
|
101
|
+
|
|
102
|
+
Follow the `designsnitch-hooks` skill. The hook tells the coding agent about errors right after it edits a file, and keeps it from finishing while errors it can fix remain. The ESLint plugin blocks at lint time. The hook blocks while the code is being written.
|
|
103
|
+
|
|
104
|
+
## 8. Show the user
|
|
105
|
+
|
|
106
|
+
Show the config file and say which CSS file and directory you chose, and why. Give the counts from `designSystem`, the number of errors and warnings the first check found, and what was added to ESLint and to the agent's hooks.
|
|
107
|
+
|
|
108
|
+
If you were unsure about a choice, say so and give the alternative. For example, if two directories both look like the shared component directory, name both and say why you picked one.
|
|
109
|
+
|
|
110
|
+
## What not to do
|
|
111
|
+
|
|
112
|
+
- Do not guess paths or component names you could not find in the repository.
|
|
113
|
+
- Do not edit the token CSS without the user's agreement.
|
|
114
|
+
- Do not change an existing config file without asking.
|
|
115
|
+
- Do not start fixing violations as part of setup.
|
package/src/check.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
3
|
+
import { replacementNames } from "./config.js";
|
|
4
|
+
import { normalizeHex } from "./core/color.js";
|
|
5
|
+
import { findCssColors } from "./core/css.js";
|
|
6
|
+
import { createEngine } from "./engine.js";
|
|
7
|
+
import { splitPaths } from "./files.js";
|
|
5
8
|
import plugin from "./index.js";
|
|
9
|
+
import { messages, resolveLang } from "./messages.js";
|
|
6
10
|
import { loadTokens } from "./rules/load-tokens.js";
|
|
7
11
|
|
|
8
|
-
const FILES = ["**/*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}"];
|
|
9
|
-
const IGNORES = ["**/.next/**", "**/dist/**", "**/build/**", "**/out/**", "**/coverage/**"];
|
|
10
12
|
const RULE_PREFIX = "designsnitch/";
|
|
11
13
|
|
|
12
14
|
/**
|
|
@@ -21,6 +23,10 @@ const RULE_PREFIX = "designsnitch/";
|
|
|
21
23
|
* @property {string} message
|
|
22
24
|
* @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
|
|
23
25
|
* @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
|
|
26
|
+
* @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
|
|
27
|
+
* replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
|
|
28
|
+
* ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
|
|
29
|
+
* repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
|
|
24
30
|
*/
|
|
25
31
|
|
|
26
32
|
/**
|
|
@@ -29,68 +35,60 @@ const RULE_PREFIX = "designsnitch/";
|
|
|
29
35
|
* @param {string} options.cwd 프로젝트 디렉터리
|
|
30
36
|
* @param {ReturnType<typeof import("./config.js").loadConfig>} options.config
|
|
31
37
|
* @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
|
|
38
|
+
* @param {"en" | "ko"} [options.lang] 문장의 언어. 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
|
|
32
39
|
* @returns {Promise<{
|
|
33
|
-
* designSystem: { colorTokens: number,
|
|
40
|
+
* designSystem: { colorTokens: number, components: number, replacedTags: number },
|
|
34
41
|
* problems: string[],
|
|
42
|
+
* next: string[],
|
|
35
43
|
* summary: { files: number, errors: number, warnings: number },
|
|
36
44
|
* violations: Violation[],
|
|
37
|
-
* }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정
|
|
45
|
+
* }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제,
|
|
46
|
+
* next 는 이 결과를 받은 에이전트가 순서대로 할 일
|
|
38
47
|
*/
|
|
39
|
-
export async function check({ cwd, config, paths = ["."] }) {
|
|
40
|
-
|
|
48
|
+
export async function check({ cwd, config, paths = ["."], lang }) {
|
|
49
|
+
lang = resolveLang(lang, config.lang);
|
|
50
|
+
const m = messages(lang);
|
|
51
|
+
// 규칙도 같은 언어를 쓰도록 설정에 실어 보낸다.
|
|
52
|
+
const settings = { designsnitch: { ...config, lang } };
|
|
41
53
|
// 설정에 문제가 있으면 파일을 검사하기 전에 알린다.
|
|
42
54
|
const tokens = loadTokens(settings, cwd);
|
|
43
55
|
if (config.components) {
|
|
44
56
|
const dir = path.resolve(cwd, config.components.path);
|
|
45
57
|
if (!fs.existsSync(dir)) {
|
|
46
|
-
throw new Error(
|
|
58
|
+
throw new Error(m.componentsDirMissing({ dir }));
|
|
47
59
|
}
|
|
48
60
|
}
|
|
49
61
|
const designSystem = describeDesignSystem(tokens, config);
|
|
50
62
|
const problems = [];
|
|
51
63
|
if (designSystem.colorTokens === 0) {
|
|
52
|
-
problems.push(
|
|
53
|
-
`색 토큰을 하나도 읽지 못했습니다: ${config.tokens}. ` +
|
|
54
|
-
"--color-* 변수의 값이 hex이거나 var()로 hex를 가리켜야 읽을 수 있습니다. " +
|
|
55
|
-
'지금은 모든 hex가 "토큰에 없음" 경고로 나옵니다.',
|
|
56
|
-
);
|
|
64
|
+
problems.push(m.noColorTokens({ tokens: config.tokens }));
|
|
57
65
|
}
|
|
58
66
|
|
|
59
|
-
const
|
|
60
|
-
cwd,
|
|
61
|
-
overrideConfigFile: true,
|
|
62
|
-
errorOnUnmatchedPattern: false,
|
|
63
|
-
overrideConfig: [
|
|
64
|
-
{ ignores: IGNORES },
|
|
65
|
-
{
|
|
66
|
-
...plugin.configs.recommended,
|
|
67
|
-
files: FILES,
|
|
68
|
-
languageOptions: {
|
|
69
|
-
parser: tsParser,
|
|
70
|
-
parserOptions: { ecmaFeatures: { jsx: true } },
|
|
71
|
-
},
|
|
72
|
-
// 프로젝트 코드에는 다른 규칙용 eslint-disable 주석이 있을 수 있다.
|
|
73
|
-
linterOptions: { reportUnusedDisableDirectives: "off" },
|
|
74
|
-
settings,
|
|
75
|
-
},
|
|
76
|
-
],
|
|
77
|
-
});
|
|
67
|
+
const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
|
|
78
68
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
69
|
+
// JS, TS 는 ESLint 로 규칙을 실행하고, CSS 는 직접 읽는다.
|
|
70
|
+
const eslint = createEngine({ cwd, config: { ...plugin.configs.recommended, settings } });
|
|
71
|
+
const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
|
|
72
|
+
const scriptViolations = results.flatMap((result) => {
|
|
83
73
|
const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
|
|
84
74
|
return result.messages
|
|
85
75
|
.filter(isOurs)
|
|
86
76
|
.map((message) => toViolation(file, result.source, message, config));
|
|
87
77
|
});
|
|
78
|
+
const cssViolations = cssFiles.flatMap((file) =>
|
|
79
|
+
checkCss(file, fs.readFileSync(path.resolve(cwd, file), "utf8"), tokens, m),
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
const violations = [...scriptViolations, ...cssViolations]
|
|
83
|
+
.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) }));
|
|
88
85
|
|
|
89
86
|
return {
|
|
90
87
|
designSystem,
|
|
91
88
|
problems,
|
|
89
|
+
next: nextSteps(designSystem, violations, lang),
|
|
92
90
|
summary: {
|
|
93
|
-
files: results.length,
|
|
91
|
+
files: results.length + cssFiles.length,
|
|
94
92
|
errors: violations.filter((v) => v.severity === "error").length,
|
|
95
93
|
warnings: violations.filter((v) => v.severity === "warning").length,
|
|
96
94
|
},
|
|
@@ -98,14 +96,101 @@ export async function check({ cwd, config, paths = ["."] }) {
|
|
|
98
96
|
};
|
|
99
97
|
}
|
|
100
98
|
|
|
99
|
+
/**
|
|
100
|
+
* CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
|
|
101
|
+
* @returns {(Omit<Violation, "action"> & { messageId?: string })[]}
|
|
102
|
+
*/
|
|
103
|
+
function checkCss(file, source, tokens, m) {
|
|
104
|
+
let colors;
|
|
105
|
+
try {
|
|
106
|
+
colors = findCssColors(source);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
const at = { line: error.line ?? 1, column: error.column ?? 1 };
|
|
109
|
+
return [
|
|
110
|
+
{
|
|
111
|
+
file,
|
|
112
|
+
...at,
|
|
113
|
+
endLine: at.line,
|
|
114
|
+
endColumn: at.column,
|
|
115
|
+
rule: "parse-error",
|
|
116
|
+
severity: "error",
|
|
117
|
+
message: error.reason ?? error.message,
|
|
118
|
+
found: "",
|
|
119
|
+
candidates: [],
|
|
120
|
+
},
|
|
121
|
+
];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return colors
|
|
125
|
+
.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})`);
|
|
129
|
+
const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
130
|
+
return {
|
|
131
|
+
file,
|
|
132
|
+
...location,
|
|
133
|
+
...(tokenNames.length > 0
|
|
134
|
+
? {
|
|
135
|
+
rule: "color-use-token",
|
|
136
|
+
severity: "error",
|
|
137
|
+
messageId,
|
|
138
|
+
message: m[messageId]({
|
|
139
|
+
found: value,
|
|
140
|
+
tokens: tokenNames.join(", "),
|
|
141
|
+
candidates: candidates.join(", "),
|
|
142
|
+
}),
|
|
143
|
+
}
|
|
144
|
+
: {
|
|
145
|
+
rule: "color-unknown",
|
|
146
|
+
severity: "warning",
|
|
147
|
+
message: m.unknownCssColor({ value }),
|
|
148
|
+
}),
|
|
149
|
+
found: value,
|
|
150
|
+
candidates,
|
|
151
|
+
};
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function actionFor({ rule, severity, candidates }, messageId) {
|
|
156
|
+
if (rule === "parse-error") return "repair";
|
|
157
|
+
if (messageId === "useComponentAsk" || messageId === "useTokenThemed") return "ask";
|
|
158
|
+
return severity === "error" && candidates.length === 1 ? "replace" : "ask";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 결과를 받은 에이전트가 무엇부터 해야 하는지를 순서대로 적는다.
|
|
163
|
+
* @param {{ colorTokens: number }} designSystem
|
|
164
|
+
* @param {Violation[]} violations action 이 붙은 위반들
|
|
165
|
+
* @param {"en" | "ko"} [lang]
|
|
166
|
+
* @returns {string[]}
|
|
167
|
+
*/
|
|
168
|
+
export function nextSteps(designSystem, violations, lang) {
|
|
169
|
+
const m = messages(lang);
|
|
170
|
+
const noColorTokens = designSystem.colorTokens === 0;
|
|
171
|
+
// 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
|
|
172
|
+
const actionable = noColorTokens
|
|
173
|
+
? violations.filter((v) => !v.rule.startsWith("color-"))
|
|
174
|
+
: violations;
|
|
175
|
+
const count = (action) => actionable.filter((v) => v.action === action).length;
|
|
176
|
+
const [repair, replace, ask] = ["repair", "replace", "ask"].map(count);
|
|
177
|
+
const steps = [];
|
|
178
|
+
|
|
179
|
+
if (noColorTokens) steps.push(m.nextNoTokens());
|
|
180
|
+
if (repair > 0) steps.push(m.nextRepair(repair));
|
|
181
|
+
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());
|
|
184
|
+
|
|
185
|
+
return steps.length > 0 ? steps : [m.nextNone()];
|
|
186
|
+
}
|
|
187
|
+
|
|
101
188
|
function describeDesignSystem(tokens, config) {
|
|
102
189
|
const countNames = (map) => new Set([...map.values()].flat()).size;
|
|
103
190
|
const replaces = Object.values(config.components?.replaces ?? {});
|
|
104
191
|
return {
|
|
105
192
|
colorTokens: countNames(tokens.colors),
|
|
106
|
-
|
|
107
|
-
textTokens: countNames(tokens.scale.text),
|
|
108
|
-
components: new Set(replaces.flat()).size,
|
|
193
|
+
components: new Set(replaces.flatMap(replacementNames)).size,
|
|
109
194
|
replacedTags: replaces.length,
|
|
110
195
|
};
|
|
111
196
|
}
|
|
@@ -128,7 +213,7 @@ function toViolation(file, source, message, config) {
|
|
|
128
213
|
let candidates = (message.suggestions ?? []).map((suggestion) => suggestion.fix.text);
|
|
129
214
|
if (rule === "use-ds-component") {
|
|
130
215
|
// 컴포넌트는 import 까지 바꿔야 해서 제안(자동 교체)이 없다. 설정에서 후보를 찾는다.
|
|
131
|
-
candidates =
|
|
216
|
+
candidates = replacementNames(config.components?.replaces?.[found]);
|
|
132
217
|
}
|
|
133
218
|
|
|
134
219
|
return {
|
|
@@ -140,6 +225,7 @@ function toViolation(file, source, message, config) {
|
|
|
140
225
|
rule,
|
|
141
226
|
severity: message.severity === 2 ? "error" : "warning",
|
|
142
227
|
message: message.message,
|
|
228
|
+
messageId: message.messageId,
|
|
143
229
|
found,
|
|
144
230
|
candidates,
|
|
145
231
|
};
|
package/src/cli.js
CHANGED
|
@@ -1,30 +1,55 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
1
3
|
import { parseArgs } from "node:util";
|
|
2
4
|
import { check } from "./check.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
+
import { collectColors } from "./colors.js";
|
|
6
|
+
import { CONFIG_FILE, loadConfig } from "./config.js";
|
|
7
|
+
import { formatColorsText, formatText } from "./format.js";
|
|
8
|
+
import { runHook } from "./hook.js";
|
|
9
|
+
import { AGENT_CHOICES, install } from "./install.js";
|
|
10
|
+
import { isLang, messages, resolveLang } from "./messages.js";
|
|
11
|
+
import { loadTokens } from "./rules/load-tokens.js";
|
|
5
12
|
|
|
6
|
-
const
|
|
13
|
+
const json = (result) => `${JSON.stringify(result, null, 2)}\n`;
|
|
7
14
|
|
|
8
|
-
|
|
15
|
+
// 명령은 내보낼 글과 종료 코드를 돌려준다. flagLang 은 --lang 으로 준 언어다(없으면 undefined).
|
|
16
|
+
const COMMANDS = {
|
|
17
|
+
async check({ cwd, paths, configPath, format, flagLang }) {
|
|
18
|
+
const config = loadConfig(cwd, configPath, resolveLang(flagLang));
|
|
19
|
+
const lang = resolveLang(flagLang, config.lang);
|
|
20
|
+
const result = await check({ cwd, config, paths, lang });
|
|
21
|
+
return {
|
|
22
|
+
stdout: format === "json" ? json(result) : formatText(result, lang),
|
|
23
|
+
exitCode: result.summary.errors > 0 ? 1 : 0,
|
|
24
|
+
};
|
|
25
|
+
},
|
|
9
26
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
27
|
+
// 설정 파일은 선택이다. 있으면 색마다 이미 있는 토큰을 붙인다.
|
|
28
|
+
async colors({ cwd, paths, configPath, format, flagLang }) {
|
|
29
|
+
const hasConfig = configPath !== undefined || fs.existsSync(path.resolve(cwd, CONFIG_FILE));
|
|
30
|
+
const config = hasConfig ? loadConfig(cwd, configPath, resolveLang(flagLang)) : undefined;
|
|
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 });
|
|
34
|
+
return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
|
|
35
|
+
},
|
|
13
36
|
|
|
14
|
-
|
|
15
|
-
|
|
37
|
+
hook({ cwd, configPath, stdin, flagLang }) {
|
|
38
|
+
return runHook({ cwd, input: stdin, configPath, lang: flagLang });
|
|
39
|
+
},
|
|
16
40
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
41
|
+
install({ cwd, flagLang, agent }) {
|
|
42
|
+
return install({ cwd, lang: resolveLang(flagLang), agent });
|
|
43
|
+
},
|
|
20
44
|
};
|
|
21
45
|
|
|
22
46
|
/**
|
|
23
47
|
* @param {string[]} argv 명령 이름부터 시작하는 인자 (process.argv.slice(2))
|
|
24
|
-
* @param {{ cwd: string, stdout: { write(chunk: string): unknown }, stderr: { write(chunk: string): unknown } }} io
|
|
48
|
+
* @param {{ cwd: string, stdin?: string, stdout: { write(chunk: string): unknown }, stderr: { write(chunk: string): unknown } }} io
|
|
49
|
+
* stdin 은 이미 읽어 둔 표준 입력이다. hook 명령만 쓴다
|
|
25
50
|
* @returns {Promise<number>} 종료 코드
|
|
26
51
|
*/
|
|
27
|
-
export async function run(argv, { cwd, stdout, stderr }) {
|
|
52
|
+
export async function run(argv, { cwd, stdin, stdout, stderr }) {
|
|
28
53
|
let args;
|
|
29
54
|
try {
|
|
30
55
|
args = parseArgs({
|
|
@@ -33,35 +58,51 @@ export async function run(argv, { cwd, stdout, stderr }) {
|
|
|
33
58
|
options: {
|
|
34
59
|
format: { type: "string", default: "text" },
|
|
35
60
|
config: { type: "string" },
|
|
61
|
+
lang: { type: "string" },
|
|
62
|
+
agent: { type: "string", default: "claude" },
|
|
36
63
|
help: { type: "boolean", short: "h" },
|
|
37
64
|
},
|
|
38
65
|
});
|
|
39
66
|
} catch (error) {
|
|
40
|
-
stderr.write(`${error.message}\n\n${
|
|
67
|
+
stderr.write(`${error.message}\n\n${messages().cliUsage}`);
|
|
41
68
|
return 2;
|
|
42
69
|
}
|
|
43
70
|
|
|
71
|
+
const flagLang = args.values.lang;
|
|
72
|
+
const usage = messages(resolveLang(flagLang)).cliUsage;
|
|
73
|
+
|
|
44
74
|
if (args.values.help) {
|
|
45
|
-
stdout.write(
|
|
75
|
+
stdout.write(usage);
|
|
46
76
|
return 0;
|
|
47
77
|
}
|
|
48
78
|
|
|
49
|
-
const [
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
79
|
+
const [name, ...paths] = args.positionals;
|
|
80
|
+
const command = Object.hasOwn(COMMANDS, name ?? "") ? COMMANDS[name] : undefined;
|
|
81
|
+
const { format } = args.values;
|
|
82
|
+
const validLang = flagLang === undefined || isLang(flagLang);
|
|
83
|
+
const { agent } = args.values;
|
|
84
|
+
if (!command || !["text", "json"].includes(format) || !validLang || !AGENT_CHOICES.includes(agent)) {
|
|
85
|
+
stderr.write(usage);
|
|
53
86
|
return 2;
|
|
54
87
|
}
|
|
55
88
|
|
|
56
|
-
let
|
|
89
|
+
let outcome;
|
|
57
90
|
try {
|
|
58
|
-
|
|
59
|
-
|
|
91
|
+
outcome = await command({
|
|
92
|
+
cwd,
|
|
93
|
+
paths: paths.length > 0 ? paths : undefined,
|
|
94
|
+
configPath: args.values.config,
|
|
95
|
+
format,
|
|
96
|
+
stdin,
|
|
97
|
+
flagLang,
|
|
98
|
+
agent,
|
|
99
|
+
});
|
|
60
100
|
} catch (error) {
|
|
61
101
|
stderr.write(`${error.message}\n`);
|
|
62
102
|
return 2;
|
|
63
103
|
}
|
|
64
104
|
|
|
65
|
-
stdout.write(
|
|
66
|
-
|
|
105
|
+
if (outcome.stdout) stdout.write(outcome.stdout);
|
|
106
|
+
if (outcome.stderr) stderr.write(outcome.stderr);
|
|
107
|
+
return outcome.exitCode;
|
|
67
108
|
}
|
package/src/colors.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { findArbitraryColors, findPaletteClasses } from "./core/classes.js";
|
|
4
|
+
import { normalizeHex } from "./core/color.js";
|
|
5
|
+
import { findCssColors } from "./core/css.js";
|
|
6
|
+
import { createEngine } from "./engine.js";
|
|
7
|
+
import { splitPaths } from "./files.js";
|
|
8
|
+
import { visitStrings } from "./rules/visit-strings.js";
|
|
9
|
+
|
|
10
|
+
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
|
+
const MAX_EXAMPLES = 3;
|
|
13
|
+
|
|
14
|
+
// 알파가 붙은 hex 는 6자리로 펼칠 수 없으니 소문자로만 맞춘다.
|
|
15
|
+
const colorKey = (hex) => normalizeHex(hex) ?? hex.toLowerCase();
|
|
16
|
+
|
|
17
|
+
const findColors = (text) => [
|
|
18
|
+
...findArbitraryColors(text).map((found) => ({
|
|
19
|
+
...found,
|
|
20
|
+
payload: { kind: "hex", key: colorKey(found.value), utility: found.utility },
|
|
21
|
+
})),
|
|
22
|
+
...findPaletteClasses(text).map((found) => ({
|
|
23
|
+
...found,
|
|
24
|
+
payload: { kind: "palette", key: found.name, utility: found.utility },
|
|
25
|
+
})),
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
// 위반을 보고하는 규칙이 아니라, 찾은 색을 메시지에 실어 내보내는 수집용 규칙이다.
|
|
29
|
+
const collectRule = {
|
|
30
|
+
meta: { type: "suggestion", schema: [], messages: { found: "{{payload}}" } },
|
|
31
|
+
create(context) {
|
|
32
|
+
const report = (loc, payload) =>
|
|
33
|
+
context.report({ loc, messageId: "found", data: { payload: JSON.stringify(payload) } });
|
|
34
|
+
const visitor = visitStrings(context, findColors, (found, { loc }) => report(loc, found.payload));
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
...visitor,
|
|
38
|
+
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 });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
visitor.Literal(node);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} ColorUse
|
|
52
|
+
* @property {number} uses 쓰인 횟수
|
|
53
|
+
* @property {number} files 쓰인 파일 수
|
|
54
|
+
* @property {Record<string, number>} utilities Tailwind 유틸리티별 횟수. 예: { bg: 3, text: 1 }
|
|
55
|
+
* @property {{ file: string, line: number }[]} examples 파일이 서로 다른 위치 몇 개
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 코드에서 쓰는 색을 모은다. 설정 파일이 없어도 동작한다.
|
|
60
|
+
* @param {object} options
|
|
61
|
+
* @param {string} options.cwd 프로젝트 디렉터리
|
|
62
|
+
* @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
|
|
63
|
+
* @param {Map<string, string[]>} [options.tokens] 색 값 → 토큰 이름들. 주면 색마다 tokens 를 붙인다
|
|
64
|
+
* @returns {Promise<{
|
|
65
|
+
* summary: { files: number, colors: number, paletteColors: number, uses: number },
|
|
66
|
+
* colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
|
|
67
|
+
* palette: (ColorUse & { name: string })[],
|
|
68
|
+
* }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
|
|
69
|
+
* literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
|
|
70
|
+
*/
|
|
71
|
+
export async function collectColors({ cwd, paths = ["."], tokens }) {
|
|
72
|
+
const eslint = createEngine({
|
|
73
|
+
cwd,
|
|
74
|
+
// 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
|
|
75
|
+
allowInlineConfig: false,
|
|
76
|
+
config: {
|
|
77
|
+
plugins: { "designsnitch-internal": { rules: { "collect-colors": collectRule } } },
|
|
78
|
+
rules: { [RULE_ID]: "warn" },
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
|
|
83
|
+
const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
|
|
84
|
+
|
|
85
|
+
/** @type {{ file: string, line: number, kind: "hex" | "palette", key: string, utility?: string | null, prop?: string }[]} */
|
|
86
|
+
const uses = [];
|
|
87
|
+
for (const result of results) {
|
|
88
|
+
const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
|
|
89
|
+
for (const message of result.messages) {
|
|
90
|
+
if (message.ruleId !== RULE_ID) continue;
|
|
91
|
+
uses.push({ file, line: message.line, ...JSON.parse(message.message) });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const file of cssFiles) {
|
|
95
|
+
let found;
|
|
96
|
+
try {
|
|
97
|
+
found = findCssColors(fs.readFileSync(path.resolve(cwd, file), "utf8"));
|
|
98
|
+
} catch {
|
|
99
|
+
continue; // 읽지 못한 CSS 는 건너뛴다
|
|
100
|
+
}
|
|
101
|
+
for (const { line, value, prop } of found) {
|
|
102
|
+
uses.push({ file, line, kind: "hex", key: colorKey(value), prop });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
uses.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
|
|
106
|
+
|
|
107
|
+
const groups = { hex: new Map(), palette: new Map() };
|
|
108
|
+
for (const { file, line, kind, key, utility, prop } of uses) {
|
|
109
|
+
const entry = getOrCreate(groups[kind], key);
|
|
110
|
+
entry.uses += 1;
|
|
111
|
+
if (prop) entry.properties[prop] = (entry.properties[prop] ?? 0) + 1;
|
|
112
|
+
else if (utility) entry.utilities[utility] = (entry.utilities[utility] ?? 0) + 1;
|
|
113
|
+
else entry.literals += 1;
|
|
114
|
+
if (!entry.fileSet.has(file)) {
|
|
115
|
+
entry.fileSet.add(file);
|
|
116
|
+
if (entry.examples.length < MAX_EXAMPLES) entry.examples.push({ file, line });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const colors = sorted(groups.hex).map(([color, entry]) => ({
|
|
121
|
+
color,
|
|
122
|
+
uses: entry.uses,
|
|
123
|
+
files: entry.fileSet.size,
|
|
124
|
+
utilities: entry.utilities,
|
|
125
|
+
literals: entry.literals,
|
|
126
|
+
properties: entry.properties,
|
|
127
|
+
...(tokens ? { tokens: tokens.get(color) ?? [] } : {}),
|
|
128
|
+
examples: entry.examples,
|
|
129
|
+
}));
|
|
130
|
+
// 프로젝트가 --color-blue-500 처럼 같은 이름의 토큰을 정의했으면 그 클래스는 프로젝트 토큰이다.
|
|
131
|
+
const tokenClassNames = new Set(
|
|
132
|
+
[...(tokens?.values() ?? [])].flat().map((name) => name.replace(/^--color-/, "")),
|
|
133
|
+
);
|
|
134
|
+
const palette = sorted(groups.palette)
|
|
135
|
+
.filter(([name]) => !tokenClassNames.has(name))
|
|
136
|
+
.map(([name, entry]) => ({
|
|
137
|
+
name,
|
|
138
|
+
uses: entry.uses,
|
|
139
|
+
files: entry.fileSet.size,
|
|
140
|
+
utilities: entry.utilities,
|
|
141
|
+
examples: entry.examples,
|
|
142
|
+
}));
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
summary: {
|
|
146
|
+
files: results.length + cssFiles.length,
|
|
147
|
+
colors: colors.length,
|
|
148
|
+
paletteColors: palette.length,
|
|
149
|
+
uses: [...colors, ...palette].reduce((sum, item) => sum + item.uses, 0),
|
|
150
|
+
},
|
|
151
|
+
colors,
|
|
152
|
+
palette,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function getOrCreate(map, key) {
|
|
157
|
+
if (!map.has(key)) {
|
|
158
|
+
map.set(key, { uses: 0, fileSet: new Set(), utilities: {}, literals: 0, properties: {}, examples: [] });
|
|
159
|
+
}
|
|
160
|
+
return map.get(key);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 많이 쓰인 순서, 같으면 이름 순서
|
|
164
|
+
function sorted(map) {
|
|
165
|
+
return [...map].sort(([a, x], [b, y]) => y.uses - x.uses || a.localeCompare(b));
|
|
166
|
+
}
|