designsnitch 0.2.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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: designsnitch-hooks
3
- description: Register designsnitch as a hook of the coding agent, so the agent is told about design system errors right after it edits a file and cannot finish while errors it can fix remain. Use as part of setting up designsnitch, or when the user asks to make AI-written code follow the design system automatically.
3
+ description: Register designsnitch as a hook of the coding agent (Claude Code, Codex, Gemini CLI or Grok Build), so the agent is told about design system errors right after it edits a file and cannot finish while errors it can fix remain. Use as part of setting up designsnitch, or when the user asks to make AI-written code follow the design system automatically.
4
4
  ---
5
5
 
6
6
  # designsnitch-hooks
@@ -11,7 +11,7 @@ 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.
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.
15
15
 
16
16
  | When it runs | What happens |
17
17
  | --- | --- |
@@ -20,7 +20,7 @@ A skill is advice: an agent may or may not follow it. A hook is run by the agent
20
20
 
21
21
  - Warnings never block.
22
22
  - 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.
23
- - Violations that were already in files the agent did not touch are left alone.
23
+ - 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
24
 
25
25
  ## 1. Register the hook in Claude Code
26
26
 
@@ -54,17 +54,92 @@ If you need to do it by hand, this is what it adds to `.claude/settings.json`.
54
54
 
55
55
  `.claude/settings.json` is shared with the team through git, so the hook applies to everyone who uses Claude Code in this project. If the user wants the hook only for themselves, do not run the installer: add the entries above to `.claude/settings.local.json` by hand.
56
56
 
57
- ## 2. Other agents
57
+ ## 2. Register the hook in Codex
58
58
 
59
- `designsnitch hook` does not depend on Claude Code. It reads an optional JSON object from stdin:
59
+ ```sh
60
+ npx designsnitch install --agent codex
61
+ ```
62
+
63
+ It adds the hook to `.codex/hooks.json` and copies the skills into `.agents/skills`. Use `--agent all` to set up every supported agent together.
64
+
65
+ ```json
66
+ {
67
+ "hooks": {
68
+ "PostToolUse": [
69
+ {
70
+ "matcher": "apply_patch",
71
+ "hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
72
+ }
73
+ ],
74
+ "Stop": [
75
+ {
76
+ "hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
77
+ }
78
+ ]
79
+ }
80
+ }
81
+ ```
82
+
83
+ Two things are different in Codex. Tell the user about both.
84
+
85
+ - **The hook does not run until the user approves it.** Codex runs project hooks only in a project the user has trusted, and only hooks the user has approved. You cannot do this for them. Ask the user to open Codex in the project and approve when it asks.
86
+ - **Codex often edits files with shell commands, which the `apply_patch` matcher does not see.** Those edits are still caught when Codex is about to finish: the `Stop` hook checks every file git reports as changed.
87
+
88
+ ## 3. Register the hook in Gemini CLI
89
+
90
+ ```sh
91
+ npx designsnitch install --agent gemini
92
+ ```
93
+
94
+ It adds the hook to `.gemini/settings.json` and copies the skills into `.agents/skills`, which Gemini CLI reads as workspace skills. Gemini CLI uses different event names, and its `timeout` is in milliseconds.
95
+
96
+ ```json
97
+ {
98
+ "hooks": {
99
+ "AfterTool": [
100
+ {
101
+ "matcher": "write_file|replace",
102
+ "hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
103
+ }
104
+ ],
105
+ "AfterAgent": [
106
+ {
107
+ "hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
108
+ }
109
+ ]
110
+ }
111
+ }
112
+ ```
113
+
114
+ - `AfterTool` runs after `write_file` or `replace`. Exit code 2 replaces the tool's result with the errors, and the turn continues.
115
+ - `AfterAgent` runs when Gemini CLI is about to answer. Exit code 2 rejects the answer and makes it try again with the errors as feedback. `stop_hook_active` keeps it from looping.
116
+
117
+ Tell the user that Gemini CLI warns before it runs a new project hook, and that they need to allow it. If they have turned on folder trust, they also need to trust the folder. This setup follows the official Gemini CLI documentation and has not been tested with Gemini CLI. If the user reports that the hook does not fire, check that the installed Gemini CLI version supports hooks.
118
+
119
+ ## 4. Register the hook in Grok Build
120
+
121
+ ```sh
122
+ npx designsnitch install --agent grok
123
+ ```
124
+
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.
126
+
127
+ Tell the user two things.
128
+
129
+ - **The hook does not run until the project is trusted.** Ask the user to run `/hooks-trust` in Grok Build, or to start it with `--trust`.
130
+ - **Grok Build may report the errors without stopping.** Its documentation calls `PreToolUse` the only blocking event and does not say what exit code 2 does after a tool or at the end of a turn. This setup follows the official xAI documentation and has not been tested with Grok Build.
131
+
132
+ ## 5. Other agents
133
+
134
+ `designsnitch hook` does not depend on a particular agent. It reads an optional JSON object from stdin:
60
135
 
