designsnitch 0.1.0 → 0.2.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 +426 -0
- package/README.md +289 -242
- package/bin/designsnitch.js +27 -1
- package/package.json +1 -1
- package/skills/designsnitch-check/SKILL.md +107 -0
- package/skills/designsnitch-eslint/SKILL.md +128 -0
- package/skills/designsnitch-hooks/SKILL.md +90 -0
- package/skills/designsnitch-palette/SKILL.md +140 -0
- package/skills/designsnitch-setup/SKILL.md +107 -0
- package/src/check.js +116 -32
- package/src/cli.js +64 -19
- package/src/colors.js +166 -0
- package/src/config.js +4 -1
- package/src/core/classes.js +14 -10
- package/src/core/css.js +54 -0
- package/src/core/tokens.js +0 -39
- package/src/engine.js +37 -0
- package/src/files.js +46 -0
- package/src/format.js +42 -3
- package/src/hook.js +100 -0
- package/src/index.js +4 -7
- package/src/install.js +95 -0
- package/src/rules/load-tokens.js +11 -4
- 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
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
|
@@ -27,20 +27,59 @@ export function formatText({ designSystem, problems, summary, violations }) {
|
|
|
27
27
|
].join("\n"),
|
|
28
28
|
);
|
|
29
29
|
|
|
30
|
+
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
|
+
|
|
30
37
|
return [
|
|
31
38
|
...header,
|
|
32
39
|
...sections,
|
|
33
40
|
`오류 ${summary.errors}개, 경고 ${summary.warnings}개 (파일 ${summary.files}개 검사)`,
|
|
41
|
+
actions,
|
|
34
42
|
"",
|
|
35
43
|
].join("\n");
|
|
36
44
|
}
|
|
37
45
|
|
|
38
46
|
// 설정에서 무엇을 읽었는지 보여준다. 경로를 잘못 적으면 여기서 0개로 드러난다.
|
|
39
|
-
function describe({ colorTokens,
|
|
47
|
+
function describe({ colorTokens, components }) {
|
|
40
48
|
return [
|
|
41
49
|
`디자인 시스템: 색 토큰 ${colorTokens}개`,
|
|
42
|
-
`radius 토큰 ${radiusTokens}개`,
|
|
43
|
-
`폰트 크기 토큰 ${textTokens}개`,
|
|
44
50
|
components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음",
|
|
45
51
|
].join(", ");
|
|
46
52
|
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 색 수집 결과를 사람이 읽는 글로 만든다.
|
|
56
|
+
* @param {Awaited<ReturnType<typeof import("./colors.js").collectColors>>} result
|
|
57
|
+
*/
|
|
58
|
+
export function formatColorsText({ summary, colors, palette }) {
|
|
59
|
+
if (colors.length === 0 && palette.length === 0) {
|
|
60
|
+
return `코드에서 색을 찾지 못했습니다. (파일 ${summary.files}개 검사)\n`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const usage = ({ uses, files, utilities, literals, properties = {} }) => {
|
|
64
|
+
const where = Object.entries(utilities).map(([utility, count]) => `${utility} ${count}`);
|
|
65
|
+
if (literals) where.push(`문자열 ${literals}`);
|
|
66
|
+
const inCss = Object.values(properties).reduce((sum, count) => sum + count, 0);
|
|
67
|
+
if (inCss) where.push(`CSS ${inCss}`);
|
|
68
|
+
return `${uses}곳 파일 ${files}개 ${where.join(", ")}`;
|
|
69
|
+
};
|
|
70
|
+
// 설정 파일이 있을 때만 tokens 가 붙는다.
|
|
71
|
+
const tokenNote = ({ tokens }) =>
|
|
72
|
+
tokens === undefined ? "" : tokens.length > 0 ? ` 토큰: ${tokens.join(", ")}` : " 토큰 없음";
|
|
73
|
+
|
|
74
|
+
const lines = [
|
|
75
|
+
`코드에서 쓰는 색: hex ${summary.colors}개, 기본 팔레트 ${summary.paletteColors}개 (사용 ${summary.uses}곳, 파일 ${summary.files}개 검사)`,
|
|
76
|
+
"",
|
|
77
|
+
];
|
|
78
|
+
if (colors.length > 0) {
|
|
79
|
+
lines.push("hex 색", ...colors.map((c) => ` ${c.color} ${usage(c)}${tokenNote(c)}`), "");
|
|
80
|
+
}
|
|
81
|
+
if (palette.length > 0) {
|
|
82
|
+
lines.push("Tailwind 기본 팔레트", ...palette.map((p) => ` ${p.name} ${usage(p)}`), "");
|
|
83
|
+
}
|
|
84
|
+
return lines.join("\n");
|
|
85
|
+
}
|
package/src/hook.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { check, nextSteps } from "./check.js";
|
|
5
|
+
import { CONFIG_FILE, loadConfig } from "./config.js";
|
|
6
|
+
|
|
7
|
+
const CHECKABLE = /\.(?:[cm]?[jt]s|[jt]sx|css)$/;
|
|
8
|
+
const STOP_EVENTS = new Set(["Stop", "SubagentStop"]);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 코딩 에이전트의 훅에서 부르는 검사. 에이전트가 방금 고친 파일만 본다.
|
|
12
|
+
*
|
|
13
|
+
* - 파일을 고친 직후: 그 파일에 오류가 있으면 종료 코드 2와 함께 stderr 로 알린다.
|
|
14
|
+
* - 작업을 끝내려 할 때(Stop): 에이전트가 스스로 고칠 수 있는 오류가 남아 있으면 2로 막는다.
|
|
15
|
+
* 사람이 정해야 하는 오류만 남았으면 막지 않는다. 물어보려면 멈춰야 하기 때문이다.
|
|
16
|
+
* - 경고는 막지 않는다. 설정 파일이 없는 프로젝트에서는 아무것도 하지 않는다.
|
|
17
|
+
*
|
|
18
|
+
* @param {object} options
|
|
19
|
+
* @param {string} options.cwd 프로젝트 디렉터리
|
|
20
|
+
* @param {string} [options.input] 훅이 stdin 으로 준 JSON. 비어 있거나 JSON 이 아니어도 된다
|
|
21
|
+
* @param {string} [options.configPath]
|
|
22
|
+
* @returns {Promise<{ stderr: string, exitCode: 0 | 2 }>}
|
|
23
|
+
*/
|
|
24
|
+
export async function runHook({ cwd, input = "", configPath = CONFIG_FILE }) {
|
|
25
|
+
const pass = { stderr: "", exitCode: 0 };
|
|
26
|
+
const event = parse(input);
|
|
27
|
+
const stopping = STOP_EVENTS.has(event.hook_event_name);
|
|
28
|
+
|
|
29
|
+
// 이미 한 번 막아서 에이전트가 고치는 중이면 다시 막지 않는다.
|
|
30
|
+
if (stopping && event.stop_hook_active) return pass;
|
|
31
|
+
if (!fs.existsSync(path.resolve(cwd, configPath))) return pass;
|
|
32
|
+
|
|
33
|
+
const edited = event.tool_input?.file_path;
|
|
34
|
+
const files = (typeof edited === "string" ? [edited] : changedFiles(cwd))
|
|
35
|
+
.map((file) => path.resolve(cwd, file))
|
|
36
|
+
.filter((file) => isInside(cwd, file) && CHECKABLE.test(file) && fs.existsSync(file))
|
|
37
|
+
.map((file) => path.relative(cwd, file));
|
|
38
|
+
if (files.length === 0) return pass;
|
|
39
|
+
|
|
40
|
+
let result;
|
|
41
|
+
try {
|
|
42
|
+
result = await check({ cwd, config: loadConfig(cwd, configPath), paths: files });
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return { stderr: `${error.message}\n`, exitCode: 2 };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const errors = result.violations.filter((v) => v.severity === "error");
|
|
48
|
+
const blocking = stopping ? errors.filter((v) => v.action !== "ask") : errors;
|
|
49
|
+
if (blocking.length === 0) return pass;
|
|
50
|
+
|
|
51
|
+
const lines = [
|
|
52
|
+
`designsnitch: 방금 고친 파일에 디자인 시스템 오류가 ${errors.length}건 있습니다.`,
|
|
53
|
+
"",
|
|
54
|
+
...errors.map((v) => `${v.file}:${v.line}:${v.column} ${v.message} [${v.action}]`),
|
|
55
|
+
"",
|
|
56
|
+
"다음에 할 일",
|
|
57
|
+
...nextSteps(result.designSystem, errors).map((step) => `- ${step}`),
|
|
58
|
+
"",
|
|
59
|
+
];
|
|
60
|
+
return { stderr: lines.join("\n"), exitCode: 2 };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parse(input) {
|
|
64
|
+
try {
|
|
65
|
+
const value = JSON.parse(input);
|
|
66
|
+
return value && typeof value === "object" ? value : {};
|
|
67
|
+
} catch {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isInside(cwd, file) {
|
|
73
|
+
const relative = path.relative(cwd, file);
|
|
74
|
+
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** git 작업 폴더에서 바뀌었거나 새로 생긴 파일. git 저장소가 아니면 빈 배열. */
|
|
78
|
+
function changedFiles(cwd) {
|
|
79
|
+
let output;
|
|
80
|
+
try {
|
|
81
|
+
output = execFileSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], {
|
|
82
|
+
cwd,
|
|
83
|
+
encoding: "utf8",
|
|
84
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
85
|
+
});
|
|
86
|
+
} catch {
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const files = [];
|
|
91
|
+
const entries = output.split("\0").filter(Boolean);
|
|
92
|
+
for (let i = 0; i < entries.length; i += 1) {
|
|
93
|
+
const status = entries[i].slice(0, 2);
|
|
94
|
+
const file = entries[i].slice(3);
|
|
95
|
+
// 이름이 바뀐 항목은 바로 다음에 예전 경로가 따라온다.
|
|
96
|
+
if (status[0] === "R" || status[0] === "C") i += 1;
|
|
97
|
+
if (!status.includes("D")) files.push(file);
|
|
98
|
+
}
|
|
99
|
+
return files;
|
|
100
|
+
}
|
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
|
|
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
|
};
|
package/src/install.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { CONFIG_FILE } from "./config.js";
|
|
5
|
+
|
|
6
|
+
const SKILLS_DIR = fileURLToPath(new URL("../skills", import.meta.url));
|
|
7
|
+
const SETTINGS_FILE = ".claude/settings.json";
|
|
8
|
+
const HOOK_COMMAND = "npx designsnitch hook";
|
|
9
|
+
// 파일을 고친 직후와 작업을 끝내려 할 때 훅을 실행한다.
|
|
10
|
+
const HOOK_ENTRIES = {
|
|
11
|
+
PostToolUse: { matcher: "Edit|Write|MultiEdit", hooks: [{ type: "command", command: HOOK_COMMAND }] },
|
|
12
|
+
Stop: { hooks: [{ type: "command", command: HOOK_COMMAND }] },
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 프로젝트에 스킬과 에이전트 훅을 설치한다. Claude Code 의 위치(.claude)에 맞춘다.
|
|
17
|
+
* 여러 번 실행해도 된다. 스킬은 최신으로 덮어쓰고, 훅은 없을 때만 더한다.
|
|
18
|
+
* @param {{ cwd: string }} options
|
|
19
|
+
* @returns {{ stdout: string, exitCode: 0 }}
|
|
20
|
+
* @throws {Error} .claude/settings.json 을 읽을 수 없을 때. 이때는 아무것도 바꾸지 않는다
|
|
21
|
+
*/
|
|
22
|
+
export function install({ cwd }) {
|
|
23
|
+
const settingsPath = path.join(cwd, SETTINGS_FILE);
|
|
24
|
+
// 설정 파일이 깨져 있으면 아무것도 건드리기 전에 멈춘다.
|
|
25
|
+
const settings = readSettings(settingsPath);
|
|
26
|
+
|
|
27
|
+
const skills = fs.readdirSync(SKILLS_DIR).filter((name) => !name.startsWith("."));
|
|
28
|
+
for (const skill of skills) {
|
|
29
|
+
fs.cpSync(path.join(SKILLS_DIR, skill), path.join(cwd, ".claude/skills", skill), { recursive: true });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const added = addHooks(settings);
|
|
33
|
+
if (added) {
|
|
34
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
35
|
+
fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const steps = [];
|
|
39
|
+
if (!isInstalled(cwd)) {
|
|
40
|
+
steps.push("훅이 매번 빠르게 돌도록 프로젝트에 설치하세요: npm install --save-dev designsnitch");
|
|
41
|
+
}
|
|
42
|
+
if (!fs.existsSync(path.join(cwd, CONFIG_FILE))) {
|
|
43
|
+
steps.push(
|
|
44
|
+
`코딩 에이전트에게 "이 프로젝트에 designsnitch를 설정해 줘"라고 요청하세요. 토큰 CSS와 공용 컴포넌트를 찾아 ${CONFIG_FILE} 을 만들고 ESLint에 규칙을 넣습니다.`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const lines = [
|
|
49
|
+
`스킬 ${skills.length}개를 .claude/skills 에 복사했습니다.`,
|
|
50
|
+
added
|
|
51
|
+
? `훅을 ${SETTINGS_FILE} 에 등록했습니다.`
|
|
52
|
+
: `훅은 이미 ${SETTINGS_FILE} 에 등록되어 있습니다.`,
|
|
53
|
+
...(steps.length > 0 ? ["", "다음에 할 일", ...steps.map((step) => `- ${step}`)] : []),
|
|
54
|
+
"",
|
|
55
|
+
];
|
|
56
|
+
return { stdout: lines.join("\n"), exitCode: 0 };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readSettings(file) {
|
|
60
|
+
if (!fs.existsSync(file)) return {};
|
|
61
|
+
try {
|
|
62
|
+
const settings = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
63
|
+
if (settings && typeof settings === "object" && !Array.isArray(settings)) return settings;
|
|
64
|
+
} catch {
|
|
65
|
+
// 아래에서 같은 오류로 알린다.
|
|
66
|
+
}
|
|
67
|
+
throw new Error(`${file} 을 읽을 수 없습니다. JSON 형식을 고친 뒤 다시 실행하세요.`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 훅이 없는 이벤트에만 더한다. 하나라도 더했으면 true. */
|
|
71
|
+
function addHooks(settings) {
|
|
72
|
+
settings.hooks ??= {};
|
|
73
|
+
let added = false;
|
|
74
|
+
for (const [event, entry] of Object.entries(HOOK_ENTRIES)) {
|
|
75
|
+
const entries = (settings.hooks[event] ??= []);
|
|
76
|
+
const registered = entries.some((existing) =>
|
|
77
|
+
existing.hooks?.some((hook) => hook.command?.includes("designsnitch hook")),
|
|
78
|
+
);
|
|
79
|
+
if (!registered) {
|
|
80
|
+
entries.push(structuredClone(entry));
|
|
81
|
+
added = true;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return added;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function isInstalled(cwd) {
|
|
88
|
+
if (fs.existsSync(path.join(cwd, "node_modules/designsnitch"))) return true;
|
|
89
|
+
try {
|
|
90
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
|
|
91
|
+
return Boolean(pkg.dependencies?.designsnitch ?? pkg.devDependencies?.designsnitch);
|
|
92
|
+
} catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
package/src/rules/load-tokens.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { parseColorTokens
|
|
3
|
+
import { parseColorTokens } from "../core/tokens.js";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* @typedef {object} Tokens
|
|
7
7
|
* @property {Map<string, string[]>} colors 색 값 → 토큰 이름들
|
|
8
|
-
* @property {ReturnType<typeof parseScaleTokens>} scale 간격 단위, radius, 폰트 크기 토큰
|
|
9
8
|
*/
|
|
10
9
|
|
|
11
10
|
/** @type {Map<string, { mtimeMs: number, tokens: Tokens }>} */
|
|
@@ -35,8 +34,16 @@ export function loadTokens(settings, cwd) {
|
|
|
35
34
|
const cached = cache.get(file);
|
|
36
35
|
if (cached?.mtimeMs === stat.mtimeMs) return cached.tokens;
|
|
37
36
|
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
let colors;
|
|
38
|
+
try {
|
|
39
|
+
colors = parseColorTokens(fs.readFileSync(file, "utf8"));
|
|
40
|
+
} catch (error) {
|
|
41
|
+
// 기준이 되는 파일이 깨져 있으면 무엇도 판정할 수 없다. 어디가 깨졌는지 알려준다.
|
|
42
|
+
throw new Error(
|
|
43
|
+
`designsnitch: 토큰 CSS를 읽을 수 없습니다: ${file}:${error.line ?? 1}:${error.column ?? 1} ${error.reason ?? error.message}`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
const tokens = { colors };
|
|
40
47
|
cache.set(file, { mtimeMs: stat.mtimeMs, tokens });
|
|
41
48
|
return tokens;
|
|
42
49
|
}
|
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: designsnitch
|
|
3
|
-
description: React/Next.js + Tailwind 프로젝트에서 UI 코드를 만들거나 고친 뒤, 디자인 시스템(토큰, 공용 컴포넌트)을 벗어난 곳을 검사하고 고친다. 컴포넌트나 페이지, className, 스타일을 수정했을 때, 또는 사용자가 디자인 시스템 준수, 토큰 사용, 디자인 검사를 말할 때 사용한다.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# designsnitch
|
|
7
|
-
|
|
8
|
-
UI 코드를 수정했으면 작업을 끝내기 전에 디자인 시스템 검사를 실행한다. 판정은 CLI가 하고, 이 문서는 언제 실행하고 결과를 어떻게 다룰지를 정한다.
|
|
9
|
-
|
|
10
|
-
## 1. 검사 실행
|
|
11
|
-
|
|
12
|
-
수정한 파일을 지정해서 실행한다. 경로를 생략하면 프로젝트 전체를 검사한다.
|
|
13
|
-
|
|
14
|
-
```sh
|
|
15
|
-
npx designsnitch check src/features/checkout/PayButton.tsx --format json
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
종료 코드는 0(오류 없음), 1(오류 있음), 2(실행하지 못함)이다. 2로 끝나면 stderr의 메시지를 읽는다. 설정 파일이 없다는 메시지면 2절로 간다.
|
|
19
|
-
|
|
20
|
-
## 2. 설정 파일이 없을 때
|
|
21
|
-
|
|
22
|
-
프로젝트 루트에 `designsnitch.config.json`이 없으면 저장소를 읽어서 만든다.
|
|
23
|
-
|
|
24
|
-
1. **토큰 CSS를 찾는다.** `@theme` 블록이나 `--color-*` 변수가 있는 CSS 파일이다. 보통 `app/globals.css`나 `src/app/globals.css`다.
|
|
25
|
-
2. **공용 컴포넌트 경로를 찾는다.** 버튼, 입력창 같은 기본 UI 컴포넌트가 모여 있는 디렉터리다. 보통 `components/ui`다.
|
|
26
|
-
3. **각 컴포넌트가 대체하는 raw 태그를 적는다.** 그 디렉터리의 파일을 읽어서, 최상위 요소가 `button`, `input`, `select`, `textarea`, `dialog` 같은 raw 태그인 컴포넌트를 찾는다. 같은 태그를 대체하는 컴포넌트가 여러 개면 모두 적는다. 이름은 export된 컴포넌트 이름을 쓴다.
|
|
27
|
-
4. **파일을 쓴다.**
|
|
28
|
-
|
|
29
|
-
```json
|
|
30
|
-
{
|
|
31
|
-
"tokens": "./src/app/globals.css",
|
|
32
|
-
"components": {
|
|
33
|
-
"path": "./src/components/ui",
|
|
34
|
-
"replaces": {
|
|
35
|
-
"button": ["SolidButton", "GlassButton", "IconButton"],
|
|
36
|
-
"input": "Input"
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
5. **검사를 실행해서 설정이 맞는지 확인한다.** 결과의 `designSystem`에 읽어 낸 개수가 나온다. `colorTokens`가 0이거나 `problems`가 비어 있지 않으면 설정이 틀린 것이므로, 경로를 다시 확인하고 고친다.
|
|
43
|
-
6. **사용자에게 설정 파일을 보여준다.** 이 파일이 판정 기준이므로, 어떤 파일과 경로를 골랐는지와 `designSystem`의 개수를 함께 알린다.
|
|
44
|
-
|
|
45
|
-
찾지 못한 항목은 추측해서 채우지 않는다. 공용 컴포넌트 디렉터리가 없으면 `components`를 빼고 `tokens`만 적는다. 토큰 CSS를 찾지 못하면 사용자에게 묻는다.
|
|
46
|
-
|
|
47
|
-
## 3. 결과 읽기
|
|
48
|
-
|
|
49
|
-
```json
|
|
50
|
-
{
|
|
51
|
-
"designSystem": {
|
|
52
|
-
"colorTokens": 175,
|
|
53
|
-
"radiusTokens": 4,
|
|
54
|
-
"textTokens": 0,
|
|
55
|
-
"components": 4,
|
|
56
|
-
"replacedTags": 2
|
|
57
|
-
},
|
|
58
|
-
"problems": [],
|
|
59
|
-
"summary": { "files": 1, "errors": 2, "warnings": 1 },
|
|
60
|
-
"violations": [
|
|
61
|
-
{
|
|
62
|
-
"file": "src/features/checkout/PayButton.tsx",
|
|
63
|
-
"line": 7,
|
|
64
|
-
"column": 28,
|
|
65
|
-
"endLine": 7,
|
|
66
|
-
"endColumn": 40,
|
|
67
|
-
"rule": "color-use-token",
|
|
68
|
-
"severity": "error",
|
|
69
|
-
"message": "bg-[#3B82F6]의 색은 토큰 --color-primary-500의 값입니다. 대신 사용: bg-primary-500",
|
|
70
|
-
"found": "bg-[#3B82F6]",
|
|
71
|
-
"candidates": ["bg-primary-500"]
|
|
72
|
-
}
|
|
73
|
-
]
|
|
74
|
-
}
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
- `designSystem`은 설정에서 읽어 낸 토큰과 컴포넌트의 개수다.
|
|
78
|
-
- `problems`가 비어 있지 않으면 설정에 문제가 있어 결과를 믿을 수 없다. 위반을 고치기 전에 사용자에게 알린다.
|
|
79
|
-
- `found`는 위반한 코드 조각이고, `candidates`는 대신 쓸 클래스나 컴포넌트다.
|
|
80
|
-
- `severity`가 `error`면 디자인 시스템에 쓸 것이 있는데 쓰지 않은 것이다. `warning`이면 디자인 시스템에 없는 값이다.
|
|
81
|
-
|
|
82
|
-
## 4. 고치기
|
|
83
|
-
|
|
84
|
-
대체가 확실한 위반만 고친다.
|
|
85
|
-
|
|
86
|
-
| 상황 | 할 일 |
|
|
87
|
-
| --- | --- |
|
|
88
|
-
| `error`이고 `candidates`가 하나 | `found`를 그 후보로 바꾼다. |
|
|
89
|
-
| `error`이고 `candidates`가 둘 이상 | 바꾸지 않는다. 후보들과 그 코드가 쓰인 맥락(무엇의 배경인지, 무엇의 글자색인지)을 사용자에게 보여주고 고르게 한다. |
|
|
90
|
-
| `warning` | 바꾸지 않는다. 새 값이 정말 필요한지 실수인지는 사용자가 정한다. 가까운 후보가 있으면 함께 보여준다. |
|
|
91
|
-
| `rule`이 `parse-error` | 문법 오류부터 고친 뒤 다시 검사한다. |
|
|
92
|
-
|
|
93
|
-
`rule`이 `use-ds-component`일 때는 태그 이름만 바꾸면 안 된다. 디자인 시스템 컴포넌트 파일을 읽어 props를 확인하고, import를 추가하고, 컴포넌트가 이미 가진 스타일과 겹치는 className을 정리한다.
|
|
94
|
-
|
|
95
|
-
## 5. 다시 검사
|
|
96
|
-
|
|
97
|
-
고친 뒤 같은 명령을 다시 실행한다. 남은 것이 사용자의 결정을 기다리는 항목뿐일 때 멈춘다.
|
|
98
|
-
|
|
99
|
-
## 6. 보고
|
|
100
|
-
|
|
101
|
-
고친 것과 남긴 것을 나눠서 알린다. 남긴 것은 파일과 줄, 후보, 남긴 이유를 함께 적는다.
|
|
102
|
-
|
|
103
|
-
## 하지 않는 것
|
|
104
|
-
|
|
105
|
-
- 이미 있는 `designsnitch.config.json`을 고치지 않는다. 설정 파일은 판정 기준이다. 없을 때 새로 만드는 것은 되지만, 있는 것을 바꿔야 할 것 같으면 이유를 설명하고 사용자에게 묻는다.
|
|
106
|
-
- 검사를 통과시키려고 `eslint-disable` 주석을 넣지 않는다. 예외가 필요해 보이면 사용자에게 묻는다.
|
|
107
|
-
- 후보가 여러 개일 때 임의로 하나를 고르지 않는다.
|
package/src/core/scale.js
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
const LENGTH = /^(\d*\.?\d+)(px|rem)$/;
|
|
2
|
-
const ROOT_FONT_SIZE = 16;
|
|
3
|
-
|
|
4
|
-
const SPACING_UTILITY = /^(?:[pm][xytrblse]?|gap(?:-[xy])?|space-[xy])$/;
|
|
5
|
-
const RADIUS_UTILITY = /^rounded(?:-(?:[trblse]|tl|tr|br|bl|ss|se|ee|es))?$/;
|
|
6
|
-
|
|
7
|
-
const round = (n) => Math.round(n * 1e4) / 1e4;
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* px, rem 길이를 px 숫자로 바꾼다. 다른 단위나 식은 null.
|
|
11
|
-
*/
|
|
12
|
-
export function parseLength(value) {
|
|
13
|
-
const match = LENGTH.exec(value.trim());
|
|
14
|
-
if (!match) return null;
|
|
15
|
-
const amount = Number(match[1]);
|
|
16
|
-
return round(match[2] === "rem" ? amount * ROOT_FONT_SIZE : amount);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* 임의 값으로 쓴 길이가 스케일에 있는지 본다.
|
|
21
|
-
* - 있으면 { kind, exact: [대신 쓸 클래스] }
|
|
22
|
-
* - 없으면 { kind, nearest: [{ className, px }] } (바로 아래, 바로 위)
|
|
23
|
-
* - 검사 대상이 아니거나 비교할 토큰이 없으면 null
|
|
24
|
-
*
|
|
25
|
-
* @param {string} utility 예: "p", "rounded-t", "text"
|
|
26
|
-
* @param {number} px
|
|
27
|
-
* @param {{ spacingUnit: number, radius: Map<number, string[]>, text: Map<number, string[]> }} scale
|
|
28
|
-
*/
|
|
29
|
-
export function matchScale(utility, px, scale) {
|
|
30
|
-
if (SPACING_UTILITY.test(utility)) {
|
|
31
|
-
return { kind: "spacing", ...matchSpacing(utility, px, scale.spacingUnit) };
|
|
32
|
-
}
|
|
33
|
-
if (RADIUS_UTILITY.test(utility) && scale.radius.size > 0) {
|
|
34
|
-
return { kind: "radius", ...matchTokens(utility, px, scale.radius, "--radius-") };
|
|
35
|
-
}
|
|
36
|
-
if (utility === "text" && scale.text.size > 0) {
|
|
37
|
-
return { kind: "text", ...matchTokens(utility, px, scale.text, "--text-") };
|
|
38
|
-
}
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// 간격은 단위의 0.5배수까지를 스케일로 본다 (p-0.5, p-1.5, p-4 ...). 1px 는 p-px.
|
|
43
|
-
function matchSpacing(utility, px, unit) {
|
|
44
|
-
const halfSteps = round((px / unit) * 2);
|
|
45
|
-
if (Number.isInteger(halfSteps)) return { exact: [`${utility}-${halfSteps / 2}`] };
|
|
46
|
-
if (px === 1) return { exact: [`${utility}-px`] };
|
|
47
|
-
|
|
48
|
-
const lower = Math.floor(halfSteps) / 2;
|
|
49
|
-
return {
|
|
50
|
-
nearest: [lower, lower + 0.5].map((steps) => ({
|
|
51
|
-
className: `${utility}-${steps}`,
|
|
52
|
-
px: round(steps * unit),
|
|
53
|
-
})),
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function matchTokens(utility, px, tokens, prefix) {
|
|
58
|
-
const toClass = (name) => `${utility}-${name.slice(prefix.length)}`;
|
|
59
|
-
|
|
60
|
-
const names = tokens.get(px);
|
|
61
|
-
if (names) return { exact: names.map(toClass) };
|
|
62
|
-
|
|
63
|
-
const values = [...tokens.keys()].sort((a, b) => a - b);
|
|
64
|
-
const below = values.findLast((value) => value < px);
|
|
65
|
-
const above = values.find((value) => value > px);
|
|
66
|
-
return {
|
|
67
|
-
nearest: [below, above]
|
|
68
|
-
.filter((value) => value !== undefined)
|
|
69
|
-
.map((value) => ({ className: toClass(tokens.get(value)[0]), px: value })),
|
|
70
|
-
};
|
|
71
|
-
}
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { findArbitraryLengths } from "../core/classes.js";
|
|
2
|
-
import { matchScale } from "../core/scale.js";
|
|
3
|
-
import { loadTokens } from "./load-tokens.js";
|
|
4
|
-
import { SCALE_LABELS } from "./scale-labels.js";
|
|
5
|
-
import { REPLACE_MESSAGES, suggestClasses } from "./suggest.js";
|
|
6
|
-
import { visitStrings } from "./visit-strings.js";
|
|
7
|
-
|
|
8
|
-
/** @type {import("eslint").Rule.RuleModule} */
|
|
9
|
-
export default {
|
|
10
|
-
meta: {
|
|
11
|
-
type: "suggestion",
|
|
12
|
-
docs: { description: "스케일에 없는 간격, 폰트 크기, radius를 쓰면 알린다" },
|
|
13
|
-
hasSuggestions: true,
|
|
14
|
-
schema: [],
|
|
15
|
-
messages: {
|
|
16
|
-
...REPLACE_MESSAGES,
|
|
17
|
-
unknown: "{{found}}의 값은 {{scale}}에 없습니다. 가까운 값: {{nearest}}",
|
|
18
|
-
},
|
|
19
|
-
},
|
|
20
|
-
create(context) {
|
|
21
|
-
const { scale } = loadTokens(context.settings, context.cwd);
|
|
22
|
-
|
|
23
|
-
return visitStrings(context, findArbitraryLengths, (found, { loc, range }) => {
|
|
24
|
-
const match = matchScale(found.utility, found.px, scale);
|
|
25
|
-
if (!match?.nearest) return;
|
|
26
|
-
context.report({
|
|
27
|
-
loc,
|
|
28
|
-
messageId: "unknown",
|
|
29
|
-
data: {
|
|
30
|
-
found: found.text,
|
|
31
|
-
scale: SCALE_LABELS[match.kind],
|
|
32
|
-
nearest: match.nearest
|
|
33
|
-
.map(({ className, px }) => `${className} (${px}px)`)
|
|
34
|
-
.join(", "),
|
|
35
|
-
},
|
|
36
|
-
suggest: suggestClasses(
|
|
37
|
-
range,
|
|
38
|
-
match.nearest.map(({ className }) => className),
|
|
39
|
-
),
|
|
40
|
-
});
|
|
41
|
-
});
|
|
42
|
-
},
|
|
43
|
-
};
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { findArbitraryLengths } from "../core/classes.js";
|
|
2
|
-
import { matchScale } from "../core/scale.js";
|
|
3
|
-
import { loadTokens } from "./load-tokens.js";
|
|
4
|
-
import { SCALE_LABELS } from "./scale-labels.js";
|
|
5
|
-
import { REPLACE_MESSAGES, suggestClasses } from "./suggest.js";
|
|
6
|
-
import { visitStrings } from "./visit-strings.js";
|
|
7
|
-
|
|
8
|
-
/** @type {import("eslint").Rule.RuleModule} */
|
|
9
|
-
export default {
|
|
10
|
-
meta: {
|
|
11
|
-
type: "problem",
|
|
12
|
-
docs: { description: "스케일에 있는 간격, 폰트 크기, radius를 임의 값으로 쓰지 않는다" },
|
|
13
|
-
hasSuggestions: true,
|
|
14
|
-
schema: [],
|
|
15
|
-
messages: {
|
|
16
|
-
...REPLACE_MESSAGES,
|
|
17
|
-
useToken: "{{found}}의 값은 {{scale}}에 있습니다. 대신 사용: {{classes}}",
|
|
18
|
-
},
|
|
19
|
-
},
|
|
20
|
-
create(context) {
|
|
21
|
-
const { scale } = loadTokens(context.settings, context.cwd);
|
|
22
|
-
|
|
23
|
-
return visitStrings(context, findArbitraryLengths, (found, { loc, range }) => {
|
|
24
|
-
const match = matchScale(found.utility, found.px, scale);
|
|
25
|
-
if (!match?.exact) return;
|
|
26
|
-
context.report({
|
|
27
|
-
loc,
|
|
28
|
-
messageId: "useToken",
|
|
29
|
-
data: {
|
|
30
|
-
found: found.text,
|
|
31
|
-
scale: SCALE_LABELS[match.kind],
|
|
32
|
-
classes: match.exact.join(", "),
|
|
33
|
-
},
|
|
34
|
-
suggest: suggestClasses(range, match.exact),
|
|
35
|
-
});
|
|
36
|
-
});
|
|
37
|
-
},
|
|
38
|
-
};
|