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/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,53 +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(`설정 파일이 없습니다: ${file}\n다음과 같은 내용으로 만드세요.\n${EXAMPLE}`);
40
+ throw new Error(m.configMissing({ file, example: EXAMPLE }));
28
41
  }
29
42
 
30
43
  let config;
31
44
  try {
32
45
  config = JSON.parse(text);
33
46
  } catch (error) {
34
- throw new Error(`설정 파일을 읽을 수 없습니다: ${file}\n${error.message}`);
47
+ throw new Error(m.configUnreadable({ file, reason: error.message }));
35
48
  }
36
49
 
37
- if (typeof config?.tokens !== "string") {
38
- throw new Error(`설정 파일에 "tokens"(토큰 CSS 파일 경로)가 없습니다: ${file}`);
39
- }
40
- 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);
41
53
  return config;
42
54
  }
43
55
 
44
- function validateComponents(components, file) {
45
- if (typeof components?.path !== "string") {
46
- throw new Error(
47
- `설정 파일의 "components.path"(디자인 시스템 컴포넌트 경로)가 없습니다: ${file}`,
48
- );
49
- }
50
- if (typeof components.replaces !== "object" || components.replaces === null) {
51
- throw new Error(
52
- `설정 파일의 "components.replaces"(raw 태그와 대체 컴포넌트)가 없습니다: ${file}`,
53
- );
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 }));
54
60
  }
55
61
  for (const [tag, value] of Object.entries(components.replaces)) {
56
- const names = [value].flat();
62
+ const conditional = isRecord(value);
63
+ const names = replacementNames(value);
57
64
  if (names.length === 0 || names.some((name) => typeof name !== "string" || name === "")) {
58
- throw new Error(
59
- `설정 파일의 "components.replaces.${tag}"는 컴포넌트 이름이거나 이름의 배열이어야 합니다: ${file}`,
60
- );
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
+ }
61
74
  }
62
75
  }
63
76
  }
77
+
78
+ function isRecord(value) {
79
+ return value !== null && typeof value === "object" && !Array.isArray(value);
80
+ }
@@ -1,5 +1,3 @@
1
- import { parseLength } from "./scale.js";
2
-
3
1
  // 예: bg-[#3B82F6], ring-offset-[#fff]
4
2
  const ARBITRARY_COLOR =
5
3
  /(?<![\w-])([a-z][a-z0-9]*(?:-[a-z0-9]+)*)-\[(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4}))\]/gi;
@@ -23,20 +21,26 @@ export function tokenToClass(utility, tokenName) {
23
21
  return `${utility}-${tokenName.replace(/^--color-/, "")}`;
24
22
  }
25
23
 
26
- // 예: p-[16px], rounded-t-[0.375rem]
27
- const ARBITRARY_LENGTH =
28
- /(?<![\w-])([a-z][a-z0-9]*(?:-[a-z0-9]+)*)-\[(\d*\.?\d+(?:px|rem))\]/gi;
24
+ const COLOR_UTILITY =
25
+ "bg|text|border(?:-[trblxyse])?|ring(?:-offset)?|outline|divide|fill|stroke|from|via|to|decoration|accent|caret|shadow|placeholder";
26
+ const PALETTE_HUE =
27
+ "slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose";
28
+ // 예: bg-blue-500, border-t-red-50, text-white
29
+ const PALETTE_CLASS = new RegExp(
30
+ `(?<![\\w-])(${COLOR_UTILITY})-((?:${PALETTE_HUE})-(?:50|[1-9]00|950)|black|white)(?![\\w-])`,
31
+ "g",
32
+ );
29
33
 
30
34
  /**
31
- * 문자열에서 px, rem 길이를 임의 값으로 쓴 Tailwind 클래스를 찾는다.
35
+ * 문자열에서 Tailwind 기본 팔레트 색을 쓴 클래스를 찾는다.
32
36
  * @param {string} text
33
- * @returns {{ index: number, text: string, utility: string, px: number }[]}
37
+ * @returns {{ index: number, text: string, utility: string, name: string }[]}
34
38
  */