61
136
  - `tool_input.file_path`: the file that was just edited. Without it, the files that git reports as changed are checked.
62
- - `hook_event_name`: `Stop` or `SubagentStop` means the agent is about to finish.
137
+ - `hook_event_name` (or `hookEventName`): `Stop`, `SubagentStop` or `AfterAgent` means the agent is about to finish.
63
138
  - `stop_hook_active`: when true, the hook does not block again.
64
139
 
65
140
  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.
66
141
 
67
- ## 3. Verify
142
+ ## 6. Verify
68
143
 
69
144
  Make the hook fire once.
70
145
 
@@ -79,7 +154,7 @@ It should print the error and exit with 2.
79
154
 
80
155
  3. Undo the test change and run it again. It should print nothing and exit with 0.
81
156
 
82
- ## 4. Tell the user
157
+ ## 7. Tell the user
83
158
 
84
159
  Say which file you changed and what the hook will now do. Mention that it only looks at files the agent changes, so existing violations elsewhere stay until someone cleans them up with the `designsnitch-check` skill.
85
160
 
@@ -53,6 +53,12 @@ Read the files in that directory and find the components whose root element is a
53
53
 
54
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
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
+
56
62
  ## 4. Write the file
57
63
 
58
64
  ```json
@@ -62,7 +68,7 @@ Leave out components that only happen to contain a raw tag deep inside, such as
62
68
  "path": "./src/components/ui",
63
69
  "replaces": {
64
70
  "button": ["SolidButton", "GlassButton", "IconButton"],
65
- "input": "Input"
71
+ "input": { "component": "Input", "when": { "type": ["text", "email", "password", null] } }
66
72
  }
67
73
  }
68
74
  }
@@ -70,6 +76,8 @@ Leave out components that only happen to contain a raw tag deep inside, such as
70
76
 
71
77
  Paths are relative to the project root.
72
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
+
73
81
  ## 5. Verify
74
82
 
75
83
  ```sh
package/src/check.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { replacementNames } from "./config.js";
3
4
  import { normalizeHex } from "./core/color.js";
4
5
  import { findCssColors } from "./core/css.js";
5
6
  import { createEngine } from "./engine.js";
6
7
  import { splitPaths } from "./files.js";
7
8
  import plugin from "./index.js";
9
+ import { messages, resolveLang } from "./messages.js";
8
10
  import { loadTokens } from "./rules/load-tokens.js";
9
11
 
10
12
  const RULE_PREFIX = "designsnitch/";
@@ -22,8 +24,8 @@ const RULE_PREFIX = "designsnitch/";
22
24
  * @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
23
25
  * @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
24
26
  * @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
25
- * replace: found 를 candidates 의 값으로 바꾸면 된다 (후보가 하나뿐인 오류)
26
- * ask: 사람이 정해야 한다 (후보가 여러 개이거나, 토큰에 없는 값)
27
+ * replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
28
+ * ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
27
29
  * repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
28
30
  */
29
31
 
@@ -33,6 +35,7 @@ const RULE_PREFIX = "designsnitch/";
33
35
  * @param {string} options.cwd 프로젝트 디렉터리
34
36
  * @param {ReturnType<typeof import("./config.js").loadConfig>} options.config
35
37
  * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
38
+ * @param {"en" | "ko"} [options.lang] 문장의 언어. 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
36
39
  * @returns {Promise<{
37
40
  * designSystem: { colorTokens: number, components: number, replacedTags: number },
38
41
  * problems: string[],
@@ -42,24 +45,23 @@ const RULE_PREFIX = "designsnitch/";
42
45
  * }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제,
43
46
  * next 는 이 결과를 받은 에이전트가 순서대로 할 일
44
47
  */
45
- export async function check({ cwd, config, paths = ["."] }) {
46
- const settings = { designsnitch: config };
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 } };
47
53
  // 설정에 문제가 있으면 파일을 검사하기 전에 알린다.
