@slopdam/core 0.0.0-stage → 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/LICENSE +21 -0
- package/README.ko.md +149 -0
- package/README.md +148 -2
- package/dist/cjs/eslint.d.ts +87 -0
- package/dist/cjs/eslint.js +221 -0
- package/dist/cjs/index.d.ts +3 -0
- package/dist/cjs/index.js +11 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pino.d.ts +26 -0
- package/dist/cjs/pino.js +49 -0
- package/dist/cjs/pyregex.d.ts +28 -0
- package/dist/cjs/pyregex.js +184 -0
- package/dist/cjs/sanitizer.d.ts +46 -0
- package/dist/cjs/sanitizer.js +265 -0
- package/dist/cjs/spec.generated.d.ts +2 -0
- package/dist/cjs/spec.generated.js +468 -0
- package/dist/cjs/types.d.ts +45 -0
- package/dist/cjs/types.js +4 -0
- package/dist/cjs/winston.d.ts +31 -0
- package/dist/cjs/winston.js +41 -0
- package/dist/esm/eslint.d.ts +87 -0
- package/dist/esm/eslint.js +218 -0
- package/dist/esm/index.d.ts +3 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/pino.d.ts +26 -0
- package/dist/esm/pino.js +46 -0
- package/dist/esm/pyregex.d.ts +28 -0
- package/dist/esm/pyregex.js +173 -0
- package/dist/esm/sanitizer.d.ts +46 -0
- package/dist/esm/sanitizer.js +260 -0
- package/dist/esm/spec.generated.d.ts +2 -0
- package/dist/esm/spec.generated.js +465 -0
- package/dist/esm/types.d.ts +45 -0
- package/dist/esm/types.js +3 -0
- package/dist/esm/winston.d.ts +31 -0
- package/dist/esm/winston.js +38 -0
- package/package.json +92 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The slopdam Authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.ko.md
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
<h1 align="center">JavaScript용 slopdam</h1>
|
|
2
|
+
|
|
3
|
+
<p align="center"><i><a href="https://github.com/slopdam/slopdam">slopdam</a>의 JavaScript, TypeScript 구현: 긴 대시, 이모지, 구분선, 마크다운이 로그에 남지 않게 합니다.</i></p>
|
|
4
|
+
|
|
5
|
+
<p align="center"><a href="https://github.com/slopdam/slopdam/blob/main/js/README.md">English</a> | <b>한국어</b></p>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://github.com/slopdam/slopdam/actions/workflows/ci.yml"><img src="https://github.com/slopdam/slopdam/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
9
|
+
<a href="https://github.com/slopdam/slopdam/blob/main/spec/README.ko.md"><img src="https://img.shields.io/badge/spec-v1%20conformance%20tested-informational.svg" alt="명세 v1: 적합성 테스트"></a>
|
|
10
|
+
<a href="https://github.com/slopdam/slopdam/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="라이선스: MIT"></a>
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
`@slopdam/core`는 AI 코딩 도구가 로그 메시지와 콘솔 출력에 남기는 흔적을 걷어냅니다. 긴 대시와 그와 닮은 선(한글 `ㅡ` 포함), 장식 이모지, 구분선, 마크다운 굵은 글씨, 둥근 따옴표, 보이지 않는 문자가 대상입니다. Python 패키지와 같은 [적합성 사례](https://github.com/slopdam/slopdam/blob/main/spec/README.ko.md)로 테스트하므로 결과가 똑같습니다.
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
입력 : ✅ **저장 완료** ㅡ 2024–2025년 데이터 3건 처리했습니다! 🎉
|
|
17
|
+
reader: 저장 완료: 2024~2025년 데이터 3건 처리했습니다.
|
|
18
|
+
dev : [OK] 저장 완료 - 2024-2025년 데이터 3건 처리했습니다!
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- `reader`(기본): 사람이 읽는 글. CLI 메시지, 알림, 보고서에 씁니다.
|
|
22
|
+
- `dev`: 검색하기 쉬운 글. 로그 파일과 수집기에 씁니다. 상태 이모지는 지우지 않고 `[OK]`, `[FAIL]`, `[WARN]`으로 바꿉니다.
|
|
23
|
+
|
|
24
|
+
## 설치
|
|
25
|
+
|
|
26
|
+
Node.js 20 이상 또는 최신 브라우저에서 동작합니다. 실행 의존성이 없고, ESM과 CommonJS 빌드에 TypeScript 타입이 들어 있습니다.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install @slopdam/core
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## 사용법
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { clean, Sanitizer } from "@slopdam/core";
|
|
36
|
+
|
|
37
|
+
clean("✅ **저장 완료** ㅡ 3건 처리했습니다! 🎉"); // "저장 완료: 3건 처리했습니다."
|
|
38
|
+
clean("✅ **Saved** — 3 rows 🎉"); // "Saved: 3 rows"
|
|
39
|
+
|
|
40
|
+
const dev = new Sanitizer({ profile: "dev" });
|
|
41
|
+
dev.clean("✅ 업로드 완료 ㅡ 3개 파일"); // "[OK] 업로드 완료 - 3개 파일"
|
|
42
|
+
dev.clean("❌ 업로드 실패", "error"); // "업로드 실패" (로그 레벨이 이미 실패를 말함)
|
|
43
|
+
|
|
44
|
+
console.log(dev.findings("log.info('🚀 시작 ㅡ 정상')"));
|
|
45
|
+
// [ { ruleId: 'emoji.pictograph', text: '🚀', fix: '', ... },
|
|
46
|
+
// { ruleId: 'dash.run', text: 'ㅡ', fix: ' - ', ... } ]
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
CommonJS에서도 `require("@slopdam/core")`로 똑같이 씁니다.
|
|
50
|
+
|
|
51
|
+
### pino
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import pino from "pino";
|
|
55
|
+
import { slopdamPino } from "@slopdam/core/pino";
|
|
56
|
+
|
|
57
|
+
const log = pino({ ...slopdamPino({ profile: "dev" }) });
|
|
58
|
+
log.info("✅ **저장 완료** %d건 ㅡ 처리했습니다!", 3); // msg: "[OK] 저장 완료 3건 - 처리했습니다!"
|
|
59
|
+
log.error(err, "❌ 업로드 실패"); // msg: "업로드 실패", err는 그대로
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
pino가 쓰기 전에 모든 호출의 메시지를 정리합니다. 객체와 오류는 그대로 두고, 구분선만 출력하던 호출은 버립니다. 프로필은 로거 전체에 적용되므로, `reader`와 `dev`를 다른 곳에 보내려면 로거를 두 개 만드세요. 이미 `hooks.logMethod`를 쓰고 있다면 `slopdamPino({ hooks })`로 넘기면 둘 다 실행됩니다.
|
|
63
|
+
|
|
64
|
+
### winston
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import winston from "winston";
|
|
68
|
+
import { slopdamWinston } from "@slopdam/core/winston";
|
|
69
|
+
|
|
70
|
+
const { combine, printf, json } = winston.format;
|
|
71
|
+
winston.createLogger({
|
|
72
|
+
transports: [
|
|
73
|
+
new winston.transports.Console({ format: combine(slopdamWinston(), printf((i) => i.message)) }),
|
|
74
|
+
new winston.transports.File({ filename: "app.log", format: combine(slopdamWinston({ profile: "dev" }), json()) }),
|
|
75
|
+
],
|
|
76
|
+
});
|
|
77
|
+
// 화면: "저장 완료: 3건 처리했습니다." app.log: {"message":"[OK] 저장 완료 - 3건 처리했습니다!", ...}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
winston은 트랜스포트마다 로그 항목의 사본을 넘기므로 트랜스포트마다 다른 프로필을 쓸 수 있습니다. `slopdamWinston()`은 `format.splat()` 뒤, `colorize()`, `printf()`, `simple()`, `json()` 앞에 둡니다. 스택 트레이스는 그대로 둡니다.
|
|
81
|
+
|
|
82
|
+
두 연동 모두 pino나 winston을 불러오지 않으므로 `@slopdam/core`는 여전히 실행 의존성이 없습니다.
|
|
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
|
+
|
|
116
|
+
### 옵션
|
|
117
|
+
|
|
118
|
+
| 옵션 | 값 | 기본값 |
|
|
119
|
+
|---|---|---|
|
|
120
|
+
| `profile` | `"reader"`, `"dev"` | `"reader"` |
|
|
121
|
+
| `level` | `"basic"`, `"strong"`(군더더기 표현도 제거), `"strict"`(ASCII가 아닌 기호를 모두 알림) | `"basic"` |
|
|
122
|
+
| `disable` | 끌 규칙 ID나 군. 예: `["emoji"]`, `["dash.run"]` | `[]` |
|
|
123
|
+
| `dashInline` | `reader`에서 문장 중간 대시를 바꿀 문자: `"colon"`, `"comma"`, `"hyphen"`, `"space"` | `"colon"` |
|
|
124
|
+
|
|
125
|
+
`clean()`의 두 번째 인자는 로그 레벨입니다. 이름(`"error"`, `"warning"`)이나 Python logging 숫자(40, 30)로 줍니다. `findings()`는 `clean()`이 바꿀 부분을 돌려주며, `start`와 `end`는 입력 안의 UTF-16 위치입니다.
|
|
126
|
+
|
|
127
|
+
URL, 인라인 코드, `key=value`의 값, 파일 경로는 바꾸지 않습니다. 두 번 정리해도 한 번 정리한 결과와 같습니다.
|
|
128
|
+
|
|
129
|
+
## Python과 같은 결과를 내는 방법
|
|
130
|
+
|
|
131
|
+
규칙을 손으로 다시 쓰지 않습니다. 빌드할 때 저장소의 [spec/](https://github.com/slopdam/slopdam/blob/main/spec/README.ko.md)을 직접 읽고, 그 안의 패턴은 패키지를 불러올 때 Python 정규식 문법에서 변환됩니다(유니코드 `\w`, `\s`, `\b`와 Python의 `^`, `$`). 문맥에 따라 바꾸는 동작 네 가지만 TypeScript로 작성했습니다. PR마다 Python 패키지와 이 패키지의 ESM, CommonJS 빌드에 같은 적합성 사례를 실행하므로 한 언어에서만 규칙이 바뀔 수 없습니다. 무작위 입력 20,000개에서 두 패키지의 결과가 같았습니다.
|
|
132
|
+
|
|
133
|
+
## 로드맵
|
|
134
|
+
|
|
135
|
+
slopdam 0.5 마일스톤의 일부입니다([로드맵](https://github.com/slopdam/slopdam/blob/main/ROADMAP.ko.md)). 핵심 패키지, pino와 winston 연동, ESLint 규칙으로 이루어집니다.
|
|
136
|
+
|
|
137
|
+
## 기여
|
|
138
|
+
|
|
139
|
+
규칙 변경은 Python 기준 구현과 `spec/`에서 적합성 사례와 함께 한 번만 합니다. 이 패키지는 다음 빌드에서 이를 반영하고, 같은 PR에서 통과 여부가 드러납니다. 기여는 slopdam의 [기여 안내](https://github.com/slopdam/slopdam/blob/main/CONTRIBUTING.ko.md)(DCO 서명), [행동 강령](https://github.com/slopdam/slopdam/blob/main/CODE_OF_CONDUCT.ko.md), [보안 정책](https://github.com/slopdam/slopdam/blob/main/SECURITY.ko.md)을 따릅니다.
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
cd js
|
|
143
|
+
npm install
|
|
144
|
+
npm test # 빌드한 뒤 적합성 사례와 API 테스트를 실행
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## 라이선스
|
|
148
|
+
|
|
149
|
+
[MIT](https://github.com/slopdam/slopdam/blob/main/LICENSE)
|
package/README.md
CHANGED
|
@@ -1,3 +1,149 @@
|
|
|
1
|
-
|
|
1
|
+
<h1 align="center">slopdam for JavaScript</h1>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center"><i>The JavaScript and TypeScript port of <a href="https://github.com/slopdam/slopdam">slopdam</a>: em dashes, emoji, separator lines and markdown stay out of your logs.</i></p>
|
|
4
|
+
|
|
5
|
+
<p align="center"><b>English</b> | <a href="https://github.com/slopdam/slopdam/blob/main/js/README.ko.md">한국어</a></p>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://github.com/slopdam/slopdam/actions/workflows/ci.yml"><img src="https://github.com/slopdam/slopdam/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
9
|
+
<a href="https://github.com/slopdam/slopdam/blob/main/spec/README.md"><img src="https://img.shields.io/badge/spec-v1%20conformance%20tested-informational.svg" alt="Spec v1: conformance tested"></a>
|
|
10
|
+
<a href="https://github.com/slopdam/slopdam/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License: MIT"></a>
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
`@slopdam/core` removes the traces AI coding tools leave in log messages and console output: em dashes and look-alike lines (including the Korean `ㅡ`), decorative emoji, separator lines, markdown bold, curly quotes and invisible characters. It gives exactly the same output as the Python package, because both are tested against the same [conformance cases](https://github.com/slopdam/slopdam/blob/main/spec/README.md).
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
input : ✅ **Saved** — 3 rows processed 🎉
|
|
17
|
+
reader: Saved: 3 rows processed
|
|
18
|
+
dev : [OK] Saved - 3 rows processed
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- `reader` (default): plain text for people, such as CLI messages, alerts and reports.
|
|
22
|
+
- `dev`: grep-friendly text for log files and collectors. Status emoji become `[OK]`, `[FAIL]` and `[WARN]` instead of disappearing.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
Node.js 20 or later, or any modern browser. No runtime dependencies; ESM and CommonJS builds with TypeScript types.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install @slopdam/core
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Use
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { clean, Sanitizer } from "@slopdam/core";
|
|
36
|
+
|
|
37
|
+
clean("✅ **Saved** — 3 rows 🎉"); // "Saved: 3 rows"
|
|
38
|
+
clean("✅ **저장 완료** ㅡ 3건 처리했습니다! 🎉"); // "저장 완료: 3건 처리했습니다."
|
|
39
|
+
|
|
40
|
+
const dev = new Sanitizer({ profile: "dev" });
|
|
41
|
+
dev.clean("✅ Upload done — 3 files"); // "[OK] Upload done - 3 files"
|
|
42
|
+
dev.clean("❌ Upload failed", "error"); // "Upload failed" (the level already says it)
|
|
43
|
+
|
|
44
|
+
console.log(dev.findings("log.info('🚀 Started — ok')"));
|
|
45
|
+
// [ { ruleId: 'emoji.pictograph', text: '🚀', fix: '', start: 10, end: 13, ... },
|
|
46
|
+
// { ruleId: 'dash.run', text: '—', fix: ' - ', ... } ]
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`require("@slopdam/core")` works the same way in CommonJS.
|
|
50
|
+
|
|
51
|
+
### pino
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import pino from "pino";
|
|
55
|
+
import { slopdamPino } from "@slopdam/core/pino";
|
|
56
|
+
|
|
57
|
+
const log = pino({ ...slopdamPino({ profile: "dev" }) });
|
|
58
|
+
log.info("✅ **Saved** %d rows — done!", 3); // msg: "[OK] Saved 3 rows - done!"
|
|
59
|
+
log.error(err, "❌ Upload failed"); // msg: "Upload failed", err untouched
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The message of every call is cleaned before pino writes it. Objects and errors are left as they are, and a call that only printed a separator line is dropped. The profile applies to the whole logger; to send `reader` text to one place and `dev` text to another, use two loggers. If you already pass `hooks.logMethod`, give it to `slopdamPino({ hooks })` so both run.
|
|
63
|
+
|
|
64
|
+
### winston
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import winston from "winston";
|
|
68
|
+
import { slopdamWinston } from "@slopdam/core/winston";
|
|
69
|
+
|
|
70
|
+
const { combine, printf, json } = winston.format;
|
|
71
|
+
winston.createLogger({
|
|
72
|
+
transports: [
|
|
73
|
+
new winston.transports.Console({ format: combine(slopdamWinston(), printf((i) => i.message)) }),
|
|
74
|
+
new winston.transports.File({ filename: "app.log", format: combine(slopdamWinston({ profile: "dev" }), json()) }),
|
|
75
|
+
],
|
|
76
|
+
});
|
|
77
|
+
// console: "Saved 3 rows: done!" app.log: {"message":"[OK] Saved 3 rows - done!", ...}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
winston gives every transport its own copy of the entry, so each one can use its own profile. Put `slopdamWinston()` after `format.splat()` and before `colorize()`, `printf()`, `simple()` or `json()`. Stack traces are kept as they are.
|
|
81
|
+
|
|
82
|
+
Neither integration imports pino or winston, so `@slopdam/core` still has no runtime dependencies.
|
|
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
|
+
|
|
116
|
+
### Options
|
|
117
|
+
|
|
118
|
+
| Option | Values | Default |
|
|
119
|
+
|---|---|---|
|
|
120
|
+
| `profile` | `"reader"`, `"dev"` | `"reader"` |
|
|
121
|
+
| `level` | `"basic"`, `"strong"` (also removes filler words), `"strict"` (also reports any non-ASCII symbol) | `"basic"` |
|
|
122
|
+
| `disable` | rule IDs or groups, such as `["emoji"]` or `["dash.run"]` | `[]` |
|
|
123
|
+
| `dashInline` | what an inline dash becomes in `reader`: `"colon"`, `"comma"`, `"hyphen"`, `"space"` | `"colon"` |
|
|
124
|
+
|
|
125
|
+
The second argument of `clean()` is the log level, as a name (`"error"`, `"warning"`) or a Python logging number (40, 30). `findings()` returns what `clean()` would change, with `start` and `end` as UTF-16 offsets into the input.
|
|
126
|
+
|
|
127
|
+
URLs, inline code, `key=value` values and file paths are never changed. Cleaning twice gives the same result as cleaning once.
|
|
128
|
+
|
|
129
|
+
## How it stays in step with Python
|
|
130
|
+
|
|
131
|
+
The rules are not rewritten by hand. The build reads the repository's [spec/](https://github.com/slopdam/slopdam/blob/main/spec/README.md) directly; its patterns are translated from Python's regular expression dialect when the package loads (Unicode `\w`, `\s` and `\b`, and Python's `^` and `$`), and only the four context-dependent actions are written in TypeScript. Every pull request runs the conformance cases against the Python package and against this package's ESM and CommonJS builds, so a rule cannot change in one language only. On 20,000 random inputs the two packages gave identical results.
|
|
132
|
+
|
|
133
|
+
## Roadmap
|
|
134
|
+
|
|
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.
|
|
136
|
+
|
|
137
|
+
## Contributing
|
|
138
|
+
|
|
139
|
+
A rule change is made once, in the Python reference and `spec/`, with conformance cases; this package picks it up on the next build, and the same pull request shows whether it passes. Contributions follow the slopdam [contribution guide](https://github.com/slopdam/slopdam/blob/main/CONTRIBUTING.md) (DCO sign-off), [code of conduct](https://github.com/slopdam/slopdam/blob/main/CODE_OF_CONDUCT.md) and [security policy](https://github.com/slopdam/slopdam/blob/main/SECURITY.md).
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
cd js
|
|
143
|
+
npm install
|
|
144
|
+
npm test # builds, then runs the conformance suite and API tests
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## License
|
|
148
|
+
|
|
149
|
+
[MIT](https://github.com/slopdam/slopdam/blob/main/LICENSE)
|
|
@@ -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;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SPEC_VERSION = exports.RULE_IDS = exports.PROFILES = exports.LEVELS = exports.clean = exports.Sanitizer = void 0;
|
|
4
|
+
// SPDX-License-Identifier: MIT
|
|
5
|
+
var sanitizer_js_1 = require("./sanitizer.js");
|
|
6
|
+
Object.defineProperty(exports, "Sanitizer", { enumerable: true, get: function () { return sanitizer_js_1.Sanitizer; } });
|
|
7
|
+
Object.defineProperty(exports, "clean", { enumerable: true, get: function () { return sanitizer_js_1.clean; } });
|
|
8
|
+
Object.defineProperty(exports, "LEVELS", { enumerable: true, get: function () { return sanitizer_js_1.LEVELS; } });
|
|
9
|
+
Object.defineProperty(exports, "PROFILES", { enumerable: true, get: function () { return sanitizer_js_1.PROFILES; } });
|
|
10
|
+
Object.defineProperty(exports, "RULE_IDS", { enumerable: true, get: function () { return sanitizer_js_1.RULE_IDS; } });
|
|
11
|
+
Object.defineProperty(exports, "SPEC_VERSION", { enumerable: true, get: function () { return sanitizer_js_1.SPEC_VERSION; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|