35
- export function findArbitraryLengths(text) {
36
- return [...text.matchAll(ARBITRARY_LENGTH)].map((match) => ({
39
+ export function findPaletteClasses(text) {
40
+ return [...text.matchAll(PALETTE_CLASS)].map((match) => ({
37
41
  index: match.index,
38
42
  text: match[0],
39
43
  utility: match[1],
40
- px: parseLength(match[2]),
44
+ name: match[2],
41
45
  }));
42
46
  }
@@ -0,0 +1,54 @@
1
+ import postcss from "postcss";
2
+
3
+ const HEX_COLOR = /(?<![\w-])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
4
+ // 색이 아닌 # 이 들어갈 수 있는 곳: url(#id), "문자열", /* 주석 */
5
+ const NOT_A_VALUE = /url\([^)]*\)|"[^"]*"|'[^']*'|\/\*[\s\S]*?\*\//g;
6
+ const DISABLE_NEXT_LINE = "designsnitch-disable-next-line";
7
+
8
+ /**
9
+ * CSS 의 선언 값에서 hex 색을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
10
+ * --로 시작하는 선언은 토큰이나 변수를 정의하는 곳이므로 건너뛴다.
11
+ * 바로 앞에 designsnitch-disable-next-line 주석이 있는 선언의 색은 disabled 로 표시한다.
12
+ * @param {string} css
13
+ * @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop: string, disabled: boolean }[]}
14
+ * @throws {import("postcss").CssSyntaxError} CSS 를 읽지 못했을 때
15
+ */
16
+ export function findCssColors(css) {
17
+ const lineStarts = [0];
18
+ for (let i = 0; i < css.length; i += 1) {
19
+ if (css[i] === "\n") lineStarts.push(i + 1);
20
+ }
21
+ const position = (offset) => {
22
+ let line = lineStarts.length - 1;
23
+ while (lineStarts[line] > offset) line -= 1;
24
+ return { line: line + 1, column: offset - lineStarts[line] + 1 };
25
+ };
26
+
27
+ const found = [];
28
+ postcss.parse(css).walkDecls((decl) => {
29
+ if (decl.prop.startsWith("--")) return;
30
+
31
+ const previous = decl.prev();
32
+ const disabled = previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
33
+
34
+ // 위치를 정확히 잡으려고 정리된 값이 아니라 원본 텍스트에서 찾는다.
35
+ const raw = decl.raws.value?.raw ?? decl.value;
36
+ const valueStart = decl.source.start.offset + decl.prop.length + decl.raws.between.length;
37
+ const masked = raw.replace(NOT_A_VALUE, (skipped) => " ".repeat(skipped.length));
38
+
39
+ for (const match of masked.matchAll(HEX_COLOR)) {
40
+ const start = position(valueStart + match.index);
41
+ const end = position(valueStart + match.index + match[0].length);
42
+ found.push({
43
+ line: start.line,
44
+ column: start.column,
45
+ endLine: end.line,
46
+ endColumn: end.column,
47
+ value: match[0],
48
+ prop: decl.prop,
49
+ disabled,
50
+ });
51
+ }
52
+ });
53
+ return found;
54
+ }
@@ -1,6 +1,5 @@
1
1
  import postcss from "postcss";
2
2
  import { normalizeHex } from "./color.js";
3
- import { parseLength } from "./scale.js";
4
3
 
5
4
  const COLOR_TOKEN = /^--color-/;
6
5
  // var(--name) 또는 var(--name, 대체값)
@@ -15,6 +14,15 @@ const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
15
14
  * @returns {Map<string, string[]>}
16
15
  */
17
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) {
18
26
  /** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
19
27
  const declared = new Map();
20
28
  postcss.parse(css).walkDecls(/^--/, (decl) => {
@@ -23,13 +31,11 @@ export function parseColorTokens(css) {
23
31
  declared.set(decl.prop, values);
24
32
  });
25
33
 
26
- /** @returns {string[]} 값이 결국 가리키는 hex 색들 */
34
+ /** @returns {string[]} 값이 결국 가리키는 값들 */
27
35
  function resolve(value, visiting) {
28
- const color = normalizeHex(value);
29
- if (color) return [color];
30
-
31
- const reference = VAR_REFERENCE.exec(value.trim());
32
- if (!reference) return [];
36
+ const trimmed = value.trim();
37
+ const reference = VAR_REFERENCE.exec(trimmed);
38
+ if (!reference) return [trimmed];
33
39
  const [, name, fallback] = reference;
34
40
  if (visiting.has(name)) return [];
35
41
  if (!declared.has(name)) return fallback ? resolve(fallback, visiting) : [];
@@ -38,52 +44,22 @@ export function parseColorTokens(css) {
38
44
  return declared.get(name).flatMap((target) => resolve(target, next));
39
45
  }
40
46
 
41
- /** @type {Map<string, Set<string>>} */
42
- const tokens = new Map();
47
+ const colors = new Map();
48
+ const themed = new Set();
43
49
  for (const [name, values] of declared) {
44
50
  if (!COLOR_TOKEN.test(name)) continue;
45
- for (const color of values.flatMap((value) => resolve(value, new Set([name])))) {
46
- if (!tokens.has(color)) tokens.set(color, new Set());
47
- 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);
48
61
  }
62
+ if (resolved.size > 1) themed.add(name);
49
63
  }
50
- return new Map([...tokens].map(([color, names]) => [color, [...names]]));
51
- }
52
-
53
- const DEFAULT_SPACING = "0.25rem";
54
- // --text-sm--line-height 같은 부속 값은 제외한다.
55
- const RADIUS_TOKEN = /^--radius-(?!.*--)/;
56
- const TEXT_TOKEN = /^--text-(?!.*--)/;
57
-
58
- /**
59
- * 토큰 CSS에서 간격 단위와 radius, 폰트 크기 토큰을 px 값으로 읽는다.
60
- * @param {string} css
61
- * @returns {{ spacingUnit: number, radius: Map<number, string[]>, text: Map<number, string[]> }}
62
- */
63
- export function parseScaleTokens(css) {
64
- const scale = {
65
- spacingUnit: parseLength(DEFAULT_SPACING),
66
- radius: new Map(),
67
- text: new Map(),
68
- };
69
-
70
- postcss.parse(css).walkDecls((decl) => {
71
- const px = parseLength(decl.value);
72
- if (px === null) return;
73
-
74
- if (decl.prop === "--spacing") {
75
- scale.spacingUnit = px;
76
- return;
77
- }
78
- const tokens = RADIUS_TOKEN.test(decl.prop)
79
- ? scale.radius
80
- : TEXT_TOKEN.test(decl.prop)
81
- ? scale.text
82
- : null;
83
- if (!tokens) return;
84
- const names = tokens.get(px) ?? [];
85
- names.push(decl.prop);
86
- tokens.set(px, names);
87
- });
88
- return scale;
64
+ return { colors, themed };
89
65
  }
package/src/engine.js ADDED
@@ -0,0 +1,37 @@
1
+ import tsParser from "@typescript-eslint/parser";
2
+ import { ESLint } from "eslint";
3
+ import { IGNORED_DIRS } from "./files.js";
4
+
5
+ const FILES = ["**/*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}"];
6
+ const IGNORES = IGNORED_DIRS.map((dir) => `**/${dir}/**`);
7
+
8
+ /**
9
+ * 프로젝트의 소스 파일에 주어진 규칙만 실행하는 ESLint 를 만든다.
10
+ * 프로젝트 자신의 ESLint 설정은 쓰지 않는다.
11
+ * @param {object} options
12
+ * @param {string} options.cwd 프로젝트 디렉터리
13
+ * @param {import("eslint").Linter.Config} options.config plugins, rules, settings
14
+ * @param {boolean} [options.allowInlineConfig] false 면 eslint-disable 같은 주석을 무시한다
15
+ */
16
+ export function createEngine({ cwd, config, allowInlineConfig = true }) {
17
+ return new ESLint({
18
+ cwd,
19
+ overrideConfigFile: true,
20
+ errorOnUnmatchedPattern: false,
21
+ allowInlineConfig,
22
+ overrideConfig: [
23
+ { ignores: IGNORES },
24
+ {
25
+ ...config,
26
+ files: FILES,
27
+ languageOptions: {
28
+ parser: tsParser,
29
+ parserOptions: { ecmaFeatures: { jsx: true } },
30
+ },
31
+ // 프로젝트 코드에는 다른 규칙용 eslint-disable 주석이 있을 수 있다.
32
+ linterOptions: { reportUnusedDisableDirectives: "off" },
33
+ },
34
+ ],
35
+ });
36
+ }
37
+
package/src/files.js ADDED
@@ -0,0 +1,46 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /** 검사하지 않는 디렉터리 이름. JS 와 CSS 에 똑같이 적용한다. */
5
+ export const IGNORED_DIRS = ["node_modules", ".git", ".next", "dist", "build", "out", "coverage"];
6
+
7
+ /**
8
+ * 검사할 경로를 스크립트용(ESLint 에 넘길 것)과 CSS 파일 목록으로 나눈다.
9
+ * 디렉터리는 양쪽 모두에 해당하고, .css 파일은 CSS 쪽에만 해당한다.
10
+ * @param {string} cwd
11
+ * @param {string[]} paths cwd 기준 경로
12
+ * @returns {{ scriptPaths: string[], cssFiles: string[] }} cssFiles 는 cwd 기준의 슬래시 경로, 이름순
13
+ */
14
+ export function splitPaths(cwd, paths) {
15
+ const scriptPaths = [];
16
+ const cssFiles = new Set();
17
+
18
+ for (const given of paths) {
19
+ const absolute = path.resolve(cwd, given);
20
+ const stat = fs.statSync(absolute, { throwIfNoEntry: false });
21
+ if (stat?.isDirectory()) {
22
+ scriptPaths.push(given);
23
+ for (const file of walkCss(absolute)) cssFiles.add(toRelative(cwd, file));
24
+ } else if (absolute.endsWith(".css")) {
25
+ if (stat) cssFiles.add(toRelative(cwd, absolute));
26
+ } else {
27
+ scriptPaths.push(given);
28
+ }
29
+ }
30
+ return { scriptPaths, cssFiles: [...cssFiles].sort((a, b) => a.localeCompare(b)) };
31
+ }
32
+
33
+ function* walkCss(dir) {
34
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
35
+ const full = path.join(dir, entry.name);
36
+ if (entry.isDirectory()) {
37
+ if (!IGNORED_DIRS.includes(entry.name)) yield* walkCss(full);
38
+ } else if (entry.name.endsWith(".css")) {
39
+ yield full;
40
+ }
41
+ }
42
+ }
43
+
44
+ function toRelative(cwd, file) {
45
+ return path.relative(cwd, file).split(path.sep).join("/");
46
+ }
package/src/format.js CHANGED
@@ -1,46 +1,71 @@
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 }, lang) {
9
+ const m = messages(lang);
10
+ // 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
11
+ const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
13
12
 
14
13
  if (violations.length === 0) {
15
- return [...header, `위반이 없습니다. (파일 ${summary.files}개 검사)`, ""].join("\n");
14
+ return [...header, m.noViolations(summary), ""].join("\n");
16
15
  }
17
16
 
18
- const byFile = Map.groupBy(violations, (violation) => violation.file);
17
+ const byFile = new Map();
18
+ for (const violation of violations) {
19
+ const { file } = violation;
20
+ if (!byFile.has(file)) byFile.set(file, []);
21
+ byFile.get(file).push(violation);
22
+ }
19
23
  const sections = [...byFile].map(([file, items]) =>
20
24
  [
21
25
  file,
22
26
  ...items.map(
23
27
  ({ line, column, severity, message, rule }) =>
24
- ` ${line}:${column} ${SEVERITY_LABELS[severity]} ${message} (${rule})`,
28
+ ` ${line}:${column} ${m.severity[severity]} ${message} (${rule})`,
25
29
  ),
26
30
  "",
27
31
  ].join("\n"),
28
32
  );
29
33
 
34
+ const count = (action) => violations.filter((v) => v.action === action).length;
30
35
  return [
31
36
  ...header,
32
37
  ...sections,
33
- `오류 ${summary.errors}개, 경고 ${summary.warnings}개 (파일 ${summary.files}개 검사)`,
38
+ m.summary(summary),
39
+ m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair") }),
34
40
  "",
35
41
  ].join("\n");
36
42
  }