48
54
  const tokens = loadTokens(settings, cwd);
49
55
  if (config.components) {
50
56
  const dir = path.resolve(cwd, config.components.path);
51
57
  if (!fs.existsSync(dir)) {
52
- throw new Error(`디자인 시스템 컴포넌트 경로를 찾을 수 없습니다: ${dir}`);
58
+ throw new Error(m.componentsDirMissing({ dir }));
53
59
  }
54
60
  }
55
61
  const designSystem = describeDesignSystem(tokens, config);
56
62
  const problems = [];
57
63
  if (designSystem.colorTokens === 0) {
58
- problems.push(
59
- `색 토큰을 하나도 읽지 못했습니다: ${config.tokens}. ` +
60
- "--color-* 변수의 값이 hex이거나 var()로 hex를 가리켜야 읽을 수 있습니다. " +
61
- '지금은 모든 hex가 "토큰에 없음" 경고로 나옵니다.',
62
- );
64
+ problems.push(m.noColorTokens({ tokens: config.tokens }));
63
65
  }
64
66
 
65
67
  const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
@@ -74,17 +76,17 @@ export async function check({ cwd, config, paths = ["."] }) {
74
76
  .map((message) => toViolation(file, result.source, message, config));
75
77
  });
76
78
  const cssViolations = cssFiles.flatMap((file) =>
77
- checkCss(file, fs.readFileSync(path.resolve(cwd, file), "utf8"), tokens.colors),
79
+ checkCss(file, fs.readFileSync(path.resolve(cwd, file), "utf8"), tokens, m),
78
80
  );
79
81
 
80
82
  const violations = [...scriptViolations, ...cssViolations]
81
83
  .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
82
- .map((violation) => ({ ...violation, action: actionFor(violation) }));
84
+ .map(({ messageId, ...violation }) => ({ ...violation, action: actionFor(violation, messageId) }));
83
85
 
