designsnitch 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js CHANGED
@@ -3,56 +3,44 @@ 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 } from "./config.js";
6
+ import { CONFIG_FILE, loadConfig, tokenSettings } 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;
46
- const result = await collectColors({ cwd, paths, tokens });
47
- return { stdout: format === "json" ? json(result) : formatColorsText(result), exitCode: 0 };
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 tokenFile = config ? path.resolve(config.root, tokenSettings(config.tokens).file) : undefined;
34
+ const result = await collectColors({ cwd, paths, tokens, tokenFile });
35
+ return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
48
36
  },
49
37
 
50
- hook({ cwd, configPath, stdin }) {
51
- return runHook({ cwd, input: stdin, configPath });
38
+ hook({ cwd, configPath, stdin, flagLang }) {
39
+ return runHook({ cwd, input: stdin, configPath, lang: flagLang });
52
40
  },
53
41
 
54
- install({ cwd }) {
55
- return install({ cwd });
42
+ install({ cwd, flagLang, agent }) {
43
+ return install({ cwd, lang: resolveLang(flagLang), agent });
56
44
  },
57
45
  };
58
46
 
@@ -71,24 +59,31 @@ export async function run(argv, { cwd, stdin, stdout, stderr }) {
71
59
  options: {
72
60
  format: { type: "string", default: "text" },
73
61
  config: { type: "string" },
62
+ lang: { type: "string" },
63
+ agent: { type: "string", default: "claude" },
74
64
  help: { type: "boolean", short: "h" },
75
65
  },
76
66
  });
77
67
  } catch (error) {
78
- stderr.write(`${error.message}\n\n${USAGE}`);
68
+ stderr.write(`${error.message}\n\n${messages().cliUsage}`);
79
69
  return 2;
80
70
  }
81
71
 
72
+ const flagLang = args.values.lang;
73
+ const usage = messages(resolveLang(flagLang)).cliUsage;
74
+
82
75
  if (args.values.help) {
83
- stdout.write(USAGE);
76
+ stdout.write(usage);
84
77
  return 0;
85
78
  }
86
79
 
87
80
  const [name, ...paths] = args.positionals;
88
81
  const command = Object.hasOwn(COMMANDS, name ?? "") ? COMMANDS[name] : undefined;
89
82
  const { format } = args.values;
90
- if (!command || !["text", "json"].includes(format)) {
91
- stderr.write(USAGE);
83
+ const validLang = flagLang === undefined || isLang(flagLang);
84
+ const { agent } = args.values;
85
+ if (!command || !["text", "json"].includes(format) || !validLang || !AGENT_CHOICES.includes(agent)) {
86
+ stderr.write(usage);
92
87
  return 2;
93
88
  }
94
89
 
@@ -100,6 +95,8 @@ export async function run(argv, { cwd, stdin, stdout, stderr }) {
100
95
  configPath: args.values.config,
101
96
  format,
102
97
  stdin,
98
+ flagLang,
99
+ agent,
103
100
  });