37
43
 
38
- // 설정에서 무엇을 읽었는지 보여준다. 경로를 잘못 적으면 여기서 0개로 드러난다.
39
- function describe({ colorTokens, radiusTokens, textTokens, components }) {
40
- return [
41
- `디자인 시스템: 색 토큰 ${colorTokens}개`,
42
- `radius 토큰 ${radiusTokens}개`,
43
- `폰트 크기 토큰 ${textTokens}개`,
44
- components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음",
45
- ].join(", ");
44
+ /**
45
+ * 색 수집 결과를 사람이 읽는 글로 만든다.
46
+ * @param {Awaited<ReturnType<typeof import("./colors.js").collectColors>>} result
47
+ * @param {"en" | "ko"} [lang]
48
+ */
49
+ export function formatColorsText({ summary, colors, palette }, lang) {
50
+ const m = messages(lang);
51
+ if (colors.length === 0 && palette.length === 0) return `${m.colorsNone(summary)}\n`;
52
+
53
+ const usage = ({ uses, files, utilities, literals, properties = {} }) => {
54
+ const where = Object.entries(utilities).map(([utility, count]) => `${utility} ${count}`);
55
+ if (literals) where.push(m.literals(literals));
56
+ const inCss = Object.values(properties).reduce((sum, count) => sum + count, 0);
57
+ if (inCss) where.push(m.css(inCss));
58
+ return `${m.usage({ uses, files })} ${where.join(", ")}`;
59
+ };
60
+ // 설정 파일이 있을 때만 tokens 가 붙는다.
61
+ const tokenNote = ({ tokens }) => (tokens === undefined ? "" : ` ${m.tokenNote(tokens)}`);
62
+
63
+ const lines = [m.colorsSummary(summary), ""];
64
+ if (colors.length > 0) {
65
+ lines.push(m.hexTitle, ...colors.map((c) => ` ${c.color} ${usage(c)}${tokenNote(c)}`), "");
66
+ }
67
+ if (palette.length > 0) {
68
+ lines.push(m.paletteTitle, ...palette.map((p) => ` ${p.name} ${usage(p)}`), "");
69
+ }
70
+ return lines.join("\n");
46
71
  }
package/src/hook.js ADDED
@@ -0,0 +1,163 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { check, nextSteps } from "./check.js";
6
+ import { CONFIG_FILE, loadConfig } from "./config.js";
7
+ import { messages, resolveLang } from "./messages.js";
8
+
9
+ const CHECKABLE = /\.(?:[cm]?[jt]s|[jt]sx|css)$/;
10
+ // Claude Code, Codex 는 Stop, Gemini CLI 는 AfterAgent 가 "작업을 끝내려 할 때"다.
11
+ const STOP_EVENTS = new Set(["Stop", "SubagentStop", "AfterAgent"]);
12
+
13
+ /**
14
+ * 코딩 에이전트의 훅에서 부르는 검사. 에이전트가 방금 고친 파일만 본다.
15
+ *
16
+ * - 파일을 고친 직후: HEAD 대비 새 오류가 있으면 종료 코드 2와 함께 stderr 로 알린다.
17
+ * - 작업을 끝내려 할 때(Stop): 에이전트가 스스로 고칠 수 있는 새 오류가 남아 있으면 2로 막는다.
18
+ * 사람이 정해야 하는 오류만 남았으면 막지 않는다. 물어보려면 멈춰야 하기 때문이다.
19
+ * - 경고는 막지 않는다. 설정 파일이 없는 프로젝트에서는 아무것도 하지 않는다.
20
+ *
21
+ * @param {object} options
22
+ * @param {string} options.cwd 프로젝트 디렉터리
23
+ * @param {string} [options.input] 훅이 stdin 으로 준 JSON. 비어 있거나 JSON 이 아니어도 된다
24
+ * @param {string} [options.configPath]
25
+ * @param {"en" | "ko"} [options.lang] 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
26
+ * @returns {Promise<{ stderr: string, exitCode: 0 | 2 }>}
27
+ */
28
+ export async function runHook({ cwd, input = "", configPath = CONFIG_FILE, lang }) {
29
+ const pass = { stderr: "", exitCode: 0 };
30
+ const event = parse(input);
31
+ // Claude Code, Codex, Gemini CLI 는 snake_case, Grok Build 는 camelCase 로 보낸다.
32
+ const eventName = event.hook_event_name ?? event.hookEventName;
33
+ const toolInput = event.tool_input ?? event.toolInput;
34
+ const stopping = STOP_EVENTS.has(eventName);
35
+
36
+ // 이미 한 번 막아서 에이전트가 고치는 중이면 다시 막지 않는다.
37
+ if (stopping && (event.stop_hook_active ?? event.stopHookActive)) return pass;
38
+ if (!fs.existsSync(path.resolve(cwd, configPath))) return pass;
39
+
40
+ const edited = toolInput?.file_path ?? toolInput?.filePath;
41
+ const files = (typeof edited === "string" ? [edited] : changedFiles(cwd))
42
+ .map((file) => path.resolve(cwd, file))
43
+ .filter((file) => isInside(cwd, file) && CHECKABLE.test(file) && fs.existsSync(file))
44
+ .map((file) => path.relative(cwd, file));
45
+ if (files.length === 0) return pass;
46
+
47
+ const canBlock = (v) => v.severity === "error" && (!stopping || v.action !== "ask");
48
+ let result;
49
+ let errors;
50
+ try {
51
+ const config = loadConfig(cwd, configPath, resolveLang(lang));
52
+ lang = resolveLang(lang, config.lang);
53
+ result = await check({ cwd, config, paths: files, lang });
54
+ if (!result.violations.some(canBlock)) return pass;
55
+
56
+ const baseline = countViolations(await checkHead({ cwd, config, files, lang }));
57
+ const current = countViolations(result.violations);
58
+ errors = result.violations.filter((v) => {
59
+ const key = violationKey(v);
60
+ return v.severity === "error" && current.get(key) > (baseline.get(key) ?? 0);
61
+ });
62
+ } catch (error) {
63
+ return { stderr: `${error.message}\n`, exitCode: 2 };
64
+ }
65
+
66
+ if (!errors.some(canBlock)) return pass;
67
+
68
+ const m = messages(lang);
69
+ const lines = [
70
+ m.hookHeader(errors.length),
71
+ "",
72
+ ...errors.map((v) => `${v.file}:${v.line}:${v.column} ${v.message} [${v.action}]`),
73
+ "",
74
+ m.nextTitle,
75
+ ...nextSteps(result.designSystem, errors, lang).map((step) => `- ${step}`),
76
+ "",
77
+ ];
78
+ return { stderr: lines.join("\n"), exitCode: 2 };
79
+ }
80
+
81
+ async function checkHead({ cwd, config, files, lang }) {
82
+ let temp;
83
+ const paths = [];
84
+ try {
85
+ for (const file of files) {
86
+ const gitPath = file.split(path.sep).join("/");
87
+ // HEAD 나 파일이 없으면 기준선에 위반이 없다.
88
+ const source = gitOutput(cwd, ["show", `HEAD:./${gitPath}`], { maxBuffer: Infinity });
89
+ if (source === undefined) continue;
90
+
91
+ temp ??= fs.mkdtempSync(path.join(os.tmpdir(), "designsnitch-head-"));
92
+ const target = path.join(temp, file);
93
+ fs.mkdirSync(path.dirname(target), { recursive: true });
94
+ fs.writeFileSync(target, source);
95
+ paths.push(file);
96
+ }
97
+ if (paths.length === 0) return [];
98
+
99
+ const baselineConfig = { ...config, tokens: path.resolve(cwd, config.tokens) };
100
+ if (config.components) {
101
+ baselineConfig.components = { ...config.components, path: path.resolve(cwd, config.components.path) };
102
+ }
103
+ const result = await check({ cwd: temp, config: baselineConfig, paths, lang });
104
+ return result.violations;
105
+ } finally {
106
+ if (temp) fs.rmSync(temp, { recursive: true, force: true });
107
+ }
108
+ }
109
+
110
+ function violationKey({ file, rule, found }) {
111
+ return JSON.stringify([file, rule, found]);
112
+ }
113
+
114
+ function countViolations(violations) {
115
+ const counts = new Map();
116
+ for (const violation of violations) {
117
+ const key = violationKey(violation);
118
+ counts.set(key, (counts.get(key) ?? 0) + 1);
119
+ }
120
+ return counts;
121
+ }
122
+
123
+ function parse(input) {
124
+ try {
125
+ const value = JSON.parse(input);
126
+ return value && typeof value === "object" ? value : {};
127
+ } catch {
128
+ return {};
129
+ }
130
+ }
131
+
132
+ function isInside(cwd, file) {
133
+ const relative = path.relative(cwd, file);
134
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
135
+ }
136
+
137
+ function gitOutput(cwd, args, options) {
138
+ try {
139
+ return execFileSync("git", args, {
140
+ cwd,
141
+ stdio: ["ignore", "pipe", "ignore"],
142
+ ...options,
143
+ });
144
+ } catch {
145
+ return undefined;
146
+ }
147
+ }
148
+
149
+ /** git 작업 폴더에서 바뀌었거나 새로 생긴 파일. git 저장소가 아니면 빈 배열. */
150
+ function changedFiles(cwd) {
151
+ const output = gitOutput(cwd, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { encoding: "utf8" });
152
+ if (!output) return [];
153
+ const files = [];
154
+ const entries = output.split("\0").filter(Boolean);
155
+ for (let i = 0; i < entries.length; i += 1) {
156
+ const status = entries[i].slice(0, 2);
157
+ const file = entries[i].slice(3);
158
+ // 이름이 바뀐 항목은 바로 다음에 예전 경로가 따라온다.
159
+ if (status[0] === "R" || status[0] === "C") i += 1;
160
+ if (!status.includes("D")) files.push(file);
161
+ }
162
+ return files;
163
+ }
package/src/index.js CHANGED
@@ -1,16 +1,15 @@
1
+ import { createRequire } from "node:module";
1
2
  import colorUnknown from "./rules/color-unknown.js";
2
3
  import colorUseToken from "./rules/color-use-token.js";
3
- import scaleUnknown from "./rules/scale-unknown.js";
4
- import scaleUseToken from "./rules/scale-use-token.js";
5
4
  import useDsComponent from "./rules/use-ds-component.js";
6
5
 
6
+ const { version } = createRequire(import.meta.url)("../package.json");
7
+
7
8
  const plugin = {
8
- meta: { name: "designsnitch", version: "0.1.0" },
9
+ meta: { name: "designsnitch", version },
9
10
  rules: {
10
11
  "color-use-token": colorUseToken,
11
12
  "color-unknown": colorUnknown,
12
- "scale-use-token": scaleUseToken,
13
- "scale-unknown": scaleUnknown,
14
13
  "use-ds-component": useDsComponent,
15
14
  },
16
15
  configs: {},
@@ -23,8 +22,6 @@ plugin.configs.recommended = {
23
22
  rules: {
24
23
  "designsnitch/color-use-token": "error",
25
24
  "designsnitch/color-unknown": "warn",
26
- "designsnitch/scale-use-token": "error",
27
- "designsnitch/scale-unknown": "warn",
28
25
  "designsnitch/use-ds-component": "error",
29
26
  },
30
27
  };