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/src/check.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import tsParser from "@typescript-eslint/parser";
4
- import { ESLint } from "eslint";
3
+ import { normalizeHex } from "./core/color.js";
4
+ import { findCssColors } from "./core/css.js";
5
+ import { createEngine } from "./engine.js";
6
+ import { splitPaths } from "./files.js";
5
7
  import plugin from "./index.js";
6
8
  import { loadTokens } from "./rules/load-tokens.js";
7
9
 
8
- const FILES = ["**/*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}"];
9
- const IGNORES = ["**/.next/**", "**/dist/**", "**/build/**", "**/out/**", "**/coverage/**"];
10
10
  const RULE_PREFIX = "designsnitch/";
11
11
 
12
12
  /**
@@ -21,6 +21,10 @@ const RULE_PREFIX = "designsnitch/";
21
21
  * @property {string} message
22
22
  * @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
23
23
  * @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
24
+ * @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
25
+ * replace: found 를 candidates 의 값으로 바꾸면 된다 (후보가 하나뿐인 오류)
26
+ * ask: 사람이 정해야 한다 (후보가 여러 개이거나, 토큰에 없는 값)
27
+ * repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
24
28
  */
25
29
 
26
30
  /**
@@ -30,11 +34,13 @@ const RULE_PREFIX = "designsnitch/";
30
34
  * @param {ReturnType<typeof import("./config.js").loadConfig>} options.config
31
35
  * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
32
36
  * @returns {Promise<{
33
- * designSystem: { colorTokens: number, radiusTokens: number, textTokens: number, components: number, replacedTags: number },
37
+ * designSystem: { colorTokens: number, components: number, replacedTags: number },
34
38
  * problems: string[],
39
+ * next: string[],
35
40
  * summary: { files: number, errors: number, warnings: number },
36
41
  * violations: Violation[],
37
- * }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제
42
+ * }>} designSystem 은 설정에서 읽어 낸 것의 개수, problems 는 결과를 믿기 어렵게 만드는 설정 문제,
43
+ * next 는 이 결과를 받은 에이전트가 순서대로 할 일
38
44
  */
39
45
  export async function check({ cwd, config, paths = ["."] }) {
40
46
  const settings = { designsnitch: config };
@@ -56,41 +62,31 @@ export async function check({ cwd, config, paths = ["."] }) {
56
62
  );
57
63
  }
58
64
 
59
- const eslint = new ESLint({
60
- cwd,
61
- overrideConfigFile: true,
62
- errorOnUnmatchedPattern: false,
63
- overrideConfig: [
64
- { ignores: IGNORES },
65
- {
66
- ...plugin.configs.recommended,
67
- files: FILES,
68
- languageOptions: {
69
- parser: tsParser,
70
- parserOptions: { ecmaFeatures: { jsx: true } },
71
- },
72
- // 프로젝트 코드에는 다른 규칙용 eslint-disable 주석이 있을 수 있다.
73
- linterOptions: { reportUnusedDisableDirectives: "off" },
74
- settings,
75
- },
76
- ],
77
- });
78
-
79
- const results = await eslint.lintFiles(paths);
80
- results.sort((a, b) => a.filePath.localeCompare(b.filePath));
65
+ const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
81
66
 