104
101
  } catch (error) {
105
102
  stderr.write(`${error.message}\n`);
package/src/colors.js CHANGED
@@ -61,6 +61,7 @@ const collectRule = {
61
61
  * @param {string} options.cwd 프로젝트 디렉터리
62
62
  * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
63
63
  * @param {Map<string, string[]>} [options.tokens] 색 값 → 토큰 이름들. 주면 색마다 tokens 를 붙인다
64
+ * @param {string} [options.tokenFile] 사용자 정의 속성 선언을 건너뛸 토큰 CSS 의 절대 경로
64
65
  * @returns {Promise<{
65
66
  * summary: { files: number, colors: number, paletteColors: number, uses: number },
66
67
  * colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
@@ -68,7 +69,7 @@ const collectRule = {
68
69
  * }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
69
70
  * literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
70
71
  */
71
- export async function collectColors({ cwd, paths = ["."], tokens }) {
72
+ export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
72
73
  const eslint = createEngine({
73
74
  cwd,
74
75
  // 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
@@ -92,9 +93,10 @@ export async function collectColors({ cwd, paths = ["."], tokens }) {
92
93
  }
93
94
  }
94
95
  for (const file of cssFiles) {
96
+ const absolute = path.resolve(cwd, file);
95
97
  let found;
96
98
  try {
97
- found = findCssColors(fs.readFileSync(path.resolve(cwd, file), "utf8"));
99
+ found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: absolute === tokenFile });
98
100
  } catch {
99
101
  continue; // 읽지 못한 CSS 는 건너뛴다
100
102
  }
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,91 @@ const EXAMPLE = `{
11
12
  }
12
13
  }`;
13
14
 
15
+ /** @typedef {string | string[] | { component: string | string[], when?: Record<string, (string | null)[]> }} Replacement */
16
+ /** @typedef {string | { file: string, exclude?: string[], prefer?: string[] }} TokenSettings */
17
+
18
+ /** @param {TokenSettings} tokens */
19
+ export function tokenSettings(tokens) {
20
+ return typeof tokens === "string" ? { file: tokens } : tokens;
21
+ }
22
+
23
+ export function invalidTokenField(tokens) {
24
+ if (typeof tokens === "string") return tokens.length > 0 ? null : "tokens";
25
+ if (!isRecord(tokens)) return "tokens";
26
+ if (typeof tokens.file !== "string" || tokens.file.length === 0) return "tokens.file";
27
+ if (tokens.exclude !== undefined && !isPatternList(tokens.exclude, /^[^*]*\*?$/)) return "tokens.exclude";
28
+ if (tokens.prefer !== undefined && !isPatternList(tokens.prefer, /^[^*]+$/)) return "tokens.prefer";
29
+ return null;
30
+ }
31
+
32
+ function isPatternList(values, pattern) {
33
+ return Array.isArray(values) &&
34
+ values.every((value) => typeof value === "string" && value.length > 0 && pattern.test(value));
35
+ }
36
+
37
+ /** @param {Replacement} [replacement] */
38
+ export function replacementNames(replacement) {
39
+ const component = typeof replacement === "string" || Array.isArray(replacement)
40
+ ? replacement
41
+ : replacement?.component;
42
+ return [component ?? []].flat();
43
+ }
44
+
14
45
  /**
15
46
  * 프로젝트의 설정 파일을 읽는다. 문제가 있으면 무엇을 고쳐야 하는지 담은 Error 를 던진다.
16
47
  * @param {string} cwd 프로젝트 디렉터리
17
48
  * @param {string} [configPath] cwd 기준 설정 파일 경로
18
- * @returns {{ tokens: string, components?: { path: string, replaces: Record<string, string | string[]> } }}
49
+ * @param {"en" | "ko"} [lang] 오류 문장의 언어
50
+ * @returns {{ tokens: TokenSettings, root: string, lang?: "en" | "ko", components?: { path: string, replaces: Record<string, Replacement> } }}
19
51
  */
20
- export function loadConfig(cwd, configPath = CONFIG_FILE) {
52
+ export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
53
+ const m = messages(lang);
21
54
  const file = path.resolve(cwd, configPath);
22
55
 
23
56
  let text;
24
57
  try {
25
58
  text = fs.readFileSync(file, "utf8");
26
59
  } catch {
27
- throw new Error(
28
- `설정 파일이 없습니다: ${file}\n` +
29
- `다음과 같은 내용으로 만드세요. designsnitch-setup 스킬을 따르면 저장소를 읽어서 만들 수 있습니다.\n${EXAMPLE}`,
30
- );
60
+ throw new Error(m.configMissing({ file, example: EXAMPLE }));
31
61
  }
32
62
 
33
63
  let config;
34
64
  try {
35
65
  config = JSON.parse(text);
36
66
  } catch (error) {
37
- throw new Error(`설정 파일을 읽을 수 없습니다: ${file}\n${error.message}`);
67
+ throw new Error(m.configUnreadable({ file, reason: error.message }));
38
68
  }
39
69
 
40
- if (typeof config?.tokens !== "string") {
41
- throw new Error(`설정 파일에 "tokens"(토큰 CSS 파일 경로)가 없습니다: ${file}`);
42
- }
43
- if (config.components !== undefined) validateComponents(config.components, file);
44
- return config;
70
+ const tokenField = invalidTokenField(config?.tokens);
71
+ if (tokenField === "tokens") throw new Error(m.configNoTokens({ file }));
72
+ if (tokenField) throw new Error(m.invalidTokenSetting({ field: tokenField, file }));
73
+ if (config.lang !== undefined && !isLang(config.lang)) throw new Error(m.configBadLang({ file }));
74
+ if (config.components !== undefined) validateComponents(config.components, file, m);
75
+ return { ...config, root: path.dirname(file) };
45
76
  }
46
77
 
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
- );
78
+ function validateComponents(components, file, m) {
79
+ if (typeof components?.path !== "string") throw new Error(m.configNoComponentsPath({ file }));
80
+ if (!isRecord(components.replaces)) {
81
+ throw new Error(m.configNoReplaces({ file }));
57
82
  }
58
83
  for (const [tag, value] of Object.entries(components.replaces)) {
59
- const names = [value].flat();
84
+ const conditional = isRecord(value);
85
+ const names = replacementNames(value);
60
86
  if (names.length === 0 || names.some((name) => typeof name !== "string" || name === "")) {
61
- throw new Error(
62
- `설정 파일의 "components.replaces.${tag}"는 컴포넌트 이름이거나 이름의 배열이어야 합니다: ${file}`,
63
- );
87
+ throw new Error(conditional ? m.configBadReplaceComponent({ tag, file }) : m.configBadReplace({ tag, file }));
88
+ }
89
+
90
+ if (!conditional || value.when === undefined) continue;
91
+ if (!isRecord(value.when)) throw new Error(m.configBadWhen({ tag, file }));
92
+ for (const [attribute, allowed] of Object.entries(value.when)) {
93
+ if (!Array.isArray(allowed) || allowed.some((entry) => entry !== null && typeof entry !== "string")) {
94
+ throw new Error(m.configBadWhenValues({ tag, attribute, file }));
95
+ }
64
96
  }
65
97
  }
66
98
  }
99
+
100
+ function isRecord(value) {
101
+ return value !== null && typeof value === "object" && !Array.isArray(value);
102
+ }
@@ -44,3 +44,15 @@ export function findPaletteClasses(text) {
44
44
  name: match[2],
45
45
  }));
46
46
  }
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
+ }
package/src/core/css.js CHANGED
@@ -7,13 +7,14 @@ const DISABLE_NEXT_LINE = "designsnitch-disable-next-line";
7
7
 