84
86
  return {
85
87
  designSystem,
86
88
  problems,
87
- next: nextSteps(designSystem, violations),
89
+ next: nextSteps(designSystem, violations, lang),
88
90
  summary: {
89
91
  files: results.length + cssFiles.length,
90
92
  errors: violations.filter((v) => v.severity === "error").length,
@@ -96,9 +98,9 @@ export async function check({ cwd, config, paths = ["."] }) {
96
98
 
97
99
  /**
98
100
  * CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
99
- * @returns {Violation[]}
101
+ * @returns {(Omit<Violation, "action"> & { messageId?: string })[]}
100
102
  */
101
- function checkCss(file, source, colorTokens) {
103
+ function checkCss(file, source, tokens, m) {
102
104
  let colors;
103
105
  try {
104
106
  colors = findCssColors(source);
@@ -122,8 +124,9 @@ function checkCss(file, source, colorTokens) {
122
124
  return colors
123
125
  .filter((color) => !color.disabled)
124
126
  .map(({ value, prop, disabled, ...location }) => {
125
- const tokenNames = colorTokens.get(normalizeHex(value)) ?? [];
127
+ const tokenNames = tokens.colors.get(normalizeHex(value)) ?? [];
126
128
  const candidates = tokenNames.map((name) => `var(${name})`);
129
+ const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
127
130
  return {
128
131
  file,
129
132
  ...location,
@@ -131,12 +134,17 @@ function checkCss(file, source, colorTokens) {
131
134
  ? {
132
135
  rule: "color-use-token",
133
136
  severity: "error",
134
- message: `${value}의 색은 토큰 ${tokenNames.join(", ")}의 값입니다. 대신 사용: ${candidates.join(", ")}`,
137
+ messageId,
138
+ message: m[messageId]({
139
+ found: value,
140
+ tokens: tokenNames.join(", "),
141
+ candidates: candidates.join(", "),
142
+ }),
135
143
  }
136
144
  : {
137
145
  rule: "color-unknown",
138
146
  severity: "warning",
139
- message: `${value}의 색은 토큰에 없습니다.`,
147
+ message: m.unknownCssColor({ value }),
140
148
  }),
141
149
  found: value,
142
150
  candidates,
@@ -144,8 +152,9 @@ function checkCss(file, source, colorTokens) {
144
152
  });
145
153
  }
146
154
 
147
- function actionFor({ rule, severity, candidates }) {
155
+ function actionFor({ rule, severity, candidates }, messageId) {
148
156
  if (rule === "parse-error") return "repair";
157
+ if (messageId === "useComponentAsk" || messageId === "useTokenThemed") return "ask";
149
158
  return severity === "error" && candidates.length === 1 ? "replace" : "ask";
150
159
  }
151
160
 
@@ -153,9 +162,11 @@ function actionFor({ rule, severity, candidates }) {
153
162
  * 결과를 받은 에이전트가 무엇부터 해야 하는지를 순서대로 적는다.
154
163
  * @param {{ colorTokens: number }} designSystem
155
164
  * @param {Violation[]} violations action 이 붙은 위반들
165
+ * @param {"en" | "ko"} [lang]
156
166
  * @returns {string[]}
157
167
  */
158
- export function nextSteps(designSystem, violations) {
168
+ export function nextSteps(designSystem, violations, lang) {
169
+ const m = messages(lang);
159
170
  const noColorTokens = designSystem.colorTokens === 0;
160
171
  // 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
161
172
  const actionable = noColorTokens
@@ -165,23 +176,13 @@ export function nextSteps(designSystem, violations) {
165
176
  const [repair, replace, ask] = ["repair", "replace", "ask"].map(count);
166
177
  const steps = [];
167
178
 
168
- if (noColorTokens) {
169
- steps.push(
170
- "색 토큰이 없어서 색을 판정할 기준이 없습니다. 색을 고치기 전에 `designsnitch colors`로 쓰이는 색을 모아 토큰부터 정하세요.",
171
- );
172
- }
173
- if (repair > 0) steps.push(`action이 repair인 ${repair}건은 그 파일의 문법 오류부터 고치세요.`);
174
- if (replace > 0) {
175
- steps.push(`action이 replace인 ${replace}건은 found를 candidates의 값으로 바꾸세요.`);
176
- }
177
- if (ask > 0) {
178
- steps.push(
179
- `action이 ask인 ${ask}건은 바꾸지 말고 사용자에게 물으세요. 물을 때는 \`designsnitch colors\`로 그 색이 몇 곳에서 어떻게 쓰이는지 확인해서 근거로 함께 주세요.`,
180
- );
181
- }
182
- if (repair + replace > 0) steps.push("고친 뒤 같은 명령을 다시 실행하세요.");
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());
183
184
 
184
- return steps.length > 0 ? steps : ["위반이 없습니다."];
185
+ return steps.length > 0 ? steps : [m.nextNone()];
185
186
  }
186
187
 
187
188
  function describeDesignSystem(tokens, config) {
@@ -189,7 +190,7 @@ function describeDesignSystem(tokens, config) {
189
190
  const replaces = Object.values(config.components?.replaces ?? {});
190
191
  return {
191
192
  colorTokens: countNames(tokens.colors),
192
- components: new Set(replaces.flat()).size,
193
+ components: new Set(replaces.flatMap(replacementNames)).size,
193
194
  replacedTags: replaces.length,
194
195
  };
195
196
  }
@@ -212,7 +213,7 @@ function toViolation(file, source, message, config) {
212
213
  let candidates = (message.suggestions ?? []).map((suggestion) => suggestion.fix.text);
213
214
  if (rule === "use-ds-component") {
214
215
  // 컴포넌트는 import 까지 바꿔야 해서 제안(자동 교체)이 없다. 설정에서 후보를 찾는다.
215
- candidates = [config.components?.replaces?.[found] ?? []].flat();
216
+ candidates = replacementNames(config.components?.replaces?.[found]);
216
217
  }
217
218
 
218
219
  return {
@@ -224,6 +225,7 @@ function toViolation(file, source, message, config) {
224
225
  rule,
225
226
  severity: message.severity === 2 ? "error" : "warning",
226
227
  message: message.message,
228
+ messageId: message.messageId,
227
229
  found,
228
230
  candidates,
229
231
  };
package/src/cli.js CHANGED
@@ -6,53 +6,40 @@ import { collectColors } from "./colors.js";
6
6
  import { CONFIG_FILE, loadConfig } from "./config.js";
7
7
  import { formatColorsText, formatText } from "./format.js";
8
8
  import { runHook } from "./hook.js";
9
- import { install } from "./install.js";
9
+ import { AGENT_CHOICES, install } from "./install.js";
10
+ import { isLang, messages, resolveLang } from "./messages.js";
10
11
  import { loadTokens } from "./rules/load-tokens.js";
11
12
 
12
- const USAGE = `사용법: designsnitch <명령> [경로...] [--format text|json] [--config 파일]
13
-
14
- 명령
15
- check UI 코드가 디자인 시스템을 따르는지 검사합니다.
16
- colors 코드에서 쓰는 색을 모아 보여줍니다. 설정 파일이 없어도 됩니다.
17
- hook 코딩 에이전트의 훅에서 부릅니다. 방금 고친 파일에 오류가 있으면 2로 끝납니다.
18
- install 스킬과 에이전트 훅을 프로젝트(.claude)에 설치합니다.
19
-
20
- 옵션
21
- 경로 볼 파일이나 디렉터리 (기본: 현재 디렉터리)
22
- --format 출력 형식. text(기본) 또는 json
23
- --config 설정 파일 경로 (기본: designsnitch.config.json)
24
-
25
- check 의 종료 코드: 0 오류 없음, 1 오류 있음, 2 실행하지 못함
26
- `;
27
-
28
13
  const json = (result) => `${JSON.stringify(result, null, 2)}\n`;
29
14
 
30
- // 명령은 내보낼 글과 종료 코드를 돌려준다.
15
+ // 명령은 내보낼 글과 종료 코드를 돌려준다. flagLang 은 --lang 으로 준 언어다(없으면 undefined).
31
16
  const COMMANDS = {
32
- async check({ cwd, paths, configPath, format }) {
33
- const result = await check({ cwd, config: loadConfig(cwd, configPath), paths });
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 });
34
21
  return {
35
- stdout: format === "json" ? json(result) : formatText(result),
22
+ stdout: format === "json" ? json(result) : formatText(result, lang),
36
23
  exitCode: result.summary.errors > 0 ? 1 : 0,
37
24
  };
38
25
  },
39
26
 
40
27
  // 설정 파일은 선택이다. 있으면 색마다 이미 있는 토큰을 붙인다.
41
- async colors({ cwd, paths, configPath, format }) {
28
+ async colors({ cwd, paths, configPath, format, flagLang }) {
42
29
  const hasConfig = configPath !== undefined || fs.existsSync(path.resolve(cwd, CONFIG_FILE));
43
- const tokens = hasConfig
44
- ? loadTokens({ designsnitch: loadConfig(cwd, configPath) }, cwd).colors
45
- : undefined;
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;
46
33
  const result = await collectColors({ cwd, paths, tokens });
47
- return { stdout: format === "json" ? json(result) : formatColorsText(result), exitCode: 0 };
34
+ return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
48
35
  },
49
36
 
50
- hook({ cwd, configPath, stdin }) {
51
- return runHook({ cwd, input: stdin, configPath });
37
+ hook({ cwd, configPath, stdin, flagLang }) {
38
+ return runHook({ cwd, input: stdin, configPath, lang: flagLang });
52
39
  },
53
40
 
54
- install({ cwd }) {
55
- return install({ cwd });
41
+ install({ cwd, flagLang, agent }) {
42
+ return install({ cwd, lang: resolveLang(flagLang), agent });
56
43
  },
57
44
  };
58
45
 
@@ -71,24 +58,31 @@ export async function run(argv, { cwd, stdin, stdout, stderr }) {
71
58
  options: {
72
59
  format: { type: "string", default: "text" },
73
60
  config: { type: "string" },
61
+ lang: { type: "string" },
62
+ agent: { type: "string", default: "claude" },
74
63
  help: { type: "boolean", short: "h" },
75
64
  },
76
65
  });
77
66
  } catch (error) {
78
- stderr.write(`${error.message}\n\n${USAGE}`);
67
+ stderr.write(`${error.message}\n\n${messages().cliUsage}`);
79
68
  return 2;
80
69
  }
81
70
 
71
+ const flagLang = args.values.lang;
72
+ const usage = messages(resolveLang(flagLang)).cliUsage;
73
+
82
74
  if (args.values.help) {
83
- stdout.write(USAGE);
75
+ stdout.write(usage);
84
76
  return 0;
85
77
  }
86
78
 
87
79
  const [name, ...paths] = args.positionals;
88
80
  const command = Object.hasOwn(COMMANDS, name ?? "") ? COMMANDS[name] : undefined;
89
81
  const { format } = args.values;
90
- if (!command || !["text", "json"].includes(format)) {
91
- stderr.write(USAGE);
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);
92
86
  return 2;
93
87
  }
94
88
 
@@ -100,6 +94,8 @@ export async function run(argv, { cwd, stdin, stdout, stderr }) {
100
94
  configPath: args.values.config,
101
95
  format,
102
96
  stdin,
97
+ flagLang,
98
+ agent,
103
99
  });
104
100
  } catch (error) {
105
101
  stderr.write(`${error.message}\n`);
package/src/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { isLang, messages } from "./messages.js";
3
4
 
4
5
  export const CONFIG_FILE = "designsnitch.config.json";
5
6
 
@@ -11,56 +12,69 @@ const EXAMPLE = `{
11
12
  }
12
13
  }`;
13
14
 
15
+ /** @typedef {string | string[] | { component: string | string[], when?: Record<string, (string | null)[]> }} Replacement */
16
+
17
+ /** @param {Replacement} [replacement] */
18
+ export function replacementNames(replacement) {
19
+ const component = typeof replacement === "string" || Array.isArray(replacement)
20
+ ? replacement
21
+ : replacement?.component;
22
+ return [component ?? []].flat();
23
+ }
24
+
14
25
  /**
15
26
  * 프로젝트의 설정 파일을 읽는다. 문제가 있으면 무엇을 고쳐야 하는지 담은 Error 를 던진다.
16
27
  * @param {string} cwd 프로젝트 디렉터리
17
28
  * @param {string} [configPath] cwd 기준 설정 파일 경로
18
- * @returns {{ tokens: string, components?: { path: string, replaces: Record<string, string | string[]> } }}
29
+ * @param {"en" | "ko"} [lang] 오류 문장의 언어
30
+ * @returns {{ tokens: string, lang?: "en" | "ko", components?: { path: string, replaces: Record<string, Replacement> } }}
19
31
  */
20
- export function loadConfig(cwd, configPath = CONFIG_FILE) {
32
+ export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
33
+ const m = messages(lang);
21
34
  const file = path.resolve(cwd, configPath);
22
35
 
23
36
  let text;
24
37
  try {
25
38
  text = fs.readFileSync(file, "utf8");
26
39
  } catch {
27
- throw new Error(
28
- `설정 파일이 없습니다: ${file}\n` +
29
- `다음과 같은 내용으로 만드세요. designsnitch-setup 스킬을 따르면 저장소를 읽어서 만들 수 있습니다.\n${EXAMPLE}`,
30
- );
40
+ throw new Error(m.configMissing({ file, example: EXAMPLE }));
31
41
  }
32
42
 
33
43
  let config;
34
44
  try {
35
45
  config = JSON.parse(text);
36
46
  } catch (error) {
37
- throw new Error(`설정 파일을 읽을 수 없습니다: ${file}\n${error.message}`);
47
+ throw new Error(m.configUnreadable({ file, reason: error.message }));
38
48
  }
39
49
 
40
- if (typeof config?.tokens !== "string") {
41
- throw new Error(`설정 파일에 "tokens"(토큰 CSS 파일 경로)가 없습니다: ${file}`);
42
- }
43
- if (config.components !== undefined) validateComponents(config.components, file);
50
+ if (typeof config?.tokens !== "string") throw new Error(m.configNoTokens({ file }));
51
+ if (config.lang !== undefined && !isLang(config.lang)) throw new Error(m.configBadLang({ file }));
52
+ if (config.components !== undefined) validateComponents(config.components, file, m);
44
53
  return config;
45
54
  }
46
55
 
47
- function validateComponents(components, file) {
48
- if (typeof components?.path !== "string") {
49
- throw new Error(
50
- `설정 파일의 "components.path"(디자인 시스템 컴포넌트 경로)가 없습니다: ${file}`,
51
- );
52
- }
53
- if (typeof components.replaces !== "object" || components.replaces === null) {
54
- throw new Error(
55
- `설정 파일의 "components.replaces"(raw 태그와 대체 컴포넌트)가 없습니다: ${file}`,
56
- );
56
+ function validateComponents(components, file, m) {
57
+ if (typeof components?.path !== "string") throw new Error(m.configNoComponentsPath({ file }));
58
+ if (!isRecord(components.replaces)) {
59
+ throw new Error(m.configNoReplaces({ file }));
57
60
  }
58
61
  for (const [tag, value] of Object.entries(components.replaces)) {
59
- const names = [value].flat();
62
+ const conditional = isRecord(value);
63
+ const names = replacementNames(value);
60
64
  if (names.length === 0 || names.some((name) => typeof name !== "string" || name === "")) {
61
- throw new Error(
62
- `설정 파일의 "components.replaces.${tag}"는 컴포넌트 이름이거나 이름의 배열이어야 합니다: ${file}`,
63
- );
65
+ throw new Error(conditional ? m.configBadReplaceComponent({ tag, file }) : m.configBadReplace({ tag, file }));
66
+ }
67
+
68
+ if (!conditional || value.when === undefined) continue;
69
+ if (!isRecord(value.when)) throw new Error(m.configBadWhen({ tag, file }));
70
+ for (const [attribute, allowed] of Object.entries(value.when)) {
71
+ if (!Array.isArray(allowed) || allowed.some((entry) => entry !== null && typeof entry !== "string")) {
72
+ throw new Error(m.configBadWhenValues({ tag, attribute, file }));
73
+ }
64
74
  }
65
75
  }
66
76
  }
77
+
78
+ function isRecord(value) {
79
+ return value !== null && typeof value === "object" && !Array.isArray(value);
80
+ }
@@ -14,6 +14,15 @@ const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
14
14
  * @returns {Map<string, string[]>}
15
15
  */
16
16
  export function parseColorTokens(css) {
17
+ return parseColorTokenData(css).colors;
18
+ }
19
+
20
+ /**
21
+ * 색 값 → 토큰 표와 서로 다른 최종 값이 있는 토큰 이름을 함께 읽는다.
22
+ * @param {string} css
23
+ * @returns {{ colors: Map<string, string[]>, themed: Set<string> }}
24
+ */
25
+ export function parseColorTokenData(css) {
17
26
  /** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
18
27
  const declared = new Map();
19
28
  postcss.parse(css).walkDecls(/^--/, (decl) => {
@@ -22,13 +31,11 @@ export function parseColorTokens(css) {
22
31
  declared.set(decl.prop, values);
23
32
  });
24
33
 
25
- /** @returns {string[]} 값이 결국 가리키는 hex 색들 */
34
+ /** @returns {string[]} 값이 결국 가리키는 값들 */
26
35
  function resolve(value, visiting) {
27
- const color = normalizeHex(value);
28
- if (color) return [color];
29
-
30
- const reference = VAR_REFERENCE.exec(value.trim());
31
- if (!reference) return [];
36
+ const trimmed = value.trim();
37
+ const reference = VAR_REFERENCE.exec(trimmed);
38
+ if (!reference) return [trimmed];
32
39
  const [, name, fallback] = reference;
33
40
  if (visiting.has(name)) return [];
34
41
  if (!declared.has(name)) return fallback ? resolve(fallback, visiting) : [];
@@ -37,14 +44,22 @@ export function parseColorTokens(css) {
37
44
  return declared.get(name).flatMap((target) => resolve(target, next));
38
45
  }
39
46
 
40
- /** @type {Map<string, Set<string>>} */
41
- const tokens = new Map();
47
+ const colors = new Map();
48
+ const themed = new Set();
42
49
  for (const [name, values] of declared) {
43
50
  if (!COLOR_TOKEN.test(name)) continue;
44
- for (const color of values.flatMap((value) => resolve(value, new Set([name])))) {
45
- if (!tokens.has(color)) tokens.set(color, new Set());
46
- tokens.get(color).add(name);
51
+ const resolved = new Set();
52
+ for (const value of values.flatMap((value) => resolve(value, new Set([name])))) {
53
+ const color = normalizeHex(value);
54
+ // hex 가 아닌 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
55
+ const key = color ?? value;
56
+ if (resolved.has(key)) continue;
57
+ resolved.add(key);
58
+ if (!color) continue;
59
+ if (!colors.has(color)) colors.set(color, []);
60
+ colors.get(color).push(name);
47
61
  }
62
+ if (resolved.size > 1) themed.add(name);
48
63
  }
49
- return new Map([...tokens].map(([color, names]) => [color, [...names]]));
64
+ return { colors, themed };
50
65
  }