@slopdam/core 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 CHANGED
@@ -81,6 +81,38 @@ winston은 트랜스포트마다 로그 항목의 사본을 넘기므로 트랜
81
81
 
82
82
  두 연동 모두 pino나 winston을 불러오지 않으므로 `@slopdam/core`는 여전히 실행 의존성이 없습니다.
83
83
 
84
+ ### ESLint
85
+
86
+ ```js
87
+ // eslint.config.js
88
+ import slopdam from "@slopdam/core/eslint";
89
+
90
+ export default [slopdam.configs.recommended]; // 또는 slopdam.configs.dev
91
+ ```
92
+
93
+ ```
94
+ $ npx eslint src/
95
+ src/sync.js
96
+ 4:13 warning emoji.pictograph: '✅' should be '' slopdam/no-slop
97
+ 4:34 warning dash.run: 'ㅡ' should be ': ' slopdam/no-slop
98
+
99
+ $ npx eslint --fix src/
100
+ - log.info(`✅ ${rows.length}건 동기화 ㅡ 완료`);
101
+ + log.info(`${rows.length}건 동기화: 완료`);
102
+ ```
103
+
104
+ `slopdam/no-slop` 규칙은 `console.*` 호출과, 받는 쪽 이름에 `log`가 들어간 로거 호출(`log.info`, `this.logger.warn`)의 문자열 인자를 검사합니다. 템플릿 리터럴과 `"a" + b` 같은 이어 붙이기도 포함합니다. `eslint --fix`는 문자열 안의 글자만 고칩니다. 따옴표, 이스케이프, `${...}` 표현식, `%s` 서식 자리는 그대로 두고, 양 끝에 공백을 새로 남기지 않습니다. 옵션:
105
+
106
+ ```js
107
+ rules: {
108
+ "slopdam/no-slop": ["warn", {
109
+ profile: "dev", // Sanitizer와 같은 옵션: level, disable, dashInline
110
+ receivers: "log|console|audit", // 로그 호출의 받는 쪽 이름을 고르는 정규식
111
+ functions: ["print"], // 함께 검사할 일반 함수
112
+ }],
113
+ }
114
+ ```
115
+
84
116
  ### 옵션
85
117
 
86
118
  | 옵션 | 값 | 기본값 |
@@ -100,7 +132,7 @@ URL, 인라인 코드, `key=value`의 값, 파일 경로는 바꾸지 않습니
100
132
 
101
133
  ## 로드맵
102
134
 