8
8
  /**
9
9
  * CSS 의 선언 값에서 hex 색을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
10
- * --로 시작하는 선언은 토큰이나 변수를 정의하는 곳이므로 건너뛴다.
10
+ * 토큰 CSS 에서는 옵션을 켜서 사용자 정의 속성 선언을 건너뛸 수 있다.
11
11
  * 바로 앞에 designsnitch-disable-next-line 주석이 있는 선언의 색은 disabled 로 표시한다.
12
12
  * @param {string} css
13
+ * @param {{ skipCustomProperties?: boolean }} [options]
13
14
  * @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop: string, disabled: boolean }[]}
14
15
  * @throws {import("postcss").CssSyntaxError} CSS 를 읽지 못했을 때
15
16
  */
16
- export function findCssColors(css) {
17
+ export function findCssColors(css, { skipCustomProperties = false } = {}) {
17
18
  const lineStarts = [0];
18
19
  for (let i = 0; i < css.length; i += 1) {
19
20
  if (css[i] === "\n") lineStarts.push(i + 1);
@@ -26,7 +27,7 @@ export function findCssColors(css) {
26
27
 
27
28
  const found = [];
28
29
  postcss.parse(css).walkDecls((decl) => {
29
- if (decl.prop.startsWith("--")) return;
30
+ if (skipCustomProperties && decl.prop.startsWith("--")) return;
30
31
 
31
32
  const previous = decl.prev();
32
33
  const disabled = previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
@@ -2,6 +2,11 @@ import postcss from "postcss";
2
2
  import { normalizeHex } from "./color.js";
3
3
 
4
4
  const COLOR_TOKEN = /^--color-/;
5
+ const ROLE_PREFIXES = {
6
+ text: ["--color-text-"],
7
+ border: ["--color-border-"],
8
+ bg: ["--color-bg-", "--color-surface", "--color-background"],
9
+ };
5
10
  // var(--name) 또는 var(--name, 대체값)
6
11
  const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
7
12
 
@@ -14,6 +19,16 @@ const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
14
19
  * @returns {Map<string, string[]>}
15
20
  */
16
21
  export function parseColorTokens(css) {
22
+ return parseColorTokenData(css).colors;
23
+ }
24
+
25
+ /**
26
+ * 색 값 → 토큰 표와 서로 다른 최종 값이 있는 토큰 이름을 함께 읽는다.
27
+ * @param {string} css
28
+ * @param {string[]} [exclude] 정확한 이름 또는 끝에 *가 붙은 이름 패턴
29
+ * @returns {{ colors: Map<string, string[]>, themed: Set<string> }}
30
+ */
31
+ export function parseColorTokenData(css, exclude = []) {
17
32
  /** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
18
33
  const declared = new Map();
19
34
  postcss.parse(css).walkDecls(/^--/, (decl) => {
@@ -22,13 +37,11 @@ export function parseColorTokens(css) {
22
37
  declared.set(decl.prop, values);
23
38
  });
24
39
 
25
- /** @returns {string[]} 값이 결국 가리키는 hex 색들 */
40
+ /** @returns {string[]} 값이 결국 가리키는 값들 */
26
41
  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 [];
42
+ const trimmed = value.trim();
43
+ const reference = VAR_REFERENCE.exec(trimmed);
44
+ if (!reference) return [trimmed];
32
45
  const [, name, fallback] = reference;
33
46
  if (visiting.has(name)) return [];
34
47
  if (!declared.has(name)) return fallback ? resolve(fallback, visiting) : [];
@@ -37,14 +50,55 @@ export function parseColorTokens(css) {
37
50
  return declared.get(name).flatMap((target) => resolve(target, next));
38
51
  }
39
52
 
40
- /** @type {Map<string, Set<string>>} */
41
- const tokens = new Map();
53
+ const colors = new Map();
54
+ const themed = new Set();
42
55
  for (const [name, values] of declared) {
43
56
  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);
57
+ if (exclude.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) continue;
58
+ const resolved = new Set();
59
+ for (const value of values.flatMap((value) => resolve(value, new Set([name])))) {
60
+ const color = normalizeHex(value);
61
+ // hex 가 아닌 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
62
+ const key = color ?? value;
63
+ if (resolved.has(key)) continue;
64
+ resolved.add(key);
65
+ if (!color) continue;
66
+ if (!colors.has(color)) colors.set(color, []);
67
+ colors.get(color).push(name);
47
68
  }
69
+ if (resolved.size > 1) themed.add(name);
48
70
  }
49
- return new Map([...tokens].map(([color, names]) => [color, [...names]]));
71
+ return { colors, themed };
72
+ }
73
+
74
+ export function utilityColorPrefixes(utility) {
75
+ const kind = utility.toLowerCase().split("-", 1)[0];
76
+ if (["border", "ring", "outline", "divide"].includes(kind)) return ROLE_PREFIXES.border;
77
+ return kind === "text" || kind === "bg" ? ROLE_PREFIXES[kind] : [];
78
+ }
79
+
80
+ export function cssColorPrefixes(property) {
81
+ const name = property.toLowerCase();
82
+ if (name === "color") return ROLE_PREFIXES.text;
83
+ if (name.startsWith("border")) return ROLE_PREFIXES.border;
84
+ if (name.startsWith("background")) return ROLE_PREFIXES.bg;
85
+ return [];
86
+ }
87
+
88
+ const startsWithAny = (name, prefixes) => prefixes.some((prefix) => name.startsWith(prefix));
89
+
90
+ export function selectColorTokens(names, prefer, rolePrefixes) {
91
+ const prefix = prefer.find((prefix) => names.some((name) => name.startsWith(prefix)));
92
+ if (prefix !== undefined) {
93
+ const preferred = names.filter((name) => name.startsWith(prefix));
94
+ if (preferred.length === 1) return preferred;
95
+ }
96
+
97
+ const matching = names.filter((name) => startsWithAny(name, rolePrefixes));
98
+ return [...matching, ...names.filter((name) => !startsWithAny(name, rolePrefixes))];
99
+ }
100
+
101
+ export function recommendColorCandidate(candidates, rolePrefixes) {
102
+ const matching = candidates.filter((candidate) => startsWithAny(candidate, rolePrefixes));
103
+ return matching.length === 1 ? matching[0] : null;
50
104
  }
package/src/format.js CHANGED
@@ -1,85 +1,73 @@
1
- const SEVERITY_LABELS = { error: "오류", warning: "경고" };
1
+ import { messages } from "./messages.js";
2
2
 
3
3
  /**
4
4
  * 검사 결과를 사람이 읽는 글로 만든다.
5
5
  * @param {Awaited<ReturnType<typeof import("./check.js").check>>} result
6
+ * @param {"en" | "ko"} [lang]
6
7
  */
7
- export function formatText({ designSystem, problems, summary, violations }) {
8
- const header = [
9
- describe(designSystem),
10
- ...problems.map((problem) => `주의: ${problem}`),
11
- "",
12
- ];
8
+ export function formatText({ designSystem, problems, summary, violations, decisions = [], unchecked }, lang) {
9
+ const m = messages(lang);
10
+ // 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
11
+ const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
12
+ const uncheckedLine = unchecked?.hexColors > 0 ? [m.unchecked(unchecked)] : [];
13
13
 
14
14
  if (violations.length === 0) {
15
- return [...header, `위반이 없습니다. (파일 ${summary.files}개 검사)`, ""].join("\n");
15
+ return [...header, m.noViolations(summary), ...uncheckedLine, ""].join("\n");
16
16
  }
17
17
 
18
- const byFile = Map.groupBy(violations, (violation) => violation.file);
18
+ const byFile = new Map();
19
+ for (const violation of violations) {
20
+ const { file } = violation;
21
+ if (!byFile.has(file)) byFile.set(file, []);
22
+ byFile.get(file).push(violation);
23
+ }
19
24
  const sections = [...byFile].map(([file, items]) =>
20
25
  [
21
26
  file,
22
27
  ...items.map(
23
28
  ({ line, column, severity, message, rule }) =>
24
- ` ${line}:${column} ${SEVERITY_LABELS[severity]} ${message} (${rule})`,
29
+ ` ${line}:${column} ${m.severity[severity]} ${message} (${rule})`,
25
30
  ),
26
31
  "",
27
32
  ].join("\n"),
28
33
  );
29
34
 
30
35
  const count = (action) => violations.filter((v) => v.action === action).length;
31
- const actions = [
32
- `바로 바꿀 수 있는 것 ${count("replace")}건`,
33
- `사람이 정해야 하는 것 ${count("ask")}건`,
34
- ...(count("repair") > 0 ? [`문법을 고쳐야 하는 것 ${count("repair")}건`] : []),
35
- ].join(", ");
36
-
37
36
  return [
38
37
  ...header,
39
38
  ...sections,
40
- `오류 ${summary.errors}개, 경고 ${summary.warnings}개 (파일 ${summary.files}개 검사)`,
41
- actions,
39
+ m.summary(summary),
40
+ m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
41
+ ...uncheckedLine,
42
42
  "",
43
43
  ].join("\n");
44
44
  }
45
45
 
46
- // 설정에서 무엇을 읽었는지 보여준다. 경로를 잘못 적으면 여기서 0개로 드러난다.
47
- function describe({ colorTokens, components }) {
48
- return [
49
- `디자인 시스템: 색 토큰 ${colorTokens}개`,
50
- components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음",
51
- ].join(", ");
52
- }
53
-
54
46
  /**
55
47
  * 색 수집 결과를 사람이 읽는 글로 만든다.
56
48
  * @param {Awaited<ReturnType<typeof import("./colors.js").collectColors>>} result
49
+ * @param {"en" | "ko"} [lang]
57
50
  */
58
- export function formatColorsText({ summary, colors, palette }) {
59
- if (colors.length === 0 && palette.length === 0) {
60
- return `코드에서 색을 찾지 못했습니다. (파일 ${summary.files}개 검사)\n`;
61
- }
51
+ export function formatColorsText({ summary, colors, palette }, lang) {
52
+ const m = messages(lang);
53
+ if (colors.length === 0 && palette.length === 0) return `${m.colorsNone(summary)}\n`;
62
54
 
63
55
  const usage = ({ uses, files, utilities, literals, properties = {} }) => {
64
56
  const where = Object.entries(utilities).map(([utility, count]) => `${utility} ${count}`);
65
- if (literals) where.push(`문자열 ${literals}`);
57
+ if (literals) where.push(m.literals(literals));
66
58
  const inCss = Object.values(properties).reduce((sum, count) => sum + count, 0);
67
- if (inCss) where.push(`CSS ${inCss}`);
68
- return `${uses}곳 파일 ${files}개 ${where.join(", ")}`;
59
+ if (inCss) where.push(m.css(inCss));
60
+ return `${m.usage({ uses, files })} ${where.join(", ")}`;
69
61
  };
70
62
  // 설정 파일이 있을 때만 tokens 가 붙는다.
71
- const tokenNote = ({ tokens }) =>
72
- tokens === undefined ? "" : tokens.length > 0 ? ` 토큰: ${tokens.join(", ")}` : " 토큰 없음";
63
+ const tokenNote = ({ tokens }) => (tokens === undefined ? "" : ` ${m.tokenNote(tokens)}`);
73
64
 
74
- const lines = [
75
- `코드에서 쓰는 색: hex ${summary.colors}개, 기본 팔레트 ${summary.paletteColors}개 (사용 ${summary.uses}곳, 파일 ${summary.files}개 검사)`,
76
- "",
77
- ];
65
+ const lines = [m.colorsSummary(summary), ""];
78
66
  if (colors.length > 0) {
79
- lines.push("hex 색", ...colors.map((c) => ` ${c.color} ${usage(c)}${tokenNote(c)}`), "");
67
+ lines.push(m.hexTitle, ...colors.map((c) => ` ${c.color} ${usage(c)}${tokenNote(c)}`), "");
80
68
  }
81
69
  if (palette.length > 0) {
82
- lines.push("Tailwind 기본 팔레트", ...palette.map((p) => ` ${p.name} ${usage(p)}`), "");
70
+ lines.push(m.paletteTitle, ...palette.map((p) => ` ${p.name} ${usage(p)}`), "");
83
71
  }
84
72
  return lines.join("\n");
85
73
  }