82
- const violations = results.flatMap((result) => {
67
+ // JS, TS 는 ESLint 로 규칙을 실행하고, CSS 는 직접 읽는다.
68
+ const eslint = createEngine({ cwd, config: { ...plugin.configs.recommended, settings } });
69
+ const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
70
+ const scriptViolations = results.flatMap((result) => {
83
71
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
84
72
  return result.messages
85
73
  .filter(isOurs)
86
74
  .map((message) => toViolation(file, result.source, message, config));
87
75
  });
76
+ const cssViolations = cssFiles.flatMap((file) =>
77
+ checkCss(file, fs.readFileSync(path.resolve(cwd, file), "utf8"), tokens.colors),
78
+ );
79
+
80
+ const violations = [...scriptViolations, ...cssViolations]
81
+ .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
82
+ .map((violation) => ({ ...violation, action: actionFor(violation) }));
88
83
 
89
84
  return {
90
85
  designSystem,
91
86
  problems,
87
+ next: nextSteps(designSystem, violations),
92
88
  summary: {
93
- files: results.length,
89
+ files: results.length + cssFiles.length,
94
90
  errors: violations.filter((v) => v.severity === "error").length,
95
91
  warnings: violations.filter((v) => v.severity === "warning").length,
96
92
  },
@@ -98,13 +94,101 @@ export async function check({ cwd, config, paths = ["."] }) {
98
94
  };
99
95
  }
100
96
 
97
+ /**
98
+ * CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
99
+ * @returns {Violation[]}
100
+ */
101
+ function checkCss(file, source, colorTokens) {
102
+ let colors;
103
+ try {
104
+ colors = findCssColors(source);
105
+ } catch (error) {
106
+ const at = { line: error.line ?? 1, column: error.column ?? 1 };
107
+ return [
108
+ {
109
+ file,
110
+ ...at,
111
+ endLine: at.line,
112
+ endColumn: at.column,
113
+ rule: "parse-error",
114
+ severity: "error",
115
+ message: error.reason ?? error.message,
116
+ found: "",
117
+ candidates: [],
118
+ },
119
+ ];
120
+ }
121
+
122
+ return colors
123
+ .filter((color) => !color.disabled)
124
+ .map(({ value, prop, disabled, ...location }) => {
125
+ const tokenNames = colorTokens.get(normalizeHex(value)) ?? [];
126
+ const candidates = tokenNames.map((name) => `var(${name})`);
127
+ return {
128
+ file,
129
+ ...location,
130
+ ...(tokenNames.length > 0
131
+ ? {
132
+ rule: "color-use-token",
133
+ severity: "error",
134
+ message: `${value}의 색은 토큰 ${tokenNames.join(", ")}의 값입니다. 대신 사용: ${candidates.join(", ")}`,
135
+ }
136
+ : {
137
+ rule: "color-unknown",
138
+ severity: "warning",
139
+ message: `${value}의 색은 토큰에 없습니다.`,
140
+ }),
141
+ found: value,
142
+ candidates,
143
+ };
144
+ });
145
+ }
146
+
147
+ function actionFor({ rule, severity, candidates }) {
148
+ if (rule === "parse-error") return "repair";
149
+ return severity === "error" && candidates.length === 1 ? "replace" : "ask";
150
+ }
151
+
152
+ /**
153
+ * 결과를 받은 에이전트가 무엇부터 해야 하는지를 순서대로 적는다.
154
+ * @param {{ colorTokens: number }} designSystem
155
+ * @param {Violation[]} violations action 이 붙은 위반들
156
+ * @returns {string[]}
157
+ */
158
+ export function nextSteps(designSystem, violations) {
159
+ const noColorTokens = designSystem.colorTokens === 0;
160
+ // 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
161
+ const actionable = noColorTokens
162
+ ? violations.filter((v) => !v.rule.startsWith("color-"))
163
+ : violations;
164
+ const count = (action) => actionable.filter((v) => v.action === action).length;
165
+ const [repair, replace, ask] = ["repair", "replace", "ask"].map(count);
166
+ const steps = [];
167
+
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("고친 뒤 같은 명령을 다시 실행하세요.");
183
+
184
+ return steps.length > 0 ? steps : ["위반이 없습니다."];
185
+ }
186
+
101
187
  function describeDesignSystem(tokens, config) {
102
188
  const countNames = (map) => new Set([...map.values()].flat()).size;
103
189
  const replaces = Object.values(config.components?.replaces ?? {});
104
190
  return {
105
191
  colorTokens: countNames(tokens.colors),
106
- radiusTokens: countNames(tokens.scale.radius),
107
- textTokens: countNames(tokens.scale.text),
108
192
  components: new Set(replaces.flat()).size,
109
193
  replacedTags: replaces.length,
110
194
  };
package/src/cli.js CHANGED
@@ -1,30 +1,68 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import { parseArgs } from "node:util";
2
4
  import { check } from "./check.js";
3
- import { loadConfig } from "./config.js";
4
- import { formatText } from "./format.js";
5
+ import { collectColors } from "./colors.js";
6
+ import { CONFIG_FILE, loadConfig } from "./config.js";
7
+ import { formatColorsText, formatText } from "./format.js";
8
+ import { runHook } from "./hook.js";
9
+ import { install } from "./install.js";
10
+ import { loadTokens } from "./rules/load-tokens.js";
5
11
 
6
- const USAGE = `사용법: designsnitch check [경로...] [--format text|json] [--config 파일]
12
+ const USAGE = `사용법: designsnitch <명령> [경로...] [--format text|json] [--config 파일]
7
13
 
8
- 프로젝트의 UI 코드가 디자인 시스템을 따르는지 검사합니다.
14
+ 명령
15
+ check UI 코드가 디자인 시스템을 따르는지 검사합니다.
16
+ colors 코드에서 쓰는 색을 모아 보여줍니다. 설정 파일이 없어도 됩니다.
17
+ hook 코딩 에이전트의 훅에서 부릅니다. 방금 고친 파일에 오류가 있으면 2로 끝납니다.
18
+ install 스킬과 에이전트 훅을 프로젝트(.claude)에 설치합니다.
9
19
 
10
- 경로 검사할 파일이나 디렉터리 (기본: 현재 디렉터리)
20
+ 옵션
21
+ 경로 볼 파일이나 디렉터리 (기본: 현재 디렉터리)
11
22
  --format 출력 형식. text(기본) 또는 json
12
23
  --config 설정 파일 경로 (기본: designsnitch.config.json)
13
24
 
14
- 종료 코드: 0 오류 없음, 1 오류 있음, 2 실행하지 못함
25
+ check 의 종료 코드: 0 오류 없음, 1 오류 있음, 2 실행하지 못함
15
26
  `;
16
27
 
17
- const FORMATS = {
18
- text: formatText,
19
- json: (result) => `${JSON.stringify(result, null, 2)}\n`,
28
+ const json = (result) => `${JSON.stringify(result, null, 2)}\n`;
29
+
30
+ // 명령은 내보낼 글과 종료 코드를 돌려준다.
31
+ const COMMANDS = {
32
+ async check({ cwd, paths, configPath, format }) {
33
+ const result = await check({ cwd, config: loadConfig(cwd, configPath), paths });
34
+ return {
35
+ stdout: format === "json" ? json(result) : formatText(result),
36
+ exitCode: result.summary.errors > 0 ? 1 : 0,
37
+ };
38
+ },
39
+
40
+ // 설정 파일은 선택이다. 있으면 색마다 이미 있는 토큰을 붙인다.
41
+ async colors({ cwd, paths, configPath, format }) {
42
+ 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 };
48
+ },
49
+
50
+ hook({ cwd, configPath, stdin }) {
51
+ return runHook({ cwd, input: stdin, configPath });
52
+ },
53
+
54
+ install({ cwd }) {
55
+ return install({ cwd });
56
+ },
20
57
  };
21
58
 
22
59
  /**
23
60
  * @param {string[]} argv 명령 이름부터 시작하는 인자 (process.argv.slice(2))
24
- * @param {{ cwd: string, stdout: { write(chunk: string): unknown }, stderr: { write(chunk: string): unknown } }} io
61
+ * @param {{ cwd: string, stdin?: string, stdout: { write(chunk: string): unknown }, stderr: { write(chunk: string): unknown } }} io
62
+ * stdin 은 이미 읽어 둔 표준 입력이다. hook 명령만 쓴다
25
63
  * @returns {Promise<number>} 종료 코드
26
64
  */
27
- export async function run(argv, { cwd, stdout, stderr }) {
65
+ export async function run(argv, { cwd, stdin, stdout, stderr }) {
28
66
  let args;
29
67
  try {
30
68
  args = parseArgs({
@@ -46,22 +84,29 @@ export async function run(argv, { cwd, stdout, stderr }) {
46
84
  return 0;
47
85
  }
48
86
 
49
- const [command, ...paths] = args.positionals;
50
- const format = FORMATS[args.values.format];
51
- if (command !== "check" || !format) {
87
+ const [name, ...paths] = args.positionals;
88
+ const command = Object.hasOwn(COMMANDS, name ?? "") ? COMMANDS[name] : undefined;
89
+ const { format } = args.values;
90
+ if (!command || !["text", "json"].includes(format)) {
52
91
  stderr.write(USAGE);
53
92
  return 2;
54
93
  }
55
94
 
56
- let result;
95
+ let outcome;
57
96
  try {
58
- const config = loadConfig(cwd, args.values.config);
59
- result = await check({ cwd, config, paths: paths.length > 0 ? paths : undefined });
97
+ outcome = await command({
98
+ cwd,
99
+ paths: paths.length > 0 ? paths : undefined,
100
+ configPath: args.values.config,
101
+ format,
102
+ stdin,
103
+ });
60
104
  } catch (error) {
61
105
  stderr.write(`${error.message}\n`);
62
106
  return 2;
63
107
  }
64
108
 
65
- stdout.write(format(result));
66
- return result.summary.errors > 0 ? 1 : 0;
109
+ if (outcome.stdout) stdout.write(outcome.stdout);
110
+ if (outcome.stderr) stderr.write(outcome.stderr);
111
+ return outcome.exitCode;
67
112
  }
package/src/colors.js ADDED
@@ -0,0 +1,166 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { findArbitraryColors, findPaletteClasses } from "./core/classes.js";
4
+ import { normalizeHex } from "./core/color.js";
5
+ import { findCssColors } from "./core/css.js";
6
+ import { createEngine } from "./engine.js";
7
+ import { splitPaths } from "./files.js";
8
+ import { visitStrings } from "./rules/visit-strings.js";
9
+
10
+ const RULE_ID = "designsnitch-internal/collect-colors";
11
+ const HEX_LITERAL = /^#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})$/i;
12
+ const MAX_EXAMPLES = 3;
13
+
14
+ // 알파가 붙은 hex 는 6자리로 펼칠 수 없으니 소문자로만 맞춘다.
15
+ const colorKey = (hex) => normalizeHex(hex) ?? hex.toLowerCase();
16
+
17
+ const findColors = (text) => [
18
+ ...findArbitraryColors(text).map((found) => ({
19
+ ...found,
20
+ payload: { kind: "hex", key: colorKey(found.value), utility: found.utility },
21
+ })),
22
+ ...findPaletteClasses(text).map((found) => ({
23
+ ...found,
24
+ payload: { kind: "palette", key: found.name, utility: found.utility },
25
+ })),
26
+ ];
27
+
28
+ // 위반을 보고하는 규칙이 아니라, 찾은 색을 메시지에 실어 내보내는 수집용 규칙이다.
29
+ const collectRule = {
30
+ meta: { type: "suggestion", schema: [], messages: { found: "{{payload}}" } },
31
+ create(context) {
32
+ const report = (loc, payload) =>
33
+ context.report({ loc, messageId: "found", data: { payload: JSON.stringify(payload) } });
34
+ const visitor = visitStrings(context, findColors, (found, { loc }) => report(loc, found.payload));
35
+
36
+ return {
37
+ ...visitor,
38
+ Literal(node) {
39
+ // 문자열 전체가 hex 색인 경우. 예: style={{ color: "#3B82F6" }}
40
+ if (typeof node.value === "string" && HEX_LITERAL.test(node.value)) {
41
+ report(node.loc, { kind: "hex", key: colorKey(node.value), utility: null });
42
+ return;
43
+ }
44
+ visitor.Literal(node);
45
+ },
46
+ };
47
+ },
48
+ };
49
+
50
+ /**
51
+ * @typedef {object} ColorUse
52
+ * @property {number} uses 쓰인 횟수
53
+ * @property {number} files 쓰인 파일 수
54
+ * @property {Record<string, number>} utilities Tailwind 유틸리티별 횟수. 예: { bg: 3, text: 1 }
55
+ * @property {{ file: string, line: number }[]} examples 파일이 서로 다른 위치 몇 개
56
+ */
57
+
58
+ /**
59
+ * 코드에서 쓰는 색을 모은다. 설정 파일이 없어도 동작한다.
60
+ * @param {object} options
61
+ * @param {string} options.cwd 프로젝트 디렉터리
62
+ * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
63
+ * @param {Map<string, string[]>} [options.tokens] 색 값 → 토큰 이름들. 주면 색마다 tokens 를 붙인다
64
+ * @returns {Promise<{
65
+ * summary: { files: number, colors: number, paletteColors: number, uses: number },
66
+ * colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
67
+ * palette: (ColorUse & { name: string })[],
68
+ * }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
69
+ * literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
70
+ */
71
+ export async function collectColors({ cwd, paths = ["."], tokens }) {
72
+ const eslint = createEngine({
73
+ cwd,
74
+ // 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
75
+ allowInlineConfig: false,
76
+ config: {
77
+ plugins: { "designsnitch-internal": { rules: { "collect-colors": collectRule } } },
78
+ rules: { [RULE_ID]: "warn" },
79
+ },
80
+ });
81
+
82
+ const { scriptPaths, cssFiles } = splitPaths(cwd, paths);
83
+ const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
84
+
85
+ /** @type {{ file: string, line: number, kind: "hex" | "palette", key: string, utility?: string | null, prop?: string }[]} */
86
+ const uses = [];
87
+ for (const result of results) {
88
+ const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
89
+ for (const message of result.messages) {
90
+ if (message.ruleId !== RULE_ID) continue;
91
+ uses.push({ file, line: message.line, ...JSON.parse(message.message) });
92
+ }
93
+ }
94
+ for (const file of cssFiles) {
95
+ let found;
96
+ try {
97
+ found = findCssColors(fs.readFileSync(path.resolve(cwd, file), "utf8"));
98
+ } catch {
99
+ continue; // 읽지 못한 CSS 는 건너뛴다
100
+ }
101
+ for (const { line, value, prop } of found) {
102
+ uses.push({ file, line, kind: "hex", key: colorKey(value), prop });
103
+ }
104
+ }
105
+ uses.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
106
+
107
+ const groups = { hex: new Map(), palette: new Map() };
108
+ for (const { file, line, kind, key, utility, prop } of uses) {
109
+ const entry = getOrCreate(groups[kind], key);
110
+ entry.uses += 1;
111
+ if (prop) entry.properties[prop] = (entry.properties[prop] ?? 0) + 1;
112
+ else if (utility) entry.utilities[utility] = (entry.utilities[utility] ?? 0) + 1;
113
+ else entry.literals += 1;
114
+ if (!entry.fileSet.has(file)) {
115
+ entry.fileSet.add(file);
116
+ if (entry.examples.length < MAX_EXAMPLES) entry.examples.push({ file, line });
117
+ }
118
+ }
119
+
120
+ const colors = sorted(groups.hex).map(([color, entry]) => ({
121
+ color,
122
+ uses: entry.uses,
123
+ files: entry.fileSet.size,
124
+ utilities: entry.utilities,
125
+ literals: entry.literals,
126
+ properties: entry.properties,
127
+ ...(tokens ? { tokens: tokens.get(color) ?? [] } : {}),
128
+ examples: entry.examples,
129
+ }));
130
+ // 프로젝트가 --color-blue-500 처럼 같은 이름의 토큰을 정의했으면 그 클래스는 프로젝트 토큰이다.
131
+ const tokenClassNames = new Set(
132
+ [...(tokens?.values() ?? [])].flat().map((name) => name.replace(/^--color-/, "")),
133
+ );
134
+ const palette = sorted(groups.palette)
135
+ .filter(([name]) => !tokenClassNames.has(name))
136
+ .map(([name, entry]) => ({
137
+ name,
138
+ uses: entry.uses,
139
+ files: entry.fileSet.size,
140
+ utilities: entry.utilities,
141
+ examples: entry.examples,
142
+ }));
143
+
144
+ return {
145
+ summary: {
146
+ files: results.length + cssFiles.length,
147
+ colors: colors.length,
148
+ paletteColors: palette.length,
149
+ uses: [...colors, ...palette].reduce((sum, item) => sum + item.uses, 0),
150
+ },
151
+ colors,
152
+ palette,
153
+ };
154
+ }
155
+
156
+ function getOrCreate(map, key) {
157
+ if (!map.has(key)) {
158
+ map.set(key, { uses: 0, fileSet: new Set(), utilities: {}, literals: 0, properties: {}, examples: [] });
159
+ }
160
+ return map.get(key);
161
+ }
162
+
163
+ // 많이 쓰인 순서, 같으면 이름 순서
164
+ function sorted(map) {
165
+ return [...map].sort(([a, x], [b, y]) => y.uses - x.uses || a.localeCompare(b));
166
+ }
package/src/config.js CHANGED
@@ -24,7 +24,10 @@ export function loadConfig(cwd, configPath = CONFIG_FILE) {
24
24
  try {
25
25
  text = fs.readFileSync(file, "utf8");
26
26
  } catch {
27
- throw new Error(`설정 파일이 없습니다: ${file}\n다음과 같은 내용으로 만드세요.\n${EXAMPLE}`);
27
+ throw new Error(
28
+ `설정 파일이 없습니다: ${file}\n` +
29
+ `다음과 같은 내용으로 만드세요. designsnitch-setup 스킬을 따르면 저장소를 읽어서 만들 수 있습니다.\n${EXAMPLE}`,
30
+ );
28
31
  }
29
32
 
30
33
  let config;
@@ -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, 대체값)
@@ -49,41 +48,3 @@ export function parseColorTokens(css) {
49
48
  }
50
49
  return new Map([...tokens].map(([color, names]) => [color, [...names]]));
51
50
  }
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;
89
- }
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
+