103
- slopdam 0.5 마일스톤의 일부입니다([로드맵](https://github.com/slopdam/slopdam/blob/main/ROADMAP.ko.md)). 핵심 패키지와 pino, winston 연동에 이어 `eslint-plugin-slopdam`을 만듭니다.
135
+ slopdam 0.5 마일스톤의 일부입니다([로드맵](https://github.com/slopdam/slopdam/blob/main/ROADMAP.ko.md)). 핵심 패키지, pino와 winston 연동, ESLint 규칙으로 이루어집니다.
104
136
 
105
137
  ## 기여
106
138
 
package/README.md CHANGED
@@ -81,6 +81,38 @@ winston gives every transport its own copy of the entry, so each one can use its
81
81
 
82
82
  Neither integration imports pino or winston, so `@slopdam/core` still has no runtime dependencies.
83
83
 
84
+ ### ESLint
85
+
86
+ ```js
87
+ // eslint.config.js
88
+ import slopdam from "@slopdam/core/eslint";
89
+
90
+ export default [slopdam.configs.recommended]; // or slopdam.configs.dev
91
+ ```
92
+
93
+ ```
94
+ $ npx eslint src/
95
+ src/sync.js
96
+ 4:13 warning emoji.pictograph: '✅' should be '' slopdam/no-slop
97
+ 4:41 warning dash.run: '—' should be ': ' slopdam/no-slop
98
+
99
+ $ npx eslint --fix src/
100
+ - log.info(`✅ Synced ${rows.length} rows — done`);
101
+ + log.info(`Synced ${rows.length} rows: done`);
102
+ ```
103
+
104
+ The rule `slopdam/no-slop` checks the string arguments of `console.*` calls and of logger calls whose receiver contains `log` (`log.info`, `this.logger.warn`), including template literals and `"a" + b` concatenations. `eslint --fix` edits only the text of the literal: quotes, escape sequences, `${...}` expressions and `%s` placeholders stay, and no space is added at either end. Options:
105
+
106
+ ```js
107
+ rules: {
108
+ "slopdam/no-slop": ["warn", {
109
+ profile: "dev", // same options as Sanitizer: level, disable, dashInline
110
+ receivers: "log|console|audit", // regular expression for the receiver of a log call
111
+ functions: ["print"], // plain functions to check as well
112
+ }],
113
+ }
114
+ ```
115
+
84
116
  ### Options
85
117
 
86
118
  | Option | Values | Default |
@@ -100,7 +132,7 @@ The rules are not rewritten by hand. The build reads the repository's [spec/](ht
100
132
 
101
133
  ## Roadmap
102
134
 
103
- Part of slopdam milestone 0.5 ([roadmap](https://github.com/slopdam/slopdam/blob/main/ROADMAP.md)): the core package and the pino and winston integrations, then `eslint-plugin-slopdam`.
135
+ Part of slopdam milestone 0.5 ([roadmap](https://github.com/slopdam/slopdam/blob/main/ROADMAP.md)): the core package, the pino and winston integrations and the ESLint rule.
104
136
 
105
137
  ## Contributing
106
138
 
@@ -0,0 +1,87 @@
1
+ /**
2
+ * ESLint plugin (flat config). The rule slopdam/no-slop reports AI traces in the string
3
+ * arguments of log calls and fixes them:
4
+ *
5
+ * // eslint.config.js
6
+ * import slopdam from "@slopdam/core/eslint";
7
+ * export default [slopdam.configs.recommended];
8
+ *
9
+ * Like `slopdam fix` for Python, a fix edits only the text of the literal: quotes, escape
10
+ * sequences, `${...}` expressions and printf placeholders such as %s stay as they are, and no
11
+ * space is left at either end that the literal did not have. ESLint is not imported here.
12
+ */
13
+ import { type SanitizerOptions } from "./sanitizer.js";
14
+ type Node = any;
15
+ type Context = any;
16
+ export interface NoSlopOptions extends SanitizerOptions {
17
+ /** A call counts as a log call when the receiver's source text matches. Default: /log|console/i. */
18
+ receivers?: string;
19
+ /** Method names of log calls. Default: the common logger levels and console methods. */
20
+ methods?: string[];
21
+ /** Plain function calls to check as well, such as ["print"]. Default: none. */
22
+ functions?: string[];
23
+ }
24
+ declare const noSlop: {
25
+ meta: {
26
+ type: string;
27
+ docs: {
28
+ description: string;
29
+ url: string;
30
+ };
31
+ fixable: string;
32
+ schema: {
33
+ type: string;
34
+ properties: {
35
+ profile: {
36
+ enum: string[];
37
+ };
38
+ level: {
39
+ enum: string[];
40
+ };
41
+ disable: {
42
+ type: string;
43
+ items: {
44
+ type: string;
45
+ };
46
+ };
47
+ dashInline: {
48
+ enum: string[];
49
+ };
50
+ receivers: {
51
+ type: string;
52
+ };
53
+ methods: {
54
+ type: string;
55
+ items: {
56
+ type: string;
57
+ };
58
+ };
59
+ functions: {
60
+ type: string;
61
+ items: {
62
+ type: string;
63
+ };
64
+ };
65
+ };
66
+ additionalProperties: boolean;
67
+ }[];
68
+ messages: {
69
+ fixable: string;
70
+ report: string;
71
+ };
72
+ };
73
+ create(context: Context): {
74
+ CallExpression(call: Node): void;
75
+ };
76
+ };
77
+ declare const plugin: {
78
+ meta: {
79
+ name: string;
80
+ };
81
+ rules: {
82
+ "no-slop": typeof noSlop;
83
+ };
84
+ configs: Record<string, unknown>;
85
+ };
86
+ export default plugin;
87
+ export { noSlop };
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.noSlop = void 0;
4
+ // SPDX-License-Identifier: MIT
5
+ /**
6
+ * ESLint plugin (flat config). The rule slopdam/no-slop reports AI traces in the string
7
+ * arguments of log calls and fixes them:
8
+ *
9
+ * // eslint.config.js
10
+ * import slopdam from "@slopdam/core/eslint";
11
+ * export default [slopdam.configs.recommended];
12
+ *
13
+ * Like `slopdam fix` for Python, a fix edits only the text of the literal: quotes, escape
14
+ * sequences, `${...}` expressions and printf placeholders such as %s stay as they are, and no
15
+ * space is left at either end that the literal did not have. ESLint is not imported here.
16
+ */
17
+ const sanitizer_js_1 = require("./sanitizer.js");
18
+ const DEFAULT_METHODS = [
19
+ "log", "info", "warn", "warning", "error", "debug", "trace", "fatal", "critical", "exception",
20
+ "notice", "verbose", "silly", "http",
21
+ ];
22
+ // Same placeholders as the Python fixer: printf-style %s, %d, %(name)s and {...}.
23
+ const PLACEHOLDER = /%(?:\([^)]*\))?[-#0 +]*\d*(?:\.\d+)?[sdifrxXeEgGcoaub%jO]|\{[^{}]*\}/g;
24
+ // Each masked piece becomes one character from the private-use plane, which the rules treat as
25
+ // part of a word (a dash next to it sits between words) and never change.
26
+ const MASK_BASE = 0xf8000;
27
+ function mask(body, spans) {
28
+ let text = "";
29
+ const pieces = [];
30
+ const index = [];
31
+ let last = 0;
32
+ for (const [a, b] of spans) {
33
+ text += body.slice(last, a);
34
+ for (let i = last; i < a; i++)
35
+ index.push(i);
36
+ const c = String.fromCodePoint(MASK_BASE + pieces.length);
37
+ text += c;
38
+ for (let k = 0; k < c.length; k++)
39
+ index.push(a);
40
+ pieces.push(body.slice(a, b));
41
+ last = b;
42
+ }
43
+ text += body.slice(last);
44
+ for (let i = last; i <= body.length; i++)
45
+ index.push(i);
46
+ return { text, pieces, where: (i) => index[Math.min(i, index.length - 1)] };
47
+ }
48
+ function unmask(text, pieces) {
49
+ const seen = [];
50
+ for (const c of text) {
51
+ const n = c.codePointAt(0) - MASK_BASE;
52
+ if (n >= 0 && n < pieces.length)
53
+ seen.push(n);
54
+ }
55
+ if (seen.length !== pieces.length || seen.some((n, i) => n !== i))
56
+ return null; // a rule swallowed a piece
57
+ return [...text].map((c) => {
58
+ const n = c.codePointAt(0) - MASK_BASE;
59
+ return n >= 0 && n < pieces.length ? pieces[n] : c;
60
+ }).join("");
61
+ }
62
+ const noSlop = {
63
+ meta: {
64
+ type: "suggestion",
65
+ docs: {
66
+ description: "Disallow AI-generated traces (em dashes, emoji, separators, markdown) in log messages",
67
+ url: "https://github.com/slopdam/slopdam/blob/main/js/README.md#eslint",
68
+ },
69
+ fixable: "code",
70
+ schema: [
71
+ {
72
+ type: "object",
73
+ properties: {
74
+ profile: { enum: ["reader", "dev"] },
75
+ level: { enum: ["basic", "strong", "strict"] },
76
+ disable: { type: "array", items: { type: "string" } },
77
+ dashInline: { enum: ["comma", "colon", "hyphen", "space"] },
78
+ receivers: { type: "string" },
79
+ methods: { type: "array", items: { type: "string" } },
80
+ functions: { type: "array", items: { type: "string" } },
81
+ },
82
+ additionalProperties: false,
83
+ },
84
+ ],
85
+ messages: {
86
+ fixable: "{{rule}}: '{{text}}' should be '{{fix}}'",
87
+ report: "{{rule}}: '{{text}}'",
88
+ },
89
+ },
90
+ create(context) {
91
+ const options = context.options[0] ?? {};
92
+ const { receivers = "log|console", methods = DEFAULT_METHODS, functions = [], ...sanitizerOptions } = options;
93
+ const sanitizer = new sanitizer_js_1.Sanitizer(sanitizerOptions);
94
+ const receiverRe = new RegExp(receivers, "i");
95
+ const methodSet = new Set(methods);
96
+ const functionSet = new Set(functions);
97
+ const source = context.sourceCode ?? context.getSourceCode();
98
+ function isLogCall(call) {
99
+ const callee = call.callee;
100
+ if (callee.type === "Identifier")
101
+ return functionSet.has(callee.name);
102
+ if (callee.type !== "MemberExpression")
103
+ return false;
104
+ const name = callee.computed ? (callee.property.type === "Literal" ? String(callee.property.value) : null) : callee.property.name;
105
+ return name !== null && methodSet.has(name) && receiverRe.test(source.getText(callee.object));
106
+ }
107
+ /** The literal's body (between the quotes or backticks) and the pieces that must not change. */
108
+ function bodyOf(node) {
109
+ const raw = source.getText(node);
110
+ const start = node.range[0] + 1;
111
+ const body = raw.slice(1, -1);
112
+ if (node.type === "Literal") {
113
+ if (typeof node.value !== "string")
114
+ return null;
115
+ const spans = [];
116
+ for (const m of body.matchAll(PLACEHOLDER))
117
+ if (m[0] !== "%%")
118
+ spans.push([m.index, m.index + m[0].length]);
119
+ return { start, body, spans, quote: raw[0] };
120
+ }
121
+ // Template literal: mask every ${...}, braces and inner spaces included.
122
+ const spans = node.expressions.map((e) => [
123
+ source.getTokenBefore(e).range[1] - 2 - start,
124
+ source.getTokenAfter(e).range[0] + 1 - start,
125
+ ]);
126
+ return { start, body, spans, quote: "`" };
127
+ }
128
+ /** joinedBefore/After: the literal is concatenated with something on that side ("a — " + b). */
129
+ function check(node, joinedBefore, joinedAfter) {
130
+ const part = bodyOf(node);
131
+ if (!part)
132
+ return;
133
+ const { start, body, quote } = part;
134
+ // An empty piece at a joined end stands for the neighbor, so a dash there is between words.
135
+ const spans = [
136
+ ...(joinedBefore ? [[0, 0]] : []),
137
+ ...part.spans,
138
+ ...(joinedAfter ? [[body.length, body.length]] : []),
139
+ ];
140
+ const masked = mask(body, spans);
141
+ const found = sanitizer.findings(masked.text);
142
+ if (!found.length)
143
+ return;
144
+ // Apply each fix at its span, as the Python fixer does; overlapping findings are skipped.
145
+ let out = "";
146
+ let last = 0;
147
+ const shown = [];
148
+ for (const f of found) {
149
+ if (f.start < last)
150
+ continue;
151
+ shown.push(f);
152
+ if (f.fix === null)
153
+ continue;
154
+ let fix = f.fix;
155
+ if (fix.includes("\\") || fix.includes(quote) || (quote === "`" && fix.includes("${"))) {
156
+ fix = fix.replace(/\\/g, "\\\\").split(quote).join("\\" + quote).replace(/\$\{/g, "\\${");
157
+ }
158
+ out += masked.text.slice(last, f.start) + fix;
159
+ last = f.end;
160
+ }
161
+ out += masked.text.slice(last);
162
+ let newBody = unmask(out, masked.pieces);
163
+ if (newBody !== null) {
164
+ // Do not leave a space at either end that the original literal did not have.
165
+ if (body === body.replace(/^\s+/, ""))
166
+ newBody = newBody.replace(/^[ \t]+/, "");
167
+ if (body === body.replace(/\s+$/, ""))
168
+ newBody = newBody.replace(/[ \t]+$/, "");
169
+ }
170
+ const replacement = newBody !== null && newBody !== body ? quote + newBody + quote : null;
171
+ for (const f of shown) {
172
+ const from = start + masked.where(f.start);
173
+ const to = start + masked.where(f.end);
174
+ context.report({
175
+ node,
176
+ loc: { start: source.getLocFromIndex(from), end: source.getLocFromIndex(to) },
177
+ messageId: f.fix === null ? "report" : "fixable",
178
+ data: { rule: f.ruleId, text: f.text, fix: f.fix ?? "" },
179
+ fix: replacement === null ? null : (fixer) => fixer.replaceTextRange(node.range, replacement),
180
+ });
181
+ }
182
+ }
183
+ /** The operands of a + chain, left to right: "a" + b + "c" -> ["a", b, "c"]. */
184
+ function operands(node, out) {
185
+ if (node.type === "BinaryExpression" && node.operator === "+") {
186
+ operands(node.left, out);
187
+ operands(node.right, out);
188
+ }
189
+ else
190
+ out.push(node);
191
+ return out;
192
+ }
193
+ const isString = (n) => (n.type === "Literal" && typeof n.value === "string") || n.type === "TemplateLiteral";
194
+ return {
195
+ CallExpression(call) {
196
+ if (!isLogCall(call))
197
+ return;
198
+ for (const arg of call.arguments) {
199
+ const parts = operands(arg, []);
200
+ parts.forEach((p, i) => {
201
+ if (isString(p))
202
+ check(p, i > 0, i < parts.length - 1);
203
+ });
204
+ }
205
+ },
206
+ };
207
+ },
208
+ };
209
+ exports.noSlop = noSlop;
210
+ const plugin = {
211
+ meta: { name: "@slopdam/core/eslint" },
212
+ rules: { "no-slop": noSlop },
213
+ configs: {},
214
+ };
215
+ plugin.configs = {
216
+ /** slopdam/no-slop as a warning, reader profile. */
217
+ recommended: { name: "slopdam/recommended", plugins: { slopdam: plugin }, rules: { "slopdam/no-slop": "warn" } },
218
+ /** Same, with dev-style fixes ([OK] tags, " - " for dashes). */
219
+ dev: { name: "slopdam/dev", plugins: { slopdam: plugin }, rules: { "slopdam/no-slop": ["warn", { profile: "dev" }] } },
220
+ };
221
+ exports.default = plugin;
@@ -33,8 +33,8 @@ exports.SPEC = {
33
33
  },
34
34
  "hangul_choseong": "ᄀ-ᅟꥠ-ꥼ"
35
35
  },
36
- "dash_word_before": ")]}%",
37
- "dash_word_after": "([{",
36
+ "dash_word_before": ")]}%\"'”’",
37
+ "dash_word_after": "([{\"'“‘",
38
38
  "tidy": {
39
39
  "multi_space": "(?<=\\S)[ \\t]{2,}",
40
40
  "max_passes": 8
@@ -0,0 +1,87 @@
1
+ /**
2
+ * ESLint plugin (flat config). The rule slopdam/no-slop reports AI traces in the string
3
+ * arguments of log calls and fixes them:
4
+ *
5
+ * // eslint.config.js
6
+ * import slopdam from "@slopdam/core/eslint";
7
+ * export default [slopdam.configs.recommended];
8
+ *
9
+ * Like `slopdam fix` for Python, a fix edits only the text of the literal: quotes, escape
10
+ * sequences, `${...}` expressions and printf placeholders such as %s stay as they are, and no
11
+ * space is left at either end that the literal did not have. ESLint is not imported here.
12
+ */
13
+ import { type SanitizerOptions } from "./sanitizer.js";
14
+ type Node = any;
15
+ type Context = any;
16
+ export interface NoSlopOptions extends SanitizerOptions {
17
+ /** A call counts as a log call when the receiver's source text matches. Default: /log|console/i. */
18
+ receivers?: string;
19
+ /** Method names of log calls. Default: the common logger levels and console methods. */
20
+ methods?: string[];
21
+ /** Plain function calls to check as well, such as ["print"]. Default: none. */
22
+ functions?: string[];
23
+ }
24
+ declare const noSlop: {
25
+ meta: {
26
+ type: string;
27
+ docs: {
28
+ description: string;
29
+ url: string;
30
+ };
31
+ fixable: string;
32
+ schema: {
33
+ type: string;
34
+ properties: {
35
+ profile: {
36
+ enum: string[];
37
+ };
38
+ level: {
39
+ enum: string[];
40
+ };
41
+ disable: {
42
+ type: string;
43
+ items: {
44
+ type: string;
45
+ };
46
+ };
47
+ dashInline: {
48
+ enum: string[];
49
+ };
50
+ receivers: {
51
+ type: string;
52
+ };
53
+ methods: {
54
+ type: string;
55
+ items: {
56
+ type: string;
57
+ };
58
+ };
59
+ functions: {
60
+ type: string;
61
+ items: {
62
+ type: string;
63
+ };
64
+ };
65
+ };
66
+ additionalProperties: boolean;
67
+ }[];
68
+ messages: {
69
+ fixable: string;
70
+ report: string;
71
+ };
72
+ };
73
+ create(context: Context): {
74
+ CallExpression(call: Node): void;
75
+ };
76
+ };
77
+ declare const plugin: {
78
+ meta: {
79
+ name: string;
80
+ };
81
+ rules: {
82
+ "no-slop": typeof noSlop;
83
+ };
84
+ configs: Record<string, unknown>;
85
+ };
86
+ export default plugin;
87
+ export { noSlop };
@@ -0,0 +1,218 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * ESLint plugin (flat config). The rule slopdam/no-slop reports AI traces in the string
4
+ * arguments of log calls and fixes them:
5
+ *
6
+ * // eslint.config.js
7
+ * import slopdam from "@slopdam/core/eslint";
8
+ * export default [slopdam.configs.recommended];
9
+ *
10
+ * Like `slopdam fix` for Python, a fix edits only the text of the literal: quotes, escape
11
+ * sequences, `${...}` expressions and printf placeholders such as %s stay as they are, and no
12
+ * space is left at either end that the literal did not have. ESLint is not imported here.
13
+ */
14
+ import { Sanitizer } from "./sanitizer.js";
15
+ const DEFAULT_METHODS = [
16
+ "log", "info", "warn", "warning", "error", "debug", "trace", "fatal", "critical", "exception",
17
+ "notice", "verbose", "silly", "http",
18
+ ];
19
+ // Same placeholders as the Python fixer: printf-style %s, %d, %(name)s and {...}.
20
+ const PLACEHOLDER = /%(?:\([^)]*\))?[-#0 +]*\d*(?:\.\d+)?[sdifrxXeEgGcoaub%jO]|\{[^{}]*\}/g;
21
+ // Each masked piece becomes one character from the private-use plane, which the rules treat as
22
+ // part of a word (a dash next to it sits between words) and never change.
23
+ const MASK_BASE = 0xf8000;
24
+ function mask(body, spans) {
25
+ let text = "";
26
+ const pieces = [];
27
+ const index = [];
28
+ let last = 0;
29
+ for (const [a, b] of spans) {
30
+ text += body.slice(last, a);
31
+ for (let i = last; i < a; i++)
32
+ index.push(i);
33
+ const c = String.fromCodePoint(MASK_BASE + pieces.length);
34
+ text += c;
35
+ for (let k = 0; k < c.length; k++)
36
+ index.push(a);
37
+ pieces.push(body.slice(a, b));
38
+ last = b;
39
+ }
40
+ text += body.slice(last);
41
+ for (let i = last; i <= body.length; i++)
42
+ index.push(i);
43
+ return { text, pieces, where: (i) => index[Math.min(i, index.length - 1)] };
44
+ }
45
+ function unmask(text, pieces) {
46
+ const seen = [];
47
+ for (const c of text) {
48
+ const n = c.codePointAt(0) - MASK_BASE;
49
+ if (n >= 0 && n < pieces.length)
50
+ seen.push(n);
51
+ }
52
+ if (seen.length !== pieces.length || seen.some((n, i) => n !== i))
53
+ return null; // a rule swallowed a piece
54
+ return [...text].map((c) => {
55
+ const n = c.codePointAt(0) - MASK_BASE;
56
+ return n >= 0 && n < pieces.length ? pieces[n] : c;
57
+ }).join("");
58
+ }
59
+ const noSlop = {
60
+ meta: {
61
+ type: "suggestion",
62
+ docs: {
63
+ description: "Disallow AI-generated traces (em dashes, emoji, separators, markdown) in log messages",
64
+ url: "https://github.com/slopdam/slopdam/blob/main/js/README.md#eslint",
65
+ },
66
+ fixable: "code",
67
+ schema: [
68
+ {
69
+ type: "object",
70
+ properties: {
71
+ profile: { enum: ["reader", "dev"] },
72
+ level: { enum: ["basic", "strong", "strict"] },
73
+ disable: { type: "array", items: { type: "string" } },
74
+ dashInline: { enum: ["comma", "colon", "hyphen", "space"] },
75
+ receivers: { type: "string" },
76
+ methods: { type: "array", items: { type: "string" } },
77
+ functions: { type: "array", items: { type: "string" } },
78
+ },
79
+ additionalProperties: false,
80
+ },
81
+ ],
82
+ messages: {
83
+ fixable: "{{rule}}: '{{text}}' should be '{{fix}}'",
84
+ report: "{{rule}}: '{{text}}'",
85
+ },
86
+ },
87
+ create(context) {
88
+ const options = context.options[0] ?? {};
89
+ const { receivers = "log|console", methods = DEFAULT_METHODS, functions = [], ...sanitizerOptions } = options;
90
+ const sanitizer = new Sanitizer(sanitizerOptions);
91
+ const receiverRe = new RegExp(receivers, "i");
92
+ const methodSet = new Set(methods);
93
+ const functionSet = new Set(functions);
94
+ const source = context.sourceCode ?? context.getSourceCode();
95
+ function isLogCall(call) {
96
+ const callee = call.callee;
97
+ if (callee.type === "Identifier")
98
+ return functionSet.has(callee.name);
99
+ if (callee.type !== "MemberExpression")
100
+ return false;
101
+ const name = callee.computed ? (callee.property.type === "Literal" ? String(callee.property.value) : null) : callee.property.name;
102
+ return name !== null && methodSet.has(name) && receiverRe.test(source.getText(callee.object));
103
+ }
104
+ /** The literal's body (between the quotes or backticks) and the pieces that must not change. */
105
+ function bodyOf(node) {
106
+ const raw = source.getText(node);
107
+ const start = node.range[0] + 1;
108
+ const body = raw.slice(1, -1);
109
+ if (node.type === "Literal") {
110
+ if (typeof node.value !== "string")
111
+ return null;
112
+ const spans = [];
113
+ for (const m of body.matchAll(PLACEHOLDER))
114
+ if (m[0] !== "%%")
115
+ spans.push([m.index, m.index + m[0].length]);
116
+ return { start, body, spans, quote: raw[0] };
117
+ }
118
+ // Template literal: mask every ${...}, braces and inner spaces included.
119
+ const spans = node.expressions.map((e) => [
120
+ source.getTokenBefore(e).range[1] - 2 - start,
121
+ source.getTokenAfter(e).range[0] + 1 - start,
122
+ ]);
123
+ return { start, body, spans, quote: "`" };
124
+ }
125
+ /** joinedBefore/After: the literal is concatenated with something on that side ("a — " + b). */
126
+ function check(node, joinedBefore, joinedAfter) {
127
+ const part = bodyOf(node);
128
+ if (!part)
129
+ return;
130
+ const { start, body, quote } = part;
131
+ // An empty piece at a joined end stands for the neighbor, so a dash there is between words.
132
+ const spans = [
133
+ ...(joinedBefore ? [[0, 0]] : []),
134
+ ...part.spans,
135
+ ...(joinedAfter ? [[body.length, body.length]] : []),
136
+ ];
137
+ const masked = mask(body, spans);
138
+ const found = sanitizer.findings(masked.text);
139
+ if (!found.length)
140
+ return;
141
+ // Apply each fix at its span, as the Python fixer does; overlapping findings are skipped.
142
+ let out = "";
143
+ let last = 0;
144
+ const shown = [];
145
+ for (const f of found) {
146
+ if (f.start < last)
147
+ continue;
148
+ shown.push(f);
149
+ if (f.fix === null)
150
+ continue;
151
+ let fix = f.fix;
152
+ if (fix.includes("\\") || fix.includes(quote) || (quote === "`" && fix.includes("${"))) {
153
+ fix = fix.replace(/\\/g, "\\\\").split(quote).join("\\" + quote).replace(/\$\{/g, "\\${");
154
+ }
155
+ out += masked.text.slice(last, f.start) + fix;
156
+ last = f.end;
157
+ }
158
+ out += masked.text.slice(last);
159
+ let newBody = unmask(out, masked.pieces);
160
+ if (newBody !== null) {
161
+ // Do not leave a space at either end that the original literal did not have.
162
+ if (body === body.replace(/^\s+/, ""))
163
+ newBody = newBody.replace(/^[ \t]+/, "");
164
+ if (body === body.replace(/\s+$/, ""))
165
+ newBody = newBody.replace(/[ \t]+$/, "");
166
+ }
167
+ const replacement = newBody !== null && newBody !== body ? quote + newBody + quote : null;
168
+ for (const f of shown) {
169
+ const from = start + masked.where(f.start);
170
+ const to = start + masked.where(f.end);
171
+ context.report({
172
+ node,
173
+ loc: { start: source.getLocFromIndex(from), end: source.getLocFromIndex(to) },
174
+ messageId: f.fix === null ? "report" : "fixable",
175
+ data: { rule: f.ruleId, text: f.text, fix: f.fix ?? "" },
176
+ fix: replacement === null ? null : (fixer) => fixer.replaceTextRange(node.range, replacement),
177
+ });
178
+ }
179
+ }
180
+ /** The operands of a + chain, left to right: "a" + b + "c" -> ["a", b, "c"]. */
181
+ function operands(node, out) {
182
+ if (node.type === "BinaryExpression" && node.operator === "+") {
183
+ operands(node.left, out);
184
+ operands(node.right, out);
185
+ }
186
+ else
187
+ out.push(node);
188
+ return out;
189
+ }
190
+ const isString = (n) => (n.type === "Literal" && typeof n.value === "string") || n.type === "TemplateLiteral";
191
+ return {
192
+ CallExpression(call) {
193
+ if (!isLogCall(call))
194
+ return;
195
+ for (const arg of call.arguments) {
196
+ const parts = operands(arg, []);
197
+ parts.forEach((p, i) => {
198
+ if (isString(p))
199
+ check(p, i > 0, i < parts.length - 1);
200
+ });
201
+ }
202
+ },
203
+ };
204
+ },
205
+ };
206
+ const plugin = {
207
+ meta: { name: "@slopdam/core/eslint" },
208
+ rules: { "no-slop": noSlop },
209
+ configs: {},
210
+ };
211
+ plugin.configs = {
212
+ /** slopdam/no-slop as a warning, reader profile. */
213
+ recommended: { name: "slopdam/recommended", plugins: { slopdam: plugin }, rules: { "slopdam/no-slop": "warn" } },
214
+ /** Same, with dev-style fixes ([OK] tags, " - " for dashes). */
215
+ dev: { name: "slopdam/dev", plugins: { slopdam: plugin }, rules: { "slopdam/no-slop": ["warn", { profile: "dev" }] } },
216
+ };
217
+ export default plugin;
218
+ export { noSlop };
@@ -30,8 +30,8 @@ export const SPEC = {
30
30
  },
31
31
  "hangul_choseong": "ᄀ-ᅟꥠ-ꥼ"
32
32
  },
33
- "dash_word_before": ")]}%",
34
- "dash_word_after": "([{",
33
+ "dash_word_before": ")]}%\"'”’",
34
+ "dash_word_after": "([{\"'“‘",
35
35
  "tidy": {
36
36
  "multi_space": "(?<=\\S)[ \\t]{2,}",
37
37
  "max_passes": 8
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@slopdam/core",
3
- "version": "0.1.0",
4
- "description": "Strip AI-generated traces (em dashes, emoji, separators, markdown) from log messages, with pino and winston integrations. JavaScript port of slopdam, conformance-tested against its spec.",
3
+ "version": "0.2.0",
4
+ "description": "Strip AI-generated traces (em dashes, emoji, separators, markdown) from log messages, with pino, winston and ESLint integrations. JavaScript port of slopdam, conformance-tested against its spec.",
5
5
  "license": "MIT",
6
6
  "author": "The slopdam Authors",
7
7
  "homepage": "https://github.com/slopdam/slopdam/tree/main/js#readme",
@@ -22,7 +22,9 @@
22
22
  "em-dash",
23
23
  "emoji",
24
24
  "pino",
25
- "winston"
25
+ "winston",
26
+ "eslint",
27
+ "eslintplugin"
26
28
  ],
27
29
  "type": "module",
28
30
  "main": "./dist/cjs/index.js",
@@ -59,6 +61,16 @@
59
61
  "default": "./dist/cjs/winston.js"
60
62
  }
61
63
  },
64
+ "./eslint": {
65
+ "import": {
66
+ "types": "./dist/esm/eslint.d.ts",
67
+ "default": "./dist/esm/eslint.js"
68
+ },
69
+ "require": {
70
+ "types": "./dist/cjs/eslint.d.ts",
71
+ "default": "./dist/cjs/eslint.js"
72
+ }
73
+ },
62
74
  "./package.json": "./package.json"
63
75
  },
64
76
  "files": [
@@ -74,6 +86,7 @@
74
86
  "prepublishOnly": "npm test"
75
87
  },
76
88
  "devDependencies": {
89
+ "eslint": "^10.14.0",
77
90
  "pino": "^10.4.0",
78
91
  "typescript": "~6.0.3",
79
92
  "winston": "^3.19.0"