designsnitch 0.4.0 → 0.6.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 +76 -26
- package/README.md +76 -26
- package/bin/designsnitch.js +5 -3
- package/package.json +2 -2
- package/skills/designsnitch-check/SKILL.md +9 -8
- package/skills/designsnitch-hooks/SKILL.md +21 -3
- package/skills/designsnitch-palette/SKILL.md +3 -3
- package/skills/designsnitch-setup/SKILL.md +10 -7
- package/src/check.js +83 -36
- package/src/cli.js +3 -4
- package/src/colors.js +16 -13
- package/src/config.js +1 -0
- package/src/core/classes.js +13 -21
- package/src/core/color.js +133 -9
- package/src/core/css.js +38 -10
- package/src/core/named-colors.js +35 -0
- package/src/core/oklch.js +58 -0
- package/src/core/tokens.js +96 -13
- package/src/format.js +2 -2
- package/src/hook.js +62 -11
- package/src/install.js +6 -0
- package/src/messages.js +46 -14
- package/src/rules/color-unknown.js +3 -2
- package/src/rules/color-use-token.js +43 -15
- package/src/rules/load-tokens.js +195 -12
- package/src/rules/tailwind-config.js +77 -0
- package/src/rules/unchecked-colors.js +28 -0
- package/src/rules/visit-style.js +82 -20
- package/src/rules/unchecked-hex.js +0 -25
package/src/core/color.js
CHANGED
|
@@ -1,13 +1,137 @@
|
|
|
1
|
-
|
|
1
|
+
import { NAMED_COLORS } from "./named-colors.js";
|
|
2
|
+
import { oklchKey } from "./oklch.js";
|
|
3
|
+
|
|
4
|
+
const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
5
|
+
const FUNCTION = /^(rgba?|hsla?|oklch)\((.*)\)$/is;
|
|
6
|
+
// hex 로 바꾸지 않는 표기. 같은 표기끼리만 맞춘다.
|
|
7
|
+
const OTHER_FUNCTION = /^(hwb|lab|lch|oklab|color)\(([^()]*)\)$/is;
|
|
8
|
+
// 문자열 속의 색 값. 예: "#fff", "rgb(1, 2, 3)". a#top, ' 같은 것은 색이 아니다.
|
|
9
|
+
const COLOR_VALUE =
|
|
10
|
+
/(?<![\w&#])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])|(?<![\w-])(?:rgba?|hsla?|oklch|hwb|lab|lch|oklab|color)\([^()]*\)/gi;
|
|
11
|
+
// 색 이름. var(--red), .red, dark-red, red-500 같은 것은 색 이름이 아니다.
|
|
12
|
+
const NAMED_VALUE = new RegExp(
|
|
13
|
+
`(?<![\\w#.$@-])(?:${Object.keys(NAMED_COLORS).sort((a, b) => b.length - a.length).join("|")})(?![\\w(-])`,
|
|
14
|
+
"gi",
|
|
15
|
+
);
|
|
16
|
+
// 색을 값으로 받는 CSS 속성. 색 이름은 여기서만 색으로 본다.
|
|
17
|
+
const COLOR_PROPERTY =
|
|
18
|
+
/^(?:-(?:webkit|moz)-)?(?:color|background(?:-color|-image)?|border(?:-[a-z-]+)?|outline(?:-color)?|fill|stroke|box-shadow|text-shadow|caret-color|accent-color|text-decoration(?:-color)?|text-emphasis(?:-color)?|column-rule(?:-color)?|scrollbar-color|stop-color|flood-color|lighting-color|text-fill-color|text-stroke(?:-color)?|tap-highlight-color)$/;
|
|
19
|
+
|
|
20
|
+
/** 색을 값으로 받는 CSS 속성인지. backgroundColor 같은 JS 표기도 받는다. */
|
|
21
|
+
export function isColorProperty(property) {
|
|
22
|
+
return COLOR_PROPERTY.test(property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** white, red 같은 CSS 색 이름인지. */
|
|
26
|
+
export function isNamedColor(value) {
|
|
27
|
+
return Object.hasOwn(NAMED_COLORS, value.trim().toLowerCase());
|
|
28
|
+
}
|
|
2
29
|
|
|
3
30
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
31
|
+
* 색 값을 읽는다. 읽을 수 없으면 null.
|
|
32
|
+
* @param {string} value 예: "#3B82F6", "rgb(59 130 246)", "hsl(217, 91%, 60%)", "oklch(55.4% 0.046 257.417)", "white"
|
|
33
|
+
* @returns {{ key: string, alpha: number, opaque: boolean } | null} key 는 비교용 표기. sRGB 색은 소문자 6자리 hex,
|
|
34
|
+
* sRGB 밖의 oklch 는 표기를 맞춘 oklch(...). opaque 가 false 면 반투명이다
|
|
6
35
|
*/
|
|
7
|
-
export function
|
|
8
|
-
const
|
|
9
|
-
if (
|
|
10
|
-
|
|
11
|
-
if (
|
|
12
|
-
|
|
36
|
+
export function parseColor(value) {
|
|
37
|
+
const text = value.trim();
|
|
38
|
+
if (text.startsWith("#")) return parseHex(text);
|
|
39
|
+
// Tailwind 임의 값은 공백 대신 _ 를 쓴다.
|
|
40
|
+
if (isNamedColor(text)) return { key: `#${NAMED_COLORS[text.toLowerCase()]}`, alpha: 1, opaque: true };
|
|
41
|
+
const spaced = text.replaceAll("_", " ");
|
|
42
|
+
const other = OTHER_FUNCTION.exec(spaced);
|
|
43
|
+
if (other) {
|
|
44
|
+
const args = other[2].trim().replace(/\s+/g, " ").toLowerCase();
|
|
45
|
+
return args ? { key: `${other[1].toLowerCase()}(${args})`, alpha: 1, opaque: !args.includes("/") } : null;
|
|
46
|
+
}
|
|
47
|
+
const match = FUNCTION.exec(spaced);
|
|
48
|
+
if (!match) return null;
|
|
49
|
+
const name = match[1].toLowerCase();
|
|
50
|
+
if (name === "oklch") return oklchKey(`oklch(${match[2]})`);
|
|
51
|
+
|
|
52
|
+
const parts = match[2].trim().split(/\s*[,/]\s*|\s+/);
|
|
53
|
+
if (parts.length !== 3 && parts.length !== 4) return null;
|
|
54
|
+
const alpha = parts.length === 4 ? unit(parts[3], 1) : 1;
|
|
55
|
+
const rgb = name.startsWith("rgb") ? parts.slice(0, 3).map((part) => unit(part, 255)) : hslToRgb(parts);
|
|
56
|
+
if (alpha === null || !rgb || rgb.some((channel) => channel === null)) return null;
|
|
57
|
+
return { key: `#${rgb.map(toByte).join("")}`, alpha, opaque: alpha >= 1 };
|
|
13
58
|
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 색을 세거나 묶을 때 쓰는 이름. 표기가 달라도 같은 색이면 같은 이름이 된다.
|
|
62
|
+
* 불투명한 색은 normalizeColor 와 같고, 반투명한 색은 #rrggbbaa 다. 색이 아니면 소문자로만 맞춘다.
|
|
63
|
+
* @param {string} value
|
|
64
|
+
*/
|
|
65
|
+
export function colorLabel(value) {
|
|
66
|
+
const color = parseColor(value);
|
|
67
|
+
if (!color) return value.toLowerCase();
|
|
68
|
+
if (color.opaque) return color.key;
|
|
69
|
+
return color.key.startsWith("#") ? `${color.key}${toByte(color.alpha * 255)}` : color.key.replace(")", ` / ${color.alpha})`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 색 값을 비교할 수 있는 표기로 바꾼다. 반투명한 색과 색이 아닌 값은 null.
|
|
74
|
+
* @param {string} value
|
|
75
|
+
* @returns {string | null}
|
|
76
|
+
*/
|
|
77
|
+
export function normalizeColor(value) {
|
|
78
|
+
const color = parseColor(value);
|
|
79
|
+
return color?.opaque ? color.key : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 문자열에서 색 값(hex 와 rgb(), hsl(), oklch() 같은 색 함수)을 찾는다. 반투명한 색도 찾는다.
|
|
84
|
+
* @param {string} text
|
|
85
|
+
* @param {{ named?: boolean }} [options] named 가 true 면 white 같은 색 이름도 찾는다.
|
|
86
|
+
* 색을 값으로 받는 자리에서만 켠다. 일반 문자열에서는 그냥 단어일 수 있다
|
|
87
|
+
* @returns {{ index: number, text: string, value: string }[]}
|
|
88
|
+
*/
|
|
89
|
+
export function findColorValues(text, { named = false } = {}) {
|
|
90
|
+
const matches = [...text.matchAll(COLOR_VALUE), ...(named ? text.matchAll(NAMED_VALUE) : [])];
|
|
91
|
+
return matches
|
|
92
|
+
.filter((match) => parseColor(match[0]) !== null)
|
|
93
|
+
.sort((a, b) => a.index - b.index)
|
|
94
|
+
.map((match) => ({ index: match.index, text: match[0], value: match[0] }));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function parseHex(text) {
|
|
98
|
+
if (!HEX.test(text)) return null;
|
|
99
|
+
let digits = text.slice(1).toLowerCase();
|
|
100
|
+
if (digits.length <= 4) digits = [...digits].map((d) => d + d).join("");
|
|
101
|
+
const alpha = digits.length === 8 ? parseInt(digits.slice(6), 16) / 255 : 1;
|
|
102
|
+
return { key: `#${digits.slice(0, 6)}`, alpha, opaque: alpha >= 1 };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** "50%" → max 의 절반, "128" → 128. 숫자가 아니면 null. */
|
|
106
|
+
function unit(text, max) {
|
|
107
|
+
const match = /^(-?[\d.]+)(%?)$/.exec(text);
|
|
108
|
+
if (!match || Number.isNaN(Number(match[1]))) return null;
|
|
109
|
+
const number = Number(match[1]);
|
|
110
|
+
return match[2] ? (number / 100) * max : number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function hslToRgb([hue, saturation, lightness]) {
|
|
114
|
+
const h = /^(-?[\d.]+)(?:deg)?$/i.exec(hue);
|
|
115
|
+
const s = unit(saturation.replace(/%$/, ""), 1);
|
|
116
|
+
const l = unit(lightness.replace(/%$/, ""), 1);
|
|
117
|
+
if (!h || s === null || l === null) return null;
|
|
118
|
+
const [sat, light] = [s / 100, l / 100];
|
|
119
|
+
const chroma = (1 - Math.abs(2 * light - 1)) * sat;
|
|
120
|
+
const sector = (((Number(h[1]) % 360) + 360) % 360) / 60;
|
|
121
|
+
const x = chroma * (1 - Math.abs((sector % 2) - 1));
|
|
122
|
+
const [r, g, b] = [
|
|
123
|
+
[chroma, x, 0],
|
|
124
|
+
[x, chroma, 0],
|
|
125
|
+
[0, chroma, x],
|
|
126
|
+
[0, x, chroma],
|
|
127
|
+
[x, 0, chroma],
|
|
128
|
+
[chroma, 0, x],
|
|
129
|
+
][Math.floor(sector) % 6];
|
|
130
|
+
const m = light - chroma / 2;
|
|
131
|
+
return [r, g, b].map((channel) => (channel + m) * 255);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const toByte = (channel) =>
|
|
135
|
+
Math.round(Math.min(255, Math.max(0, channel)))
|
|
136
|
+
.toString(16)
|
|
137
|
+
.padStart(2, "0");
|
package/src/core/css.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import postcss from "postcss";
|
|
2
|
+
import { findArbitraryColors } from "./classes.js";
|
|
3
|
+
import { findColorValues, isColorProperty, isNamedColor } from "./color.js";
|
|
2
4
|
|
|
3
|
-
const HEX_COLOR = /(?<![\w-])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
|
|
4
5
|
// 색이 아닌 # 이 들어갈 수 있는 곳: url(#id), "문자열", /* 주석 */
|
|
5
6
|
const NOT_A_VALUE = /url\([^)]*\)|"[^"]*"|'[^']*'|\/\*[\s\S]*?\*\//g;
|
|
6
7
|
const DISABLE_NEXT_LINE = "designsnitch-disable-next-line";
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
|
-
* CSS 의 선언 값에서 hex
|
|
10
|
+
* CSS 의 선언 값에서 색(hex 와 rgb(), hsl(), oklch())을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
|
|
10
11
|
* 토큰 CSS 에서는 옵션을 켜서 사용자 정의 속성 선언을 건너뛸 수 있다.
|
|
11
12
|
* 바로 앞에 designsnitch-disable-next-line 주석이 있는 선언의 색은 disabled 로 표시한다.
|
|
12
13
|
* @param {string} css
|
|
13
14
|
* @param {{ skipCustomProperties?: boolean }} [options]
|
|
14
|
-
* @
|
|
15
|
+
* @apply 에 쓴 임의 값 색 클래스도 찾는다. 그때는 prop 대신 utility 와 클래스 전체(text)가 붙는다.
|
|
16
|
+
* @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop?: string, utility?: string, text?: string, disabled: boolean }[]}
|
|
15
17
|
* @throws {import("postcss").CssSyntaxError} CSS 를 읽지 못했을 때
|
|
16
18
|
*/
|
|
17
19
|
export function findCssColors(css, { skipCustomProperties = false } = {}) {
|
|
@@ -26,30 +28,56 @@ export function findCssColors(css, { skipCustomProperties = false } = {}) {
|
|
|
26
28
|
};
|
|
27
29
|
|
|
28
30
|
const found = [];
|
|
29
|
-
postcss.parse(css)
|
|
31
|
+
const root = postcss.parse(css);
|
|
32
|
+
const isDisabled = (node) => {
|
|
33
|
+
const previous = node.prev();
|
|
34
|
+
return previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
root.walkAtRules("apply", (rule) => {
|
|
38
|
+
const raw = rule.raws.params?.raw ?? rule.params;
|
|
39
|
+
const paramsStart = rule.source.start.offset + 1 + rule.name.length + (rule.raws.afterName ?? "").length;
|
|
40
|
+
for (const match of findArbitraryColors(raw)) {
|
|
41
|
+
const start = position(paramsStart + match.index);
|
|
42
|
+
const end = position(paramsStart + match.index + match.text.length);
|
|
43
|
+
found.push({
|
|
44
|
+
line: start.line,
|
|
45
|
+
column: start.column,
|
|
46
|
+
endLine: end.line,
|
|
47
|
+
endColumn: end.column,
|
|
48
|
+
value: match.value,
|
|
49
|
+
utility: match.utility,
|
|
50
|
+
text: match.text,
|
|
51
|
+
disabled: isDisabled(rule),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
root.walkDecls((decl) => {
|
|
30
57
|
if (skipCustomProperties && decl.prop.startsWith("--")) return;
|
|
31
58
|
|
|
32
|
-
const
|
|
33
|
-
const disabled = previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
|
|
59
|
+
const disabled = isDisabled(decl);
|
|
34
60
|
|
|
35
61
|
// 위치를 정확히 잡으려고 정리된 값이 아니라 원본 텍스트에서 찾는다.
|
|
36
62
|
const raw = decl.raws.value?.raw ?? decl.value;
|
|
37
63
|
const valueStart = decl.source.start.offset + decl.prop.length + decl.raws.between.length;
|
|
38
64
|
const masked = raw.replace(NOT_A_VALUE, (skipped) => " ".repeat(skipped.length));
|
|
39
65
|
|
|
40
|
-
|
|
66
|
+
// 색 이름은 색 속성에서만, 변수 선언에서는 값 전체가 색 이름일 때만 색으로 본다.
|
|
67
|
+
const named = decl.prop.startsWith("--") ? isNamedColor(raw) : isColorProperty(decl.prop);
|
|
68
|
+
for (const match of findColorValues(masked, { named })) {
|
|
41
69
|
const start = position(valueStart + match.index);
|
|
42
|
-
const end = position(valueStart + match.index + match
|
|
70
|
+
const end = position(valueStart + match.index + match.text.length);
|
|
43
71
|
found.push({
|
|
44
72
|
line: start.line,
|
|
45
73
|
column: start.column,
|
|
46
74
|
endLine: end.line,
|
|
47
75
|
endColumn: end.column,
|
|
48
|
-
value: match
|
|
76
|
+
value: match.text,
|
|
49
77
|
prop: decl.prop,
|
|
50
78
|
disabled,
|
|
51
79
|
});
|
|
52
80
|
}
|
|
53
81
|
});
|
|
54
|
-
return found;
|
|
82
|
+
return found.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
55
83
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// CSS 의 색 이름 → hex (CSS Color Module Level 4). transparent 와 currentColor 는 색 값이 아니라서 없다.
|
|
2
|
+
export const NAMED_COLORS = {
|
|
3
|
+
aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff", aquamarine: "7fffd4", azure: "f0ffff",
|
|
4
|
+
beige: "f5f5dc", bisque: "ffe4c4", black: "000000", blanchedalmond: "ffebcd", blue: "0000ff",
|
|
5
|
+
blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00",
|
|
6
|
+
chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c",
|
|
7
|
+
cyan: "00ffff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9",
|
|
8
|
+
darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b",
|
|
9
|
+
darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000",
|
|
10
|
+
darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f",
|
|
11
|
+
darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493",
|
|
12
|
+
deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222",
|
|
13
|
+
floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc", ghostwhite: "f8f8ff",
|
|
14
|
+
gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f",
|
|
15
|
+
grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082",
|
|
16
|
+
ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00",
|
|
17
|
+
lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff",
|
|
18
|
+
lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3",
|
|
19
|
+
lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa",
|
|
20
|
+
lightslategray: "778899", lightslategrey: "778899", lightsteelblue: "b0c4de", lightyellow: "ffffe0",
|
|
21
|
+
lime: "00ff00", limegreen: "32cd32", linen: "faf0e6", magenta: "ff00ff", maroon: "800000",
|
|
22
|
+
mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db",
|
|
23
|
+
mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a",
|
|
24
|
+
mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa",
|
|
25
|
+
mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6",
|
|
26
|
+
olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6",
|
|
27
|
+
palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093",
|
|
28
|
+
papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd",
|
|
29
|
+
powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "ff0000", rosybrown: "bc8f8f",
|
|
30
|
+
royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57",
|
|
31
|
+
seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd",
|
|
32
|
+
slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4",
|
|
33
|
+
tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee",
|
|
34
|
+
wheat: "f5deb3", white: "ffffff", whitesmoke: "f5f5f5", yellow: "ffff00", yellowgreen: "9acd32",
|
|
35
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// oklch(L C H) → sRGB hex. 공식은 CSS Color 4 의 OKLab 정의를 따른다.
|
|
2
|
+
// 값 대신 none 을 쓸 수 있다(CSS Color 4). Tailwind 4.3.5 부터 회색의 색상(hue)을 none 으로 적는다.
|
|
3
|
+
const OKLCH =
|
|
4
|
+
/^oklch\(\s*([\d.]+|none)(%?)\s+([\d.]+|none)\s+([\d.]+|none)(?:deg)?\s*(?:\/\s*([\d.]+%?|none)\s*)?\)$/i;
|
|
5
|
+
// none 은 계산할 때 0 으로 본다.
|
|
6
|
+
const num = (text) => (text.toLowerCase() === "none" ? 0 : Number(text));
|
|
7
|
+
// 반올림 오차로 범위를 조금 넘는 것은 sRGB 안으로 본다.
|
|
8
|
+
const EPSILON = 0.0005;
|
|
9
|
+
const round = (number, digits) => Number(number.toFixed(digits));
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* oklch 색을 비교용 표기로 읽는다. oklch 가 아니면 null.
|
|
13
|
+
* @param {string} value
|
|
14
|
+
* @returns {{ key: string, alpha: number, opaque: boolean } | null} key 는 sRGB 안이면 소문자 6자리 hex,
|
|
15
|
+
* 밖이면 자릿수를 맞춘 "oklch(L C H)". 같은 색을 내는 hex 가 없기 때문이다
|
|
16
|
+
*/
|
|
17
|
+
export function oklchKey(value) {
|
|
18
|
+
const match = OKLCH.exec(value.trim());
|
|
19
|
+
if (!match) return null;
|
|
20
|
+
const L = num(match[1]) / (match[2] ? 100 : 1);
|
|
21
|
+
const C = num(match[3]);
|
|
22
|
+
const H = num(match[4]);
|
|
23
|
+
const alpha = match[5] === undefined ? 1 : match[5].endsWith("%") ? Number(match[5].slice(0, -1)) / 100 : num(match[5]);
|
|
24
|
+
const h = (H * Math.PI) / 180;
|
|
25
|
+
const a = C * Math.cos(h);
|
|
26
|
+
const b = C * Math.sin(h);
|
|
27
|
+
|
|
28
|
+
const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
29
|
+
const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
30
|
+
const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
31
|
+
const linear = [
|
|
32
|
+
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
|
|
33
|
+
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
|
|
34
|
+
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
|
|
35
|
+
];
|
|
36
|
+
const opaque = alpha >= 1;
|
|
37
|
+
if (linear.some((c) => c < -EPSILON || c > 1 + EPSILON)) {
|
|
38
|
+
const hue = C === 0 ? 0 : round(((H % 360) + 360) % 360, 3);
|
|
39
|
+
return { key: `oklch(${round(L, 4)} ${round(C, 4)} ${hue})`, alpha, opaque };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const toByte = (c) => {
|
|
43
|
+
const v = Math.min(1, Math.max(0, c));
|
|
44
|
+
const srgb = v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;
|
|
45
|
+
return Math.round(srgb * 255).toString(16).padStart(2, "0");
|
|
46
|
+
};
|
|
47
|
+
return { key: `#${linear.map(toByte).join("")}`, alpha, opaque };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* oklch 색을 sRGB hex(소문자 6자리)로 바꾼다. sRGB 밖의 색이거나 oklch 가 아니면 null.
|
|
52
|
+
* @param {string} value
|
|
53
|
+
* @returns {string | null}
|
|
54
|
+
*/
|
|
55
|
+
export function oklchToHex(value) {
|
|
56
|
+
const color = oklchKey(value);
|
|
57
|
+
return color?.opaque && color.key.startsWith("#") ? color.key : null;
|
|
58
|
+
}
|
package/src/core/tokens.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import postcss from "postcss";
|
|
2
|
-
import {
|
|
2
|
+
import { normalizeColor, parseColor } from "./color.js";
|
|
3
3
|
|
|
4
4
|
const COLOR_TOKEN = /^--color-/;
|
|
5
5
|
const ROLE_PREFIXES = {
|
|
@@ -7,6 +7,27 @@ const ROLE_PREFIXES = {
|
|
|
7
7
|
border: ["--color-border-"],
|
|
8
8
|
bg: ["--color-bg-", "--color-surface", "--color-background"],
|
|
9
9
|
};
|
|
10
|
+
// 값을 정할 수 없다는 표시. 가리키는 변수가 없고 fallback 도 없는 경우다.
|
|
11
|
+
const UNRESOLVED = "";
|
|
12
|
+
// 조건이 맞을 때만 적용되는 at-rule. 그 안의 선언은 전역이 아니다.
|
|
13
|
+
const CONDITIONAL_AT_RULES = new Set(["media", "supports", "container", "scope", "starting-style"]);
|
|
14
|
+
// 문서 전체에 적용되는 선택자
|
|
15
|
+
const GLOBAL_SELECTOR = /^(?::root|html|:host|\*)$/;
|
|
16
|
+
|
|
17
|
+
/** 선언이 어디서나 적용되는지. @theme 안이거나, 조건 없는 :root, html, :host 규칙 안이다. */
|
|
18
|
+
function isGlobal(decl) {
|
|
19
|
+
let rule = null;
|
|
20
|
+
for (let node = decl.parent; node && node.type !== "root"; node = node.parent) {
|
|
21
|
+
if (node.type === "atrule") {
|
|
22
|
+
if (node.name === "theme") return true;
|
|
23
|
+
if (CONDITIONAL_AT_RULES.has(node.name)) return false;
|
|
24
|
+
} else if (node.type === "rule") {
|
|
25
|
+
rule ??= node;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return !rule || rule.selectors.every((selector) => GLOBAL_SELECTOR.test(selector.trim()));
|
|
29
|
+
}
|
|
30
|
+
|
|
10
31
|
// var(--name) 또는 var(--name, 대체값)
|
|
11
32
|
const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
|
|
12
33
|
|
|
@@ -26,39 +47,57 @@ export function parseColorTokens(css) {
|
|
|
26
47
|
* 색 값 → 토큰 표와 서로 다른 최종 값이 있는 토큰 이름을 함께 읽는다.
|
|
27
48
|
* @param {string} css
|
|
28
49
|
* @param {string[]} [exclude] 정확한 이름 또는 끝에 *가 붙은 이름 패턴
|
|
29
|
-
* @returns {{ colors: Map<string, string[]>, themed: Set<string
|
|
50
|
+
* @returns {{ colors: Map<string, string[]>, themed: Set<string>, names: Set<string>, resets: string[] }}
|
|
51
|
+
* names 는 값을 읽었든 못 읽었든 선언된 --color-* 이름, resets 는 initial 로 비운 네임스페이스(예: "--color-*")
|
|
30
52
|
*/
|
|
31
53
|
export function parseColorTokenData(css, exclude = []) {
|
|
32
|
-
/** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
|
|
54
|
+
/** @type {Map<string, { global: string[], scoped: string[] }>} 변수 이름 → 전역에서 선언된 값들과 일부에서만 선언된 값들 */
|
|
33
55
|
const declared = new Map();
|
|
34
56
|
postcss.parse(css).walkDecls(/^--/, (decl) => {
|
|
35
|
-
const values = declared.get(decl.prop) ?? [];
|
|
36
|
-
values.push(decl.value);
|
|
57
|
+
const values = declared.get(decl.prop) ?? { global: [], scoped: [] };
|
|
58
|
+
values[isGlobal(decl) ? "global" : "scoped"].push(decl.value);
|
|
37
59
|
declared.set(decl.prop, values);
|
|
38
60
|
});
|
|
39
61
|
|
|
40
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* 값이 결국 가리키는 값들. 값을 정할 수 없는 경우가 있으면 UNRESOLVED 가 섞인다.
|
|
64
|
+
* @returns {string[]}
|
|
65
|
+
*/
|
|
41
66
|
function resolve(value, visiting) {
|
|
42
67
|
const trimmed = value.trim();
|
|
43
68
|
const reference = VAR_REFERENCE.exec(trimmed);
|
|
44
69
|
if (!reference) return [trimmed];
|
|
45
70
|
const [, name, fallback] = reference;
|
|
46
71
|
if (visiting.has(name)) return [];
|
|
47
|
-
|
|
72
|
+
const whenMissing = () => (fallback ? resolve(fallback, visiting) : [UNRESOLVED]);
|
|
73
|
+
const target = declared.get(name);
|
|
74
|
+
if (!target) return whenMissing();
|
|
48
75
|
|
|
49
76
|
const next = new Set(visiting).add(name);
|
|
50
|
-
|
|
77
|
+
const values = [...target.global, ...target.scoped].flatMap((item) => resolve(item, next));
|
|
78
|
+
// 변수가 일부 선택자에만 있으면, 그 밖에서는 fallback 이 쓰인다.
|
|
79
|
+
return target.global.length === 0 ? [...whenMissing(), ...values] : values;
|
|
51
80
|
}
|
|
52
81
|
|
|
53
82
|
const colors = new Map();
|
|
54
83
|
const themed = new Set();
|
|
55
|
-
|
|
84
|
+
const names = new Set();
|
|
85
|
+
const resets = [];
|
|
86
|
+
for (const [name, { global, scoped }] of declared) {
|
|
87
|
+
// Tailwind 는 --color-*: initial 처럼 네임스페이스를 비울 수 있다. 토큰이 아니라 기본 테마를 지우는 선언이다.
|
|
88
|
+
if (name.endsWith("*")) {
|
|
89
|
+
if ([...global, ...scoped].some((value) => value.trim() === "initial")) resets.push(name);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
56
92
|
if (!COLOR_TOKEN.test(name)) continue;
|
|
93
|
+
// .promo { --color-promo: ... } 처럼 일부에서만 선언된 변수는 어디서나 쓸 수 있는 토큰이 아니다.
|
|
94
|
+
if (global.length === 0) continue;
|
|
95
|
+
names.add(name);
|
|
57
96
|
if (exclude.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) continue;
|
|
58
97
|
const resolved = new Set();
|
|
59
|
-
for (const value of
|
|
60
|
-
const color =
|
|
61
|
-
//
|
|
98
|
+
for (const value of [...global, ...scoped].flatMap((value) => resolve(value, new Set([name])))) {
|
|
99
|
+
const color = normalizeColor(value);
|
|
100
|
+
// 색으로 읽지 못한 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
|
|
62
101
|
const key = color ?? value;
|
|
63
102
|
if (resolved.has(key)) continue;
|
|
64
103
|
resolved.add(key);
|
|
@@ -68,7 +107,36 @@ export function parseColorTokenData(css, exclude = []) {
|
|
|
68
107
|
}
|
|
69
108
|
if (resolved.size > 1) themed.add(name);
|
|
70
109
|
}
|
|
71
|
-
return { colors, themed };
|
|
110
|
+
return { colors, themed, names, resets };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 토큰을 CSS 에서 가리키는 표기. Tailwind 접두어가 있으면 변수 이름에 붙는다. 예: var(--tw-color-brand) */
|
|
114
|
+
export function tokenVar(name, prefix) {
|
|
115
|
+
return `var(${prefix ? name.replace(/^--/, `--${prefix}-`) : name})`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 색 값에 맞는 토큰을 찾는다. 반투명한 색이면 불투명한 색의 토큰과 불투명도를 함께 준다.
|
|
120
|
+
* @param {Map<string, string[]>} colors 색 값 → 토큰 이름들
|
|
121
|
+
* @param {string} value
|
|
122
|
+
* @returns {{ names: string[], opacity: number | null }} opacity 는 반투명할 때의 불투명도(%). 불투명하면 null
|
|
123
|
+
*/
|
|
124
|
+
export function lookupColor(colors, value) {
|
|
125
|
+
const color = parseColor(value);
|
|
126
|
+
if (!color) return { names: [], opacity: null };
|
|
127
|
+
return { names: colors.get(color.key) ?? [], opacity: color.opaque ? null : Math.round(color.alpha * 100) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 토큰을 CSS 값으로 쓰는 표기. 불투명도가 있으면 투명과 섞는다. */
|
|
131
|
+
export function tokenValue(name, prefix, opacity) {
|
|
132
|
+
const reference = tokenVar(name, prefix);
|
|
133
|
+
return opacity === null ? reference : `color-mix(in srgb, ${reference} ${opacity}%, transparent)`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 토큰을 클래스로 쓰는 표기. 불투명도는 Tailwind 의 /50 꼴로 붙인다. 예: bg-brand/50 */
|
|
137
|
+
export function tokenClass(utility, name, opacity) {
|
|
138
|
+
const className = `${utility}-${name.replace(/^--color-/, "")}`;
|
|
139
|
+
return opacity === null ? className : `${className}/${opacity}`;
|
|
72
140
|
}
|
|
73
141
|
|
|
74
142
|
export function utilityColorPrefixes(utility) {
|
|
@@ -102,3 +170,18 @@ export function recommendColorCandidate(candidates, rolePrefixes) {
|
|
|
102
170
|
const matching = candidates.filter((candidate) => startsWithAny(candidate, rolePrefixes));
|
|
103
171
|
return matching.length === 1 ? matching[0] : null;
|
|
104
172
|
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Tailwind theme.css 같은 팔레트 CSS 에서 --color-* 의 값을 비교용 표기로 읽는다.
|
|
176
|
+
* sRGB 안의 색은 hex 가 되고, 밖의 oklch 는 oklch 표기로 남아 같은 oklch 값과만 맞는다.
|
|
177
|
+
* @param {string} css
|
|
178
|
+
* @returns {Map<string, string>} 토큰 이름 → 비교용 색 표기
|
|
179
|
+
*/
|
|
180
|
+
export function parsePaletteColors(css) {
|
|
181
|
+
const palette = new Map();
|
|
182
|
+
postcss.parse(css).walkDecls(COLOR_TOKEN, (decl) => {
|
|
183
|
+
const color = normalizeColor(decl.value);
|
|
184
|
+
if (color) palette.set(decl.prop, color);
|
|
185
|
+
});
|
|
186
|
+
return palette;
|
|
187
|
+
}
|
package/src/format.js
CHANGED
|
@@ -9,7 +9,7 @@ export function formatText({ designSystem, problems, summary, violations, decisi
|
|
|
9
9
|
const m = messages(lang);
|
|
10
10
|
// 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
|
|
11
11
|
const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
|
|
12
|
-
const uncheckedLine = unchecked?.
|
|
12
|
+
const uncheckedLine = unchecked?.colors > 0 ? [m.unchecked(unchecked)] : [];
|
|
13
13
|
|
|
14
14
|
if (violations.length === 0) {
|
|
15
15
|
return [...header, m.noViolations(summary), ...uncheckedLine, ""].join("\n");
|
|
@@ -37,7 +37,7 @@ export function formatText({ designSystem, problems, summary, violations, decisi
|
|
|
37
37
|
...header,
|
|
38
38
|
...sections,
|
|
39
39
|
m.summary(summary),
|
|
40
|
-
m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
|
|
40
|
+
m.actions({ replace: count("replace"), migrate: count("migrate"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
|
|
41
41
|
...uncheckedLine,
|
|
42
42
|
"",
|
|
43
43
|
].join("\n");
|
package/src/hook.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
|
+
import crypto from "node:crypto";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import os from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
@@ -9,13 +10,19 @@ import { messages, resolveLang } from "./messages.js";
|
|
|
9
10
|
const CHECKABLE = /\.(?:[cm]?[jt]s|[jt]sx|css)$/;
|
|
10
11
|
// Claude Code, Codex 는 Stop, Gemini CLI 는 AfterAgent 가 "작업을 끝내려 할 때"다.
|
|
11
12
|
const STOP_EVENTS = new Set(["Stop", "SubagentStop", "AfterAgent"]);
|
|
13
|
+
const SESSION_START = "SessionStart";
|
|
14
|
+
// 에이전트가 스스로 할 수 있고, 해도 화면과 동작이 같다고 볼 수 있는 일. 이것만 끝내는 것을 막는다.
|
|
15
|
+
const SAFE_TO_INSIST = new Set(["replace", "repair"]);
|
|
12
16
|
|
|
13
17
|
/**
|
|
14
18
|
* 코딩 에이전트의 훅에서 부르는 검사. 에이전트가 방금 고친 파일만 본다.
|
|
15
19
|
*
|
|
16
|
-
* - 파일을 고친 직후:
|
|
17
|
-
* - 작업을 끝내려 할 때(Stop):
|
|
18
|
-
* 사람이 정해야 하는
|
|
20
|
+
* - 파일을 고친 직후: 새 오류가 있으면 종료 코드 2와 함께 stderr 로 알린다.
|
|
21
|
+
* - 작업을 끝내려 할 때(Stop): 바꿔도 화면과 동작이 같은 새 오류(replace, repair)가 남아 있으면 2로 막는다.
|
|
22
|
+
* 사람이 정해야 하는 오류(ask)와 컴포넌트로 옮길 오류(migrate)만 남았으면 막지 않는다.
|
|
23
|
+
* 물어보려면 멈춰야 하고, 옮겨도 동작이 같은지는 도구가 알 수 없기 때문이다.
|
|
24
|
+
* - "새 오류"의 기준은 HEAD 와, 세션이 시작될 때 이미 바뀌어 있던 파일의 상태다.
|
|
25
|
+
* 세션 시작(SessionStart) 때, 없었으면 세션의 첫 수정 때 그 상태를 적어 둔다.
|
|
19
26
|
* - 경고는 막지 않는다. 설정 파일이 없는 프로젝트에서는 아무것도 하지 않는다.
|
|
20
27
|
*
|
|
21
28
|
* @param {object} options
|
|
@@ -32,34 +39,54 @@ export async function runHook({ cwd, input = "", configPath = CONFIG_FILE, lang
|
|
|
32
39
|
const eventName = event.hook_event_name ?? event.hookEventName;
|
|
33
40
|
const toolInput = event.tool_input ?? event.toolInput;
|
|
34
41
|
const stopping = STOP_EVENTS.has(eventName);
|
|
42
|
+
const sessionId = event.session_id ?? event.sessionId;
|
|
35
43
|
|
|
36
44
|
// 이미 한 번 막아서 에이전트가 고치는 중이면 다시 막지 않는다.
|
|
37
45
|
if (stopping && (event.stop_hook_active ?? event.stopHookActive)) return pass;
|
|
38
46
|
if (!fs.existsSync(path.resolve(cwd, configPath))) return pass;
|
|
39
47
|
|
|
48
|
+
const checkable = (list) =>
|
|
49
|
+
list
|
|
50
|
+
.map((file) => path.resolve(cwd, file))
|
|
51
|
+
.filter((file) => isInside(cwd, file) && CHECKABLE.test(file) && fs.existsSync(file))
|
|
52
|
+
.map((file) => path.relative(cwd, file));
|
|
40
53
|
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;
|
|
54
|
+
const files = eventName === SESSION_START ? [] : checkable(typeof edited === "string" ? [edited] : changedFiles(cwd));
|
|
46
55
|
|
|
47
|
-
const canBlock = (v) => v.severity === "error" && (!stopping || v.action
|
|
56
|
+
const canBlock = (v) => v.severity === "error" && (!stopping || SAFE_TO_INSIST.has(v.action));
|
|
48
57
|
let result;
|
|
49
58
|
let errors;
|
|
50
59
|
try {
|
|
51
60
|
const config = loadConfig(cwd, configPath, resolveLang(lang));
|
|
52
61
|
lang = resolveLang(lang, config.lang);
|
|
62
|
+
|
|
63
|
+
// 세션이 시작될 때 이미 있던 위반은 이번 작업이 만든 것이 아니다. 처음 한 번만 적어 둔다.
|
|
64
|
+
let session = sessionId ? readSession(cwd, sessionId) : new Map();
|
|
65
|
+
if (sessionId && !session && !stopping) {
|
|
66
|
+
// 세션 시작 때는 바뀐 파일 전부를, 첫 수정 때는 방금 고친 파일을 뺀 나머지를 적는다.
|
|
67
|
+
// 고친 파일을 모르면 무엇이 이번 작업인지 가릴 수 없으니 적지 않는다.
|
|
68
|
+
const own = path.relative(cwd, path.resolve(cwd, typeof edited === "string" ? edited : "."));
|
|
69
|
+
const canTell = eventName === SESSION_START || typeof edited === "string";
|
|
70
|
+
const before = canTell ? checkable(changedFiles(cwd)).filter((file) => file !== own) : [];
|
|
71
|
+
const found = before.length > 0 ? (await check({ cwd, config, paths: before, lang })).violations : [];
|
|
72
|
+
session = countViolations(found);
|
|
73
|
+
writeSession(cwd, sessionId, session);
|
|
74
|
+
}
|
|
75
|
+
if (files.length === 0) return pass;
|
|
76
|
+
|
|
53
77
|
result = await check({ cwd, config, paths: files, lang });
|
|
54
78
|
if (!result.violations.some(canBlock)) return pass;
|
|
55
79
|
|
|
56
|
-
const
|
|
80
|
+
const head = countViolations(await checkHead({ cwd, config, files, lang }));
|
|
57
81
|
const current = countViolations(result.violations);
|
|
58
82
|
errors = result.violations.filter((v) => {
|
|
59
83
|
const key = violationKey(v);
|
|
60
|
-
|
|
84
|
+
const baseline = Math.max(head.get(key) ?? 0, session?.get(key) ?? 0);
|
|
85
|
+
return v.severity === "error" && current.get(key) > baseline;
|
|
61
86
|
});
|
|
62
87
|
} catch (error) {
|
|
88
|
+
// 세션 시작은 알리기만 하는 자리가 아니다. 설정 문제는 첫 수정 때 알린다.
|
|
89
|
+
if (eventName === SESSION_START) return pass;
|
|
63
90
|
return { stderr: `${error.message}\n`, exitCode: 2 };
|
|
64
91
|
}
|
|
65
92
|
|
|
@@ -103,6 +130,30 @@ async function checkHead({ cwd, config, files, lang }) {
|
|
|
103
130
|
}
|
|
104
131
|
}
|
|
105
132
|
|
|
133
|
+
function sessionFile(cwd, sessionId) {
|
|
134
|
+
const id = crypto.createHash("sha256").update(`${fs.realpathSync(cwd)}\0${sessionId}`).digest("hex").slice(0, 40);
|
|
135
|
+
return path.join(os.tmpdir(), "designsnitch-sessions", `${id}.json`);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @returns {Map<string, number> | null} 세션이 시작될 때의 위반 개수. 적어 둔 것이 없으면 null */
|
|
139
|
+
function readSession(cwd, sessionId) {
|
|
140
|
+
try {
|
|
141
|
+
return new Map(JSON.parse(fs.readFileSync(sessionFile(cwd, String(sessionId)), "utf8")));
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function writeSession(cwd, sessionId, counts) {
|
|
148
|
+
try {
|
|
149
|
+
const file = sessionFile(cwd, String(sessionId));
|
|
150
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
151
|
+
fs.writeFileSync(file, JSON.stringify([...counts]));
|
|
152
|
+
} catch {
|
|
153
|
+
// 적어 두지 못하면 HEAD 만 기준으로 삼는다.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
106
157
|
function violationKey({ file, rule, found }) {
|
|
107
158
|
return JSON.stringify([file, rule, found]);
|
|
108
159
|
}
|