cleanpastedtext 0.0.0-stage → 0.1.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.md +44 -2
- package/dist/index.d.ts +106 -0
- package/dist/index.js +1080 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Issaaf Kattan
|
|
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.md
CHANGED
|
@@ -1,3 +1,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cleanpastedtext
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Find and remove the characters you can't see in copied text: zero-width spaces, byte order marks, BiDi controls, Unicode tag characters, variation selectors, odd spaces, and AI-style typography. The same engine powers [cleanpastedtext.com](https://cleanpastedtext.com) and its browser extension.
|
|
4
|
+
|
|
5
|
+
- **Deterministic.** Explicit rules, no AI model. Words are never rewritten.
|
|
6
|
+
- **Detection first.** Every run reports each character it found by name, code point, count and action (removed, replaced or kept).
|
|
7
|
+
- **Emoji-safe.** Joiners and variation selectors that belong to a real emoji sequence are kept.
|
|
8
|
+
- **Local.** No dependencies and no network code. Works in Node 18+ and browsers.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install cleanpastedtext
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
import { cleanText, PRESETS } from "cleanpastedtext";
|
|
16
|
+
|
|
17
|
+
const { cleanedText, detections } = cleanText("Hello world — “café”", PRESETS["AI Clean"]);
|
|
18
|
+
// cleanedText: 'Hello world - "café"'
|
|
19
|
+
// detections: [{ codepoint: "U+200B", name: "Zero width space", count: 1, action: "removed", ... }, ...]
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Only want to know what's there? `detectHiddenCharacters(text)` returns the hidden-character findings without the typography changes.
|
|
23
|
+
|
|
24
|
+
## Presets
|
|
25
|
+
|
|
26
|
+
| Preset | What it does |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| AI Clean (default) | Removes hidden characters and standardizes AI-style punctuation. |
|
|
29
|
+
| Safe Clean | Removes invisible and unsafe characters while keeping more formatting. |
|
|
30
|
+
| Keep Typography | Keeps smart quotes, dashes and ellipses while cleaning hidden characters. |
|
|
31
|
+
| Plain ASCII | Converts the result to keyboard characters for code and older systems. |
|
|
32
|
+
| Markdown to Text | Removes common Markdown syntax while keeping typography and list markers. |
|
|
33
|
+
| Join Lines | Joins lines broken by PDF wrapping into paragraphs and removes hidden characters. |
|
|
34
|
+
|
|
35
|
+
`PRESETS` holds the exact options for each, and `PRESET_DESCRIPTIONS` the text above. Pass your own mix of options to `cleanText`, for example `{ ...PRESETS["AI Clean"], removeJoinControls: false }` for Persian or Hindi text, which needs ZWNJ/ZWJ inside words.
|
|
36
|
+
|
|
37
|
+
## What a result can and can't tell you
|
|
38
|
+
|
|
39
|
+
An empty report means the supported checks found nothing. It doesn't prove who wrote the text, and statistical AI watermarks (patterns in word choice) are outside what any character cleaner can see. The [methodology page](https://cleanpastedtext.com/how-it-works) documents every rule.
|
|
40
|
+
|
|
41
|
+
## For AI agents
|
|
42
|
+
|
|
43
|
+
[`cleanpastedtext-mcp`](https://www.npmjs.com/package/cleanpastedtext-mcp) exposes this engine as a local MCP server.
|
|
44
|
+
|
|
45
|
+
MIT © Issaaf Kattan
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CleanPastedText cleaning engine.
|
|
3
|
+
*
|
|
4
|
+
* Detection-first: every run scans the ORIGINAL text and produces a
|
|
5
|
+
* transparent, per-codepoint report (`detections`) naming every hidden
|
|
6
|
+
* character, AI watermark artifact, and typography change — before any
|
|
7
|
+
* transformation happens. NFKC normalization only runs after detection, so
|
|
8
|
+
* characters like U+202F (narrow no-break space, the widely reported ChatGPT
|
|
9
|
+
* watermark character) are counted and named instead of being silently
|
|
10
|
+
* folded into a plain space.
|
|
11
|
+
*
|
|
12
|
+
* Nothing changes silently: the NFKC and whitespace stages diff their own
|
|
13
|
+
* output and report what they rewrote, so an empty report always means the
|
|
14
|
+
* text came out byte-for-byte identical.
|
|
15
|
+
*
|
|
16
|
+
* Emoji-safe: zero width joiners, emoji presentation selectors (U+FE0E /
|
|
17
|
+
* U+FE0F), and emoji tag sequences that are part of a REAL emoji sequence
|
|
18
|
+
* (family ZWJ sequences, hearts with U+FE0F, keycaps, subdivision flags) are
|
|
19
|
+
* preserved in every preset except "Plain ASCII". Protection is granted by
|
|
20
|
+
* parsing the sequence, never by proximity: the supplementary-plane variation
|
|
21
|
+
* selectors (U+E0100–U+E01EF) used for hidden-byte smuggling are never part of
|
|
22
|
+
* an emoji and are always removed when the variation-selector pass is on.
|
|
23
|
+
*/
|
|
24
|
+
export type DetectionCategory = "ai-artifact" | "invisible" | "bidi" | "tag" | "variation-selector" | "control" | "space" | "typography"
|
|
25
|
+
/** Changes made by the NFKC and whitespace stages rather than by a character strip. */
|
|
26
|
+
| "normalization";
|
|
27
|
+
export type DetectionAction = "removed" | "replaced" | "kept";
|
|
28
|
+
export type Detection = {
|
|
29
|
+
/** Formatted codepoint, e.g. "U+202F". */
|
|
30
|
+
codepoint: string;
|
|
31
|
+
/** Human-readable Unicode name, e.g. "Narrow no-break space". */
|
|
32
|
+
name: string;
|
|
33
|
+
count: number;
|
|
34
|
+
category: DetectionCategory;
|
|
35
|
+
action: DetectionAction;
|
|
36
|
+
/** Extra context, e.g. "Widely reported in ChatGPT output, April 2025". */
|
|
37
|
+
note?: string;
|
|
38
|
+
};
|
|
39
|
+
export type CleaningStats = {
|
|
40
|
+
invisibleCharactersRemoved: number;
|
|
41
|
+
directionalMarkersRemoved: number;
|
|
42
|
+
nbspConverted: number;
|
|
43
|
+
quotesDashesNormalized: number;
|
|
44
|
+
blankLinesCollapsed: number;
|
|
45
|
+
/** AI-artifact spaces + tag characters + variation selectors removed or replaced. */
|
|
46
|
+
aiArtifactsRemoved: number;
|
|
47
|
+
controlCharactersRemoved: number;
|
|
48
|
+
markdownArtifactsRemoved: number;
|
|
49
|
+
/** Codepoints rewritten by Unicode (NFKC) compatibility folding. */
|
|
50
|
+
unicodeNormalized: number;
|
|
51
|
+
/** Trailing whitespace characters trimmed + CRLF/CR line endings converted. */
|
|
52
|
+
whitespaceNormalized: number;
|
|
53
|
+
/** Hard-wrapped line breaks joined inside paragraphs, plus words rejoined across a line-end hyphen. */
|
|
54
|
+
linesJoined: number;
|
|
55
|
+
};
|
|
56
|
+
export type CleaningResult = {
|
|
57
|
+
cleanedText: string;
|
|
58
|
+
stats: CleaningStats;
|
|
59
|
+
detections: Detection[];
|
|
60
|
+
};
|
|
61
|
+
export type CleaningOptions = {
|
|
62
|
+
normalizeUnicode?: boolean;
|
|
63
|
+
removeInvisibleChars?: boolean;
|
|
64
|
+
removeBiDi?: boolean;
|
|
65
|
+
normalizeWhitespace?: boolean;
|
|
66
|
+
normalizeTypography?: boolean;
|
|
67
|
+
plainAscii?: boolean;
|
|
68
|
+
/** Remove U+E0000–U+E007F tag characters (invisible data smuggling / watermarking). */
|
|
69
|
+
removeTagChars?: boolean;
|
|
70
|
+
/** Remove variation selectors (U+FE00–U+FE0F, U+E0100–U+E01EF) — emoji-safe. */
|
|
71
|
+
removeVariationSelectors?: boolean;
|
|
72
|
+
/** Remove C0/C1 control characters (except tab and newline); U+2028/U+2029/NEL become \n. */
|
|
73
|
+
removeControlChars?: boolean;
|
|
74
|
+
/** Convert exotic Unicode spaces (U+2000–U+200A, U+202F, U+205F, U+3000, U+180E) to regular spaces. */
|
|
75
|
+
normalizeSpaces?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Remove the joiner controls U+200C (ZWNJ) and U+200D (ZWJ) outside emoji.
|
|
78
|
+
* Persian, Hindi, Malayalam and Sinhala words need them, so they get their
|
|
79
|
+
* own switch. Defaults to `removeInvisibleChars` when not set.
|
|
80
|
+
*/
|
|
81
|
+
removeJoinControls?: boolean;
|
|
82
|
+
/** Strip Markdown residue commonly left by AI chat output (headings, **bold**, links, ...). */
|
|
83
|
+
stripMarkdown?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Join hard-wrapped lines inside a paragraph (PDF, email, terminal copy).
|
|
86
|
+
* Blank lines stay paragraph breaks and list items keep their own line.
|
|
87
|
+
* A word split by a hyphen at the line end is rejoined when the next line
|
|
88
|
+
* starts with a lowercase letter.
|
|
89
|
+
*/
|
|
90
|
+
joinLines?: boolean;
|
|
91
|
+
};
|
|
92
|
+
export declare const DEFAULT_PRESET = "AI Clean";
|
|
93
|
+
export declare const PRESETS: Record<string, CleaningOptions>;
|
|
94
|
+
/** One-line description of each preset, as shown in the web tool. */
|
|
95
|
+
export declare const PRESET_DESCRIPTIONS: Record<string, string>;
|
|
96
|
+
export declare function formatCodepoint(cp: number): string;
|
|
97
|
+
export declare function codepointName(cp: number): string;
|
|
98
|
+
export declare function cleanText(text: string, options: CleaningOptions): CleaningResult;
|
|
99
|
+
/**
|
|
100
|
+
* Scans text for hidden characters and AI watermark artifacts without
|
|
101
|
+
* transforming it. Actions reflect what the recommended "AI Clean" preset
|
|
102
|
+
* would do; characters it keeps (emoji parts), visible typography (em dashes,
|
|
103
|
+
* smart quotes) and formatting-only changes are not reported here, so a
|
|
104
|
+
* non-empty result always means real hidden characters are present.
|
|
105
|
+
*/
|
|
106
|
+
export declare function detectHiddenCharacters(text: string): Detection[];
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,1080 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CleanPastedText cleaning engine.
|
|
3
|
+
*
|
|
4
|
+
* Detection-first: every run scans the ORIGINAL text and produces a
|
|
5
|
+
* transparent, per-codepoint report (`detections`) naming every hidden
|
|
6
|
+
* character, AI watermark artifact, and typography change — before any
|
|
7
|
+
* transformation happens. NFKC normalization only runs after detection, so
|
|
8
|
+
* characters like U+202F (narrow no-break space, the widely reported ChatGPT
|
|
9
|
+
* watermark character) are counted and named instead of being silently
|
|
10
|
+
* folded into a plain space.
|
|
11
|
+
*
|
|
12
|
+
* Nothing changes silently: the NFKC and whitespace stages diff their own
|
|
13
|
+
* output and report what they rewrote, so an empty report always means the
|
|
14
|
+
* text came out byte-for-byte identical.
|
|
15
|
+
*
|
|
16
|
+
* Emoji-safe: zero width joiners, emoji presentation selectors (U+FE0E /
|
|
17
|
+
* U+FE0F), and emoji tag sequences that are part of a REAL emoji sequence
|
|
18
|
+
* (family ZWJ sequences, hearts with U+FE0F, keycaps, subdivision flags) are
|
|
19
|
+
* preserved in every preset except "Plain ASCII". Protection is granted by
|
|
20
|
+
* parsing the sequence, never by proximity: the supplementary-plane variation
|
|
21
|
+
* selectors (U+E0100–U+E01EF) used for hidden-byte smuggling are never part of
|
|
22
|
+
* an emoji and are always removed when the variation-selector pass is on.
|
|
23
|
+
*/
|
|
24
|
+
export const DEFAULT_PRESET = "AI Clean";
|
|
25
|
+
export const PRESETS = {
|
|
26
|
+
"AI Clean": {
|
|
27
|
+
normalizeUnicode: true,
|
|
28
|
+
removeInvisibleChars: true,
|
|
29
|
+
removeJoinControls: true,
|
|
30
|
+
removeBiDi: true,
|
|
31
|
+
removeTagChars: true,
|
|
32
|
+
removeVariationSelectors: true,
|
|
33
|
+
removeControlChars: true,
|
|
34
|
+
normalizeSpaces: true,
|
|
35
|
+
normalizeWhitespace: true,
|
|
36
|
+
normalizeTypography: true,
|
|
37
|
+
stripMarkdown: false,
|
|
38
|
+
plainAscii: false,
|
|
39
|
+
},
|
|
40
|
+
"Safe Clean": {
|
|
41
|
+
normalizeUnicode: true,
|
|
42
|
+
removeInvisibleChars: true,
|
|
43
|
+
removeJoinControls: true,
|
|
44
|
+
removeBiDi: true,
|
|
45
|
+
removeTagChars: true,
|
|
46
|
+
removeVariationSelectors: false,
|
|
47
|
+
removeControlChars: true,
|
|
48
|
+
normalizeSpaces: true,
|
|
49
|
+
normalizeWhitespace: true,
|
|
50
|
+
normalizeTypography: true,
|
|
51
|
+
stripMarkdown: false,
|
|
52
|
+
plainAscii: false,
|
|
53
|
+
},
|
|
54
|
+
"Keep Typography": {
|
|
55
|
+
normalizeUnicode: true,
|
|
56
|
+
removeInvisibleChars: true,
|
|
57
|
+
removeJoinControls: true,
|
|
58
|
+
removeBiDi: true,
|
|
59
|
+
removeTagChars: true,
|
|
60
|
+
removeVariationSelectors: false,
|
|
61
|
+
removeControlChars: true,
|
|
62
|
+
normalizeSpaces: true,
|
|
63
|
+
normalizeWhitespace: true,
|
|
64
|
+
normalizeTypography: false,
|
|
65
|
+
stripMarkdown: false,
|
|
66
|
+
plainAscii: false,
|
|
67
|
+
},
|
|
68
|
+
"Plain ASCII": {
|
|
69
|
+
normalizeUnicode: true,
|
|
70
|
+
removeInvisibleChars: true,
|
|
71
|
+
removeJoinControls: true,
|
|
72
|
+
removeBiDi: true,
|
|
73
|
+
removeTagChars: true,
|
|
74
|
+
removeVariationSelectors: true,
|
|
75
|
+
removeControlChars: true,
|
|
76
|
+
normalizeSpaces: true,
|
|
77
|
+
normalizeWhitespace: true,
|
|
78
|
+
normalizeTypography: true,
|
|
79
|
+
stripMarkdown: false,
|
|
80
|
+
plainAscii: true,
|
|
81
|
+
},
|
|
82
|
+
"Markdown to Text": {
|
|
83
|
+
stripMarkdown: true,
|
|
84
|
+
normalizeWhitespace: true,
|
|
85
|
+
},
|
|
86
|
+
"Join Lines": {
|
|
87
|
+
normalizeUnicode: true,
|
|
88
|
+
removeInvisibleChars: true,
|
|
89
|
+
removeJoinControls: true,
|
|
90
|
+
removeBiDi: true,
|
|
91
|
+
removeTagChars: true,
|
|
92
|
+
removeVariationSelectors: false,
|
|
93
|
+
removeControlChars: true,
|
|
94
|
+
normalizeSpaces: true,
|
|
95
|
+
normalizeWhitespace: true,
|
|
96
|
+
normalizeTypography: false,
|
|
97
|
+
stripMarkdown: false,
|
|
98
|
+
plainAscii: false,
|
|
99
|
+
joinLines: true,
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
/** One-line description of each preset, as shown in the web tool. */
|
|
103
|
+
export const PRESET_DESCRIPTIONS = {
|
|
104
|
+
"Markdown to Text": "Removes common Markdown syntax while keeping typography and list markers.",
|
|
105
|
+
"AI Clean": "Removes hidden characters and standardizes AI-style punctuation.",
|
|
106
|
+
"Safe Clean": "Removes invisible and unsafe characters while keeping more formatting.",
|
|
107
|
+
"Keep Typography": "Keeps smart quotes, dashes, and ellipses while cleaning hidden characters.",
|
|
108
|
+
"Plain ASCII": "Converts the result to keyboard characters for code and older systems.",
|
|
109
|
+
"Join Lines": "Joins lines broken by PDF wrapping into paragraphs and removes hidden characters. Keeps typography.",
|
|
110
|
+
};
|
|
111
|
+
const CHAR_INFO = new Map();
|
|
112
|
+
function registerChars(cps, category, disposition) {
|
|
113
|
+
for (const cp of cps)
|
|
114
|
+
CHAR_INFO.set(cp, { category, disposition });
|
|
115
|
+
}
|
|
116
|
+
function codepointRange(from, to) {
|
|
117
|
+
const out = [];
|
|
118
|
+
for (let cp = from; cp <= to; cp++)
|
|
119
|
+
out.push(cp);
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
// AI-artifact spaces: special spaces & marks known to appear in AI output.
|
|
123
|
+
// U+202F was widely reported in ChatGPT output in April 2025.
|
|
124
|
+
registerChars([...codepointRange(0x2000, 0x200a), 0x202f, 0x205f, 0x3000], "ai-artifact", "space");
|
|
125
|
+
// Mongolian vowel separator: invisible format character in modern Unicode.
|
|
126
|
+
registerChars([0x180e], "ai-artifact", "remove");
|
|
127
|
+
// Invisible / zero-width characters.
|
|
128
|
+
registerChars([
|
|
129
|
+
0x200b, // zero width space
|
|
130
|
+
0x200c, // zero width non-joiner (gated by removeJoinControls)
|
|
131
|
+
0x200d, // zero width joiner (emoji-safe handling below)
|
|
132
|
+
0x2060, // word joiner
|
|
133
|
+
0xfeff, // BOM / zero width no-break space
|
|
134
|
+
0x00ad, // soft hyphen
|
|
135
|
+
0x034f, // combining grapheme joiner
|
|
136
|
+
0xfffc, // object replacement character
|
|
137
|
+
0xfff9, // interlinear annotation anchor
|
|
138
|
+
0xfffa, // interlinear annotation separator
|
|
139
|
+
0xfffb, // interlinear annotation terminator
|
|
140
|
+
0x115f, // hangul choseong filler
|
|
141
|
+
0x1160, // hangul jungseong filler
|
|
142
|
+
0x17b4, // khmer vowel inherent aq
|
|
143
|
+
0x17b5, // khmer vowel inherent aa
|
|
144
|
+
0x3164, // hangul filler
|
|
145
|
+
0xffa0, // halfwidth hangul filler
|
|
146
|
+
], "invisible", "remove");
|
|
147
|
+
// Bidirectional control characters.
|
|
148
|
+
registerChars([0x200e, 0x200f, 0x061c, ...codepointRange(0x202a, 0x202e), ...codepointRange(0x2066, 0x2069)], "bidi", "remove");
|
|
149
|
+
// Non-breaking space: replaced with a regular space.
|
|
150
|
+
registerChars([0x00a0], "space", "space");
|
|
151
|
+
// Line/paragraph separators and NEL become real newlines.
|
|
152
|
+
registerChars([0x2028, 0x2029, 0x0085], "control", "newline");
|
|
153
|
+
const TAG_INFO = { category: "tag", disposition: "remove" };
|
|
154
|
+
const VS_INFO = { category: "variation-selector", disposition: "remove" };
|
|
155
|
+
const CONTROL_INFO = { category: "control", disposition: "remove" };
|
|
156
|
+
function isTagChar(cp) {
|
|
157
|
+
return cp >= 0xe0000 && cp <= 0xe007f;
|
|
158
|
+
}
|
|
159
|
+
/** Supplementary-plane variation selectors VS17–VS256 — never part of an emoji. */
|
|
160
|
+
function isSupplementaryVariationSelector(cp) {
|
|
161
|
+
return cp >= 0xe0100 && cp <= 0xe01ef;
|
|
162
|
+
}
|
|
163
|
+
function isVariationSelector(cp) {
|
|
164
|
+
return (cp >= 0xfe00 && cp <= 0xfe0f) || isSupplementaryVariationSelector(cp);
|
|
165
|
+
}
|
|
166
|
+
function classify(cp) {
|
|
167
|
+
const single = CHAR_INFO.get(cp);
|
|
168
|
+
if (single)
|
|
169
|
+
return single;
|
|
170
|
+
if (isTagChar(cp))
|
|
171
|
+
return TAG_INFO;
|
|
172
|
+
if (isVariationSelector(cp))
|
|
173
|
+
return VS_INFO;
|
|
174
|
+
if ((cp <= 0x1f && cp !== 0x09 && cp !== 0x0a && cp !== 0x0d) ||
|
|
175
|
+
cp === 0x7f ||
|
|
176
|
+
(cp >= 0x80 && cp <= 0x9f)) {
|
|
177
|
+
return CONTROL_INFO;
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
// Typography characters — counted only when typography normalization is on.
|
|
182
|
+
const TYPOGRAPHY_CPS = new Set([
|
|
183
|
+
0x2018, 0x2019, 0x201c, 0x201d, 0x00ab, 0x00bb, 0x2013, 0x2014, 0x2026,
|
|
184
|
+
]);
|
|
185
|
+
/* ------------------------------------------------------------------ */
|
|
186
|
+
/* Names and notes */
|
|
187
|
+
/* ------------------------------------------------------------------ */
|
|
188
|
+
export function formatCodepoint(cp) {
|
|
189
|
+
return "U+" + cp.toString(16).toUpperCase().padStart(4, "0");
|
|
190
|
+
}
|
|
191
|
+
const SINGLE_NAMES = {
|
|
192
|
+
0x0000: "Null",
|
|
193
|
+
0x0007: "Bell",
|
|
194
|
+
0x0008: "Backspace",
|
|
195
|
+
0x000b: "Vertical tab",
|
|
196
|
+
0x000c: "Form feed",
|
|
197
|
+
0x001b: "Escape",
|
|
198
|
+
0x007f: "Delete (DEL)",
|
|
199
|
+
0x0085: "Next line (NEL)",
|
|
200
|
+
0x00a0: "No-break space (NBSP)",
|
|
201
|
+
0x00ab: "Left guillemet («)",
|
|
202
|
+
0x00ad: "Soft hyphen",
|
|
203
|
+
0x00bb: "Right guillemet (»)",
|
|
204
|
+
0x034f: "Combining grapheme joiner",
|
|
205
|
+
0x061c: "Arabic letter mark",
|
|
206
|
+
0x115f: "Hangul choseong filler",
|
|
207
|
+
0x1160: "Hangul jungseong filler",
|
|
208
|
+
0x17b4: "Khmer vowel inherent aq",
|
|
209
|
+
0x17b5: "Khmer vowel inherent aa",
|
|
210
|
+
0x180e: "Mongolian vowel separator",
|
|
211
|
+
0x2000: "En quad",
|
|
212
|
+
0x2001: "Em quad",
|
|
213
|
+
0x2002: "En space",
|
|
214
|
+
0x2003: "Em space",
|
|
215
|
+
0x2004: "Three-per-em space",
|
|
216
|
+
0x2005: "Four-per-em space",
|
|
217
|
+
0x2006: "Six-per-em space",
|
|
218
|
+
0x2007: "Figure space",
|
|
219
|
+
0x2008: "Punctuation space",
|
|
220
|
+
0x2009: "Thin space",
|
|
221
|
+
0x200a: "Hair space",
|
|
222
|
+
0x200b: "Zero width space",
|
|
223
|
+
0x200c: "Zero width non-joiner",
|
|
224
|
+
0x200d: "Zero width joiner",
|
|
225
|
+
0x200e: "Left-to-right mark",
|
|
226
|
+
0x200f: "Right-to-left mark",
|
|
227
|
+
0x2013: "En dash",
|
|
228
|
+
0x2014: "Em dash",
|
|
229
|
+
0x2018: "Left single quotation mark",
|
|
230
|
+
0x2019: "Right single quotation mark",
|
|
231
|
+
0x201c: "Left double quotation mark",
|
|
232
|
+
0x201d: "Right double quotation mark",
|
|
233
|
+
0x2026: "Horizontal ellipsis",
|
|
234
|
+
0x2028: "Line separator",
|
|
235
|
+
0x2029: "Paragraph separator",
|
|
236
|
+
0x202a: "Left-to-right embedding",
|
|
237
|
+
0x202b: "Right-to-left embedding",
|
|
238
|
+
0x202c: "Pop directional formatting",
|
|
239
|
+
0x202d: "Left-to-right override",
|
|
240
|
+
0x202e: "Right-to-left override",
|
|
241
|
+
0x202f: "Narrow no-break space",
|
|
242
|
+
0x205f: "Medium mathematical space",
|
|
243
|
+
0x2060: "Word joiner",
|
|
244
|
+
0x2066: "Left-to-right isolate",
|
|
245
|
+
0x2067: "Right-to-left isolate",
|
|
246
|
+
0x2068: "First strong isolate",
|
|
247
|
+
0x2069: "Pop directional isolate",
|
|
248
|
+
0x3000: "Ideographic space",
|
|
249
|
+
0x3164: "Hangul filler",
|
|
250
|
+
0xfe0e: "Variation selector-15 (text style)",
|
|
251
|
+
0xfe0f: "Variation selector-16 (emoji style)",
|
|
252
|
+
0xfeff: "Byte order mark (BOM)",
|
|
253
|
+
0xffa0: "Halfwidth Hangul filler",
|
|
254
|
+
0xfff9: "Interlinear annotation anchor",
|
|
255
|
+
0xfffa: "Interlinear annotation separator",
|
|
256
|
+
0xfffb: "Interlinear annotation terminator",
|
|
257
|
+
0xfffc: "Object replacement character",
|
|
258
|
+
0xe0001: "Language tag",
|
|
259
|
+
0xe0020: "Tag space",
|
|
260
|
+
0xe007f: "Cancel tag",
|
|
261
|
+
};
|
|
262
|
+
export function codepointName(cp) {
|
|
263
|
+
const single = SINGLE_NAMES[cp];
|
|
264
|
+
if (single)
|
|
265
|
+
return single;
|
|
266
|
+
if (cp >= 0xe0021 && cp <= 0xe007e) {
|
|
267
|
+
return `Tag character (hidden "${String.fromCodePoint(cp - 0xe0000)}")`;
|
|
268
|
+
}
|
|
269
|
+
if (isTagChar(cp))
|
|
270
|
+
return "Tag character";
|
|
271
|
+
if (cp >= 0xfe00 && cp <= 0xfe0f)
|
|
272
|
+
return `Variation selector-${cp - 0xfe00 + 1}`;
|
|
273
|
+
if (isSupplementaryVariationSelector(cp))
|
|
274
|
+
return `Variation selector-${cp - 0xe0100 + 17}`;
|
|
275
|
+
if (cp <= 0x1f)
|
|
276
|
+
return "Control character (C0)";
|
|
277
|
+
if (cp >= 0x80 && cp <= 0x9f)
|
|
278
|
+
return "Control character (C1)";
|
|
279
|
+
return `Character ${formatCodepoint(cp)}`;
|
|
280
|
+
}
|
|
281
|
+
const NOTES = {
|
|
282
|
+
0x202f: "Widely reported in ChatGPT output, April 2025",
|
|
283
|
+
0x00a0: "Common in AI output and copied web text",
|
|
284
|
+
0x2009: "Special space repeatedly flagged in AI-generated text",
|
|
285
|
+
0x200b: "Invisible; breaks search, diffs, and code",
|
|
286
|
+
0x200c: "Needed inside Persian and Indic words — removing it changes spelling",
|
|
287
|
+
0x200d: "Joins emoji and Indic conjuncts — removed only outside emoji sequences",
|
|
288
|
+
0x00ad: "Invisible until a line wraps; a common paste artifact",
|
|
289
|
+
0xfeff: "Zero width no-break space; stray BOMs corrupt files",
|
|
290
|
+
0x202e: "Reorders displayed text; used in spoofing attacks",
|
|
291
|
+
0x2014: "Frequently cited as an AI typography tell",
|
|
292
|
+
0x180e: "Renders invisibly in modern fonts",
|
|
293
|
+
};
|
|
294
|
+
function codepointNote(cp) {
|
|
295
|
+
const note = NOTES[cp];
|
|
296
|
+
if (note)
|
|
297
|
+
return note;
|
|
298
|
+
if (isTagChar(cp))
|
|
299
|
+
return "Used for invisible data smuggling and AI watermarking";
|
|
300
|
+
if (isSupplementaryVariationSelector(cp)) {
|
|
301
|
+
return "Never part of an emoji — the channel used to hide bytes inside ordinary text";
|
|
302
|
+
}
|
|
303
|
+
if (isVariationSelector(cp))
|
|
304
|
+
return "Invisible; can encode hidden data after ordinary characters";
|
|
305
|
+
return undefined;
|
|
306
|
+
}
|
|
307
|
+
const EMOJI_KEPT_NOTE = "Part of an emoji sequence — kept so your emoji don't break";
|
|
308
|
+
/* ------------------------------------------------------------------ */
|
|
309
|
+
/* Emoji safety */
|
|
310
|
+
/* ------------------------------------------------------------------ */
|
|
311
|
+
const ZWJ = 0x200d;
|
|
312
|
+
const VS15 = 0xfe0e;
|
|
313
|
+
const VS16 = 0xfe0f;
|
|
314
|
+
const COMBINING_KEYCAP = 0x20e3;
|
|
315
|
+
const CANCEL_TAG = 0xe007f;
|
|
316
|
+
const BLACK_FLAG = 0x1f3f4;
|
|
317
|
+
const EXTENDED_PICTOGRAPHIC = /\p{Extended_Pictographic}/u;
|
|
318
|
+
const PICTOGRAPHIC_CACHE = new Map();
|
|
319
|
+
function isPictographic(cp) {
|
|
320
|
+
// Nothing below U+00A9 (©, the first Extended_Pictographic codepoint) can be
|
|
321
|
+
// an emoji base, so ordinary prose never pays for the regex.
|
|
322
|
+
if (cp < 0x00a9)
|
|
323
|
+
return false;
|
|
324
|
+
const cached = PICTOGRAPHIC_CACHE.get(cp);
|
|
325
|
+
if (cached !== undefined)
|
|
326
|
+
return cached;
|
|
327
|
+
const value = EXTENDED_PICTOGRAPHIC.test(String.fromCodePoint(cp));
|
|
328
|
+
if (PICTOGRAPHIC_CACHE.size > 4096)
|
|
329
|
+
PICTOGRAPHIC_CACHE.clear();
|
|
330
|
+
PICTOGRAPHIC_CACHE.set(cp, value);
|
|
331
|
+
return value;
|
|
332
|
+
}
|
|
333
|
+
function isRegionalIndicator(cp) {
|
|
334
|
+
return cp >= 0x1f1e6 && cp <= 0x1f1ff;
|
|
335
|
+
}
|
|
336
|
+
function isSkinToneModifier(cp) {
|
|
337
|
+
return cp >= 0x1f3fb && cp <= 0x1f3ff;
|
|
338
|
+
}
|
|
339
|
+
/** 0-9, # and * — emoji bases ONLY when the sequence continues to U+20E3. */
|
|
340
|
+
function isKeycapBase(cp) {
|
|
341
|
+
return (cp >= 0x30 && cp <= 0x39) || cp === 0x23 || cp === 0x2a;
|
|
342
|
+
}
|
|
343
|
+
function isPresentationSelector(cp) {
|
|
344
|
+
return cp === VS15 || cp === VS16;
|
|
345
|
+
}
|
|
346
|
+
/** Tag characters valid inside an emoji tag sequence: "0"-"9" and "a"-"z". */
|
|
347
|
+
function isTagSpec(cp) {
|
|
348
|
+
return (cp >= 0xe0030 && cp <= 0xe0039) || (cp >= 0xe0061 && cp <= 0xe007a);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Parses the emoji sequence starting at `start`, marking every hidden member
|
|
352
|
+
* (ZWJ, U+FE0E/U+FE0F, tag characters) that must be preserved. Returns the
|
|
353
|
+
* number of codepoints consumed, or 0 when no emoji sequence starts here.
|
|
354
|
+
*
|
|
355
|
+
* Only well-formed sequences are protected:
|
|
356
|
+
* keycap := [0-9#*] U+FE0F? U+20E3
|
|
357
|
+
* flag := RI RI
|
|
358
|
+
* tag flag := U+1F3F4 tag_spec{2,6} U+E007F
|
|
359
|
+
* zwj seq := core (ZWJ core)* where core := pictographic VS? modifier? VS?
|
|
360
|
+
*
|
|
361
|
+
* Everything else — a payload of variation selectors after an emoji, tag
|
|
362
|
+
* characters after a lone black flag, a ZWJ after a digit — is left unmarked
|
|
363
|
+
* and therefore stripped by the normal passes.
|
|
364
|
+
*
|
|
365
|
+
* Base codepoints used as emoji (a heart before U+FE0F, the two halves of a
|
|
366
|
+
* ZWJ sequence) are collected in `emojiBases` so the NFKC stage can leave them
|
|
367
|
+
* alone: compatibility folding would otherwise turn the emoji U+2122 U+FE0F
|
|
368
|
+
* into "TM" and U+2139 U+FE0F into "i".
|
|
369
|
+
*/
|
|
370
|
+
function scanEmojiSequence(cps, start, marks, emojiBases) {
|
|
371
|
+
const n = cps.length;
|
|
372
|
+
const cp = cps[start];
|
|
373
|
+
// Keycap sequence — the ONLY reason a digit, "#" or "*" is an emoji base.
|
|
374
|
+
if (isKeycapBase(cp)) {
|
|
375
|
+
let j = start + 1;
|
|
376
|
+
let vsIndex = -1;
|
|
377
|
+
if (j < n && cps[j] === VS16) {
|
|
378
|
+
vsIndex = j;
|
|
379
|
+
j++;
|
|
380
|
+
}
|
|
381
|
+
if (j < n && cps[j] === COMBINING_KEYCAP) {
|
|
382
|
+
if (vsIndex >= 0)
|
|
383
|
+
marks[vsIndex] = 1;
|
|
384
|
+
return j + 1 - start;
|
|
385
|
+
}
|
|
386
|
+
return 1;
|
|
387
|
+
}
|
|
388
|
+
// Regional indicator pair (country flag) — nothing hidden inside.
|
|
389
|
+
if (isRegionalIndicator(cp)) {
|
|
390
|
+
return start + 1 < n && isRegionalIndicator(cps[start + 1]) ? 2 : 1;
|
|
391
|
+
}
|
|
392
|
+
// Emoji tag sequence (subdivision flags such as Scotland / Wales / England).
|
|
393
|
+
if (cp === BLACK_FLAG && start + 1 < n && isTagSpec(cps[start + 1])) {
|
|
394
|
+
let j = start + 1;
|
|
395
|
+
let specs = 0;
|
|
396
|
+
while (j < n && specs < 6 && isTagSpec(cps[j])) {
|
|
397
|
+
j++;
|
|
398
|
+
specs++;
|
|
399
|
+
}
|
|
400
|
+
if (specs >= 2 && j < n && cps[j] === CANCEL_TAG) {
|
|
401
|
+
for (let k = start + 1; k <= j; k++)
|
|
402
|
+
marks[k] = 1;
|
|
403
|
+
return j + 1 - start;
|
|
404
|
+
}
|
|
405
|
+
return 1; // black flag followed by a smuggled tag payload: protect nothing.
|
|
406
|
+
}
|
|
407
|
+
// ZWJ sequence of pictographic cores (family emoji, professions, flags).
|
|
408
|
+
if (!isPictographic(cp))
|
|
409
|
+
return 0;
|
|
410
|
+
let j = start;
|
|
411
|
+
for (;;) {
|
|
412
|
+
const base = cps[j];
|
|
413
|
+
j++; // pictographic base
|
|
414
|
+
if (j < n && isPresentationSelector(cps[j])) {
|
|
415
|
+
marks[j] = 1;
|
|
416
|
+
emojiBases.add(base);
|
|
417
|
+
j++;
|
|
418
|
+
}
|
|
419
|
+
if (j < n && isSkinToneModifier(cps[j]))
|
|
420
|
+
j++;
|
|
421
|
+
if (j < n && isPresentationSelector(cps[j])) {
|
|
422
|
+
marks[j] = 1;
|
|
423
|
+
emojiBases.add(base);
|
|
424
|
+
j++;
|
|
425
|
+
}
|
|
426
|
+
if (j + 1 < n && cps[j] === ZWJ && isPictographic(cps[j + 1])) {
|
|
427
|
+
marks[j] = 1;
|
|
428
|
+
emojiBases.add(base);
|
|
429
|
+
emojiBases.add(cps[j + 1]);
|
|
430
|
+
j++;
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
return j - start;
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* One linear left-to-right scan of the whole text; every index is visited a
|
|
439
|
+
* bounded number of times, so a pathological run of joiners, tag characters or
|
|
440
|
+
* variation selectors costs O(n) instead of the O(n^2) a backward look-back
|
|
441
|
+
* would cost.
|
|
442
|
+
*/
|
|
443
|
+
function markEmojiSequences(cps) {
|
|
444
|
+
const marks = new Uint8Array(cps.length);
|
|
445
|
+
const emojiBases = new Set();
|
|
446
|
+
let i = 0;
|
|
447
|
+
while (i < cps.length) {
|
|
448
|
+
const consumed = scanEmojiSequence(cps, i, marks, emojiBases);
|
|
449
|
+
i += consumed > 0 ? consumed : 1;
|
|
450
|
+
}
|
|
451
|
+
return { marks, emojiBases };
|
|
452
|
+
}
|
|
453
|
+
/* ------------------------------------------------------------------ */
|
|
454
|
+
/* Option gating */
|
|
455
|
+
/* ------------------------------------------------------------------ */
|
|
456
|
+
function isCategoryEnabled(category, cp, o) {
|
|
457
|
+
const ascii = !!o.plainAscii;
|
|
458
|
+
switch (category) {
|
|
459
|
+
case "ai-artifact":
|
|
460
|
+
return !!o.normalizeSpaces || ascii;
|
|
461
|
+
case "invisible":
|
|
462
|
+
// ZWNJ/ZWJ carry meaning in Persian and Indic scripts, so they get their
|
|
463
|
+
// own switch; it falls back to removeInvisibleChars for older callers.
|
|
464
|
+
if (cp === 0x200c || cp === ZWJ) {
|
|
465
|
+
return (o.removeJoinControls ?? !!o.removeInvisibleChars) || ascii;
|
|
466
|
+
}
|
|
467
|
+
return !!o.removeInvisibleChars || ascii;
|
|
468
|
+
case "bidi":
|
|
469
|
+
return !!o.removeBiDi || ascii;
|
|
470
|
+
case "tag":
|
|
471
|
+
return !!o.removeTagChars || ascii;
|
|
472
|
+
case "variation-selector":
|
|
473
|
+
return !!o.removeVariationSelectors || ascii;
|
|
474
|
+
case "space":
|
|
475
|
+
return !!o.normalizeWhitespace || ascii;
|
|
476
|
+
case "control":
|
|
477
|
+
// Line separator / paragraph separator / NEL are whitespace concerns too.
|
|
478
|
+
if (cp === 0x2028 || cp === 0x2029 || cp === 0x0085) {
|
|
479
|
+
return !!o.removeControlChars || !!o.normalizeWhitespace || ascii;
|
|
480
|
+
}
|
|
481
|
+
return !!o.removeControlChars || ascii;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Single pass over the original text: detects and counts every known hidden
|
|
486
|
+
* character on the untouched input, and applies per-character removals and
|
|
487
|
+
* replacements according to the options.
|
|
488
|
+
*/
|
|
489
|
+
function runCharacterPass(text, o) {
|
|
490
|
+
const emojiSafe = !o.plainAscii;
|
|
491
|
+
const countTypography = !!o.normalizeTypography || !!o.plainAscii;
|
|
492
|
+
const chars = Array.from(text);
|
|
493
|
+
const cps = new Array(chars.length);
|
|
494
|
+
for (let i = 0; i < chars.length; i++)
|
|
495
|
+
cps[i] = chars[i].codePointAt(0);
|
|
496
|
+
const emoji = emojiSafe ? markEmojiSequences(cps) : null;
|
|
497
|
+
const emojiMarks = emoji ? emoji.marks : null;
|
|
498
|
+
const outParts = [];
|
|
499
|
+
const occurrences = new Map();
|
|
500
|
+
const typographyCounts = new Map();
|
|
501
|
+
const record = (cp, category, action, emojiKept) => {
|
|
502
|
+
const key = `${cp}|${emojiKept ? 1 : 0}`;
|
|
503
|
+
const existing = occurrences.get(key);
|
|
504
|
+
if (existing) {
|
|
505
|
+
existing.count++;
|
|
506
|
+
}
|
|
507
|
+
else {
|
|
508
|
+
occurrences.set(key, { cp, category, action, emojiKept, count: 1 });
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
for (let i = 0; i < chars.length; i++) {
|
|
512
|
+
const ch = chars[i];
|
|
513
|
+
const cp = cps[i];
|
|
514
|
+
if (TYPOGRAPHY_CPS.has(cp)) {
|
|
515
|
+
if (countTypography) {
|
|
516
|
+
typographyCounts.set(cp, (typographyCounts.get(cp) ?? 0) + 1);
|
|
517
|
+
}
|
|
518
|
+
outParts.push(ch); // actual replacement happens in the typography stage
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
const info = classify(cp);
|
|
522
|
+
if (!info) {
|
|
523
|
+
outParts.push(ch);
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
const enabled = isCategoryEnabled(info.category, cp, o);
|
|
527
|
+
if (!enabled) {
|
|
528
|
+
record(cp, info.category, "kept", false);
|
|
529
|
+
outParts.push(ch);
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
// Protection comes from the sequence parser, never from proximity: only
|
|
533
|
+
// ZWJs, U+FE0E/U+FE0F and tag characters inside a well-formed emoji
|
|
534
|
+
// sequence are marked.
|
|
535
|
+
if (emojiMarks !== null && emojiMarks[i] === 1) {
|
|
536
|
+
record(cp, info.category, "kept", true);
|
|
537
|
+
outParts.push(ch);
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
if (info.disposition === "remove") {
|
|
541
|
+
record(cp, info.category, "removed", false);
|
|
542
|
+
}
|
|
543
|
+
else {
|
|
544
|
+
record(cp, info.category, "replaced", false);
|
|
545
|
+
outParts.push(info.disposition === "space" ? " " : "\n");
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
out: outParts.join(""),
|
|
550
|
+
occurrences,
|
|
551
|
+
typographyCounts,
|
|
552
|
+
emojiBases: emoji ? emoji.emojiBases : new Set(),
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
const NFKC_FOLD_CACHE = new Map();
|
|
556
|
+
/** Returns the NFKC form of a single character, or null when it is unchanged. */
|
|
557
|
+
function nfkcFold(cp, ch) {
|
|
558
|
+
if (cp < 0x80)
|
|
559
|
+
return null; // ASCII is NFKC-stable
|
|
560
|
+
const cached = NFKC_FOLD_CACHE.get(cp);
|
|
561
|
+
if (cached !== undefined)
|
|
562
|
+
return cached;
|
|
563
|
+
const folded = ch.normalize("NFKC");
|
|
564
|
+
const value = folded === ch ? null : folded;
|
|
565
|
+
if (NFKC_FOLD_CACHE.size > 4096)
|
|
566
|
+
NFKC_FOLD_CACHE.clear();
|
|
567
|
+
NFKC_FOLD_CACHE.set(cp, value);
|
|
568
|
+
return value;
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* NFKC normalization that shields characters whose dedicated option is OFF,
|
|
572
|
+
* so toggles stay truthful: with "Keep Typography", U+2026 must survive even
|
|
573
|
+
* though NFKC would fold it to "..."; same for NBSP and exotic spaces when
|
|
574
|
+
* their toggles are off.
|
|
575
|
+
*
|
|
576
|
+
* It also diffs itself: every codepoint it rewrites is reported, so the panel
|
|
577
|
+
* can never claim "nothing found" about text NFKC just changed.
|
|
578
|
+
*/
|
|
579
|
+
function nfkcStage(text, shielded, skipReporting) {
|
|
580
|
+
const changes = new Map();
|
|
581
|
+
let out = "";
|
|
582
|
+
let buffer = "";
|
|
583
|
+
for (const ch of text) {
|
|
584
|
+
const cp = ch.codePointAt(0);
|
|
585
|
+
if (shielded.has(cp)) {
|
|
586
|
+
out += buffer.normalize("NFKC") + ch;
|
|
587
|
+
buffer = "";
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
if (!skipReporting.has(cp)) {
|
|
591
|
+
const folded = nfkcFold(cp, ch);
|
|
592
|
+
if (folded !== null) {
|
|
593
|
+
const entry = changes.get(cp);
|
|
594
|
+
if (entry)
|
|
595
|
+
entry.count++;
|
|
596
|
+
else
|
|
597
|
+
changes.set(cp, { count: 1, to: folded });
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
buffer += ch;
|
|
601
|
+
}
|
|
602
|
+
out += buffer.normalize("NFKC");
|
|
603
|
+
return { out, changes, composed: changes.size === 0 && out !== text };
|
|
604
|
+
}
|
|
605
|
+
function buildNfkcShield(o) {
|
|
606
|
+
const shielded = new Set();
|
|
607
|
+
const ascii = !!o.plainAscii;
|
|
608
|
+
if (!o.normalizeTypography && !ascii) {
|
|
609
|
+
shielded.add(0x2026); // NFKC folds the ellipsis to "..."
|
|
610
|
+
}
|
|
611
|
+
if (!o.normalizeWhitespace && !ascii) {
|
|
612
|
+
shielded.add(0x00a0);
|
|
613
|
+
}
|
|
614
|
+
if (!o.normalizeSpaces && !ascii) {
|
|
615
|
+
for (const cp of [...codepointRange(0x2000, 0x200a), 0x202f, 0x205f, 0x3000]) {
|
|
616
|
+
shielded.add(cp);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return shielded;
|
|
620
|
+
}
|
|
621
|
+
function emptyWhitespaceCounts() {
|
|
622
|
+
return { carriageReturns: 0, trailing: new Map(), blankLinesCollapsed: 0 };
|
|
623
|
+
}
|
|
624
|
+
function addWhitespaceCounts(into, extra) {
|
|
625
|
+
into.carriageReturns += extra.carriageReturns;
|
|
626
|
+
into.blankLinesCollapsed += extra.blankLinesCollapsed;
|
|
627
|
+
for (const [cp, count] of extra.trailing) {
|
|
628
|
+
into.trailing.set(cp, (into.trailing.get(cp) ?? 0) + count);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
function normalizeWhitespaceStage(text) {
|
|
632
|
+
const counts = emptyWhitespaceCounts();
|
|
633
|
+
for (let i = 0; i < text.length; i++) {
|
|
634
|
+
if (text.charCodeAt(i) === 0x0d)
|
|
635
|
+
counts.carriageReturns++;
|
|
636
|
+
}
|
|
637
|
+
let out = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
638
|
+
out = out
|
|
639
|
+
.split("\n")
|
|
640
|
+
.map((line) => {
|
|
641
|
+
const trimmed = line.trimEnd();
|
|
642
|
+
for (const ch of line.slice(trimmed.length)) {
|
|
643
|
+
const cp = ch.codePointAt(0);
|
|
644
|
+
counts.trailing.set(cp, (counts.trailing.get(cp) ?? 0) + 1);
|
|
645
|
+
}
|
|
646
|
+
return trimmed;
|
|
647
|
+
})
|
|
648
|
+
.join("\n");
|
|
649
|
+
let blankStreak = 0;
|
|
650
|
+
const collapsed = [];
|
|
651
|
+
for (const line of out.split("\n")) {
|
|
652
|
+
if (line.trim() === "") {
|
|
653
|
+
blankStreak++;
|
|
654
|
+
if (blankStreak <= 2) {
|
|
655
|
+
collapsed.push(line);
|
|
656
|
+
}
|
|
657
|
+
else {
|
|
658
|
+
counts.blankLinesCollapsed++;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
else {
|
|
662
|
+
blankStreak = 0;
|
|
663
|
+
collapsed.push(line);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return { out: collapsed.join("\n"), counts };
|
|
667
|
+
}
|
|
668
|
+
/** A line that starts a list item keeps its own line when wrapped lines are joined. */
|
|
669
|
+
const LIST_ITEM_START = /^\s*(?:[-*+\u2022\u2023\u2043\u25AA\u25E6]|\d{1,3}[.)]|[a-zA-Z][.)])\s/;
|
|
670
|
+
function joinLinesStage(text) {
|
|
671
|
+
let joined = 0;
|
|
672
|
+
let hyphensRejoined = 0;
|
|
673
|
+
const out = [];
|
|
674
|
+
for (const line of text.split("\n")) {
|
|
675
|
+
const last = out.length - 1;
|
|
676
|
+
const prev = last >= 0 ? out[last] : "";
|
|
677
|
+
if (last >= 0 && prev.trim() !== "" && line.trim() !== "" && !LIST_ITEM_START.test(line)) {
|
|
678
|
+
const head = prev.replace(/[ \t]+$/, "");
|
|
679
|
+
const tail = line.trimStart();
|
|
680
|
+
if (/\p{L}-$/u.test(head) && /^\p{Ll}/u.test(tail)) {
|
|
681
|
+
out[last] = head.slice(0, -1) + tail;
|
|
682
|
+
hyphensRejoined++;
|
|
683
|
+
}
|
|
684
|
+
else {
|
|
685
|
+
out[last] = `${head} ${tail}`;
|
|
686
|
+
joined++;
|
|
687
|
+
}
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
out.push(line);
|
|
691
|
+
}
|
|
692
|
+
return { out: out.join("\n"), joined, hyphensRejoined };
|
|
693
|
+
}
|
|
694
|
+
function whitespaceTotal(counts) {
|
|
695
|
+
let total = counts.carriageReturns;
|
|
696
|
+
for (const count of counts.trailing.values())
|
|
697
|
+
total += count;
|
|
698
|
+
return total;
|
|
699
|
+
}
|
|
700
|
+
function whitespaceDetections(counts) {
|
|
701
|
+
const rows = [];
|
|
702
|
+
if (counts.carriageReturns > 0) {
|
|
703
|
+
rows.push({
|
|
704
|
+
codepoint: "U+000D",
|
|
705
|
+
name: "Carriage return",
|
|
706
|
+
count: counts.carriageReturns,
|
|
707
|
+
category: "normalization",
|
|
708
|
+
action: "replaced",
|
|
709
|
+
note: "Windows line ending (CRLF) converted to a plain newline",
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
for (const [cp, count] of counts.trailing) {
|
|
713
|
+
const base = cp === 0x20 ? "Trailing space" : cp === 0x09 ? "Trailing tab" : `Trailing ${codepointName(cp)}`;
|
|
714
|
+
rows.push({
|
|
715
|
+
codepoint: formatCodepoint(cp),
|
|
716
|
+
name: base,
|
|
717
|
+
count,
|
|
718
|
+
category: "normalization",
|
|
719
|
+
action: "removed",
|
|
720
|
+
note: "Whitespace left at the end of a line",
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
if (counts.blankLinesCollapsed > 0) {
|
|
724
|
+
rows.push({
|
|
725
|
+
codepoint: "U+000A",
|
|
726
|
+
name: "Extra blank line",
|
|
727
|
+
count: counts.blankLinesCollapsed,
|
|
728
|
+
category: "normalization",
|
|
729
|
+
action: "removed",
|
|
730
|
+
note: "Runs of three or more blank lines collapsed to two",
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
return rows;
|
|
734
|
+
}
|
|
735
|
+
function normalizeTypographyStage(text) {
|
|
736
|
+
return text
|
|
737
|
+
.replace(/[\u201C\u201D\u00AB\u00BB]/g, '"')
|
|
738
|
+
.replace(/[\u2018\u2019]/g, "'")
|
|
739
|
+
.replace(/[\u2013\u2014]/g, "-")
|
|
740
|
+
.replace(/\u2026/g, "...");
|
|
741
|
+
}
|
|
742
|
+
/* ------------------------------------------------------------------ */
|
|
743
|
+
/* Markdown stripping */
|
|
744
|
+
/* ------------------------------------------------------------------ */
|
|
745
|
+
/** A link target has to look like one; "a[i](b)" in code must survive. */
|
|
746
|
+
const MD_URL = /^<?\s*(?:[a-z][a-z0-9+.-]*:|[/#?]|\.{1,2}\/|[\w-]+(?:\.[\w-]+)+(?:[/?#]|$))/i;
|
|
747
|
+
function looksLikeUrl(target) {
|
|
748
|
+
const trimmed = target.trim();
|
|
749
|
+
return trimmed.length > 0 && MD_URL.test(trimmed);
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Replaces the body of every fenced code block with a placeholder so the rest
|
|
753
|
+
* of the Markdown pass cannot rewrite code. The fence lines themselves stay in
|
|
754
|
+
* place and are removed (and counted) by the normal fence rule.
|
|
755
|
+
*/
|
|
756
|
+
function maskFencedCode(text, blocks, placeholder) {
|
|
757
|
+
const fences = [];
|
|
758
|
+
const fenceLine = /^[ \t]{0,3}(?:```|~~~)[^\n]*$/gm;
|
|
759
|
+
let match;
|
|
760
|
+
while ((match = fenceLine.exec(text)) !== null) {
|
|
761
|
+
fences.push({ start: match.index, end: match.index + match[0].length });
|
|
762
|
+
}
|
|
763
|
+
if (fences.length === 0)
|
|
764
|
+
return text;
|
|
765
|
+
const ranges = [];
|
|
766
|
+
for (let i = 0; i + 1 < fences.length; i += 2) {
|
|
767
|
+
// Skip the newline after the opening fence and leave the newline before the
|
|
768
|
+
// closing fence in place, so the closing fence stays at the start of a line.
|
|
769
|
+
ranges.push({ start: Math.min(fences[i].end + 1, text.length), end: fences[i + 1].start - 1 });
|
|
770
|
+
}
|
|
771
|
+
if (fences.length % 2 === 1) {
|
|
772
|
+
const last = fences[fences.length - 1];
|
|
773
|
+
ranges.push({ start: Math.min(last.end + 1, text.length), end: text.length });
|
|
774
|
+
}
|
|
775
|
+
let out = text;
|
|
776
|
+
for (let i = ranges.length - 1; i >= 0; i--) {
|
|
777
|
+
const { start, end } = ranges[i];
|
|
778
|
+
if (end <= start)
|
|
779
|
+
continue;
|
|
780
|
+
const index = blocks.length;
|
|
781
|
+
blocks.push(text.slice(start, end));
|
|
782
|
+
out = out.slice(0, start) + placeholder(index) + out.slice(end);
|
|
783
|
+
}
|
|
784
|
+
return out;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Deterministically strips Markdown residue commonly left by AI chat output.
|
|
788
|
+
* List markers ("- ", "1. ") are intentionally kept, fenced and inline code is
|
|
789
|
+
* spliced back verbatim, and identifiers like `__init__`, `my_snake_var`, array
|
|
790
|
+
* indexing `a[i](b)` and paths like `/tmp/_private_/x` are left alone.
|
|
791
|
+
*/
|
|
792
|
+
function stripMarkdownStage(text) {
|
|
793
|
+
let removed = 0;
|
|
794
|
+
const blocks = [];
|
|
795
|
+
let sentinel = "\u0000";
|
|
796
|
+
while (text.includes(sentinel + "MD"))
|
|
797
|
+
sentinel += "\u0000";
|
|
798
|
+
const placeholder = (index) => `${sentinel}MD${index}${sentinel}`;
|
|
799
|
+
const placeholderPattern = new RegExp(`${sentinel}MD(\\d+)${sentinel}`, "g");
|
|
800
|
+
// Code first: fenced blocks, then inline spans. Their content is immune to
|
|
801
|
+
// every rule below.
|
|
802
|
+
let out = maskFencedCode(text, blocks, placeholder);
|
|
803
|
+
out = out.replace(/`([^`\n]+?)`/g, (_m, inner) => {
|
|
804
|
+
removed++;
|
|
805
|
+
blocks.push(inner);
|
|
806
|
+
return placeholder(blocks.length - 1);
|
|
807
|
+
});
|
|
808
|
+
// ``` fence lines (the fenced content was masked above).
|
|
809
|
+
out = out.replace(/^[ \t]{0,3}(?:```|~~~)[^\n]*\n?/gm, () => {
|
|
810
|
+
removed++;
|
|
811
|
+
return "";
|
|
812
|
+
});
|
|
813
|
+
// "> " blockquote markers (before headings so "> # x" fully unwraps).
|
|
814
|
+
out = out.replace(/^(?:>[ \t]?)+/gm, () => {
|
|
815
|
+
removed++;
|
|
816
|
+
return "";
|
|
817
|
+
});
|
|
818
|
+
// Heading markers.
|
|
819
|
+
out = out.replace(/^#{1,6}[ \t]+/gm, () => {
|
|
820
|
+
removed++;
|
|
821
|
+
return "";
|
|
822
|
+
});
|
|
823
|
+
// Images  -> alt, then links [text](url) -> text — only when the
|
|
824
|
+
// target actually looks like a URL.
|
|
825
|
+
out = out.replace(/!\[([^\]\n]*)\]\(([^)\n]*)\)/g, (m, alt, target) => {
|
|
826
|
+
if (!looksLikeUrl(target))
|
|
827
|
+
return m;
|
|
828
|
+
removed++;
|
|
829
|
+
return alt;
|
|
830
|
+
});
|
|
831
|
+
out = out.replace(/\[([^\]\n]*)\]\(([^)\n]*)\)/g, (m, label, target) => {
|
|
832
|
+
if (!looksLikeUrl(target))
|
|
833
|
+
return m;
|
|
834
|
+
removed++;
|
|
835
|
+
return label;
|
|
836
|
+
});
|
|
837
|
+
// Bold, then italic (word-wrapping markers only; list bullets are untouched).
|
|
838
|
+
// Real emphasis never has whitespace against the delimiter, which keeps
|
|
839
|
+
// expressions such as "a = **p + **q" intact.
|
|
840
|
+
out = out.replace(/\*\*([^*\s](?:[^*\n]*[^*\s])?)\*\*/g, (_m, inner) => {
|
|
841
|
+
removed++;
|
|
842
|
+
return inner;
|
|
843
|
+
});
|
|
844
|
+
// __bold__ requires a non-identifier character inside, so Python dunders
|
|
845
|
+
// (__init__, __name__) and __CONSTANTS__ survive.
|
|
846
|
+
out = out.replace(/(^|[^\w\\])__([^_\s](?:[^_\n]*[^_\s])?)__(?![\w_])/gm, (m, pre, inner) => {
|
|
847
|
+
if (!/[^\w]/.test(inner))
|
|
848
|
+
return m;
|
|
849
|
+
removed++;
|
|
850
|
+
return pre + inner;
|
|
851
|
+
});
|
|
852
|
+
out = out.replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s).,;:!?]|$)/gm, (_m, pre, inner) => {
|
|
853
|
+
removed++;
|
|
854
|
+
return pre + inner;
|
|
855
|
+
});
|
|
856
|
+
// _italic_ only at word boundaries: my_snake_var and /tmp/_private_/x stay.
|
|
857
|
+
out = out.replace(/(^|[\s(])_([^_\s](?:[^_\n]*[^_\s])?)_(?=[\s).,;:!?]|$)/gm, (_m, pre, inner) => {
|
|
858
|
+
removed++;
|
|
859
|
+
return pre + inner;
|
|
860
|
+
});
|
|
861
|
+
// Splice code back in verbatim.
|
|
862
|
+
out = out.replace(placeholderPattern, (_m, index) => blocks[Number(index)] ?? "");
|
|
863
|
+
return { out, removed };
|
|
864
|
+
}
|
|
865
|
+
function plainAsciiStage(text) {
|
|
866
|
+
// Decompose so accented letters fold to their ASCII base (e-acute -> e) instead
|
|
867
|
+
// of being deleted outright, then drop everything outside printable ASCII.
|
|
868
|
+
// U+2044 is normalization's own output (NFKC turns 1/2 into 1 + U+2044 + 2), so it becomes
|
|
869
|
+
// a slash rather than vanishing and gluing "1" to "2".
|
|
870
|
+
return text
|
|
871
|
+
.replace(/[\u2044\u2215]/g, "/")
|
|
872
|
+
.normalize("NFD")
|
|
873
|
+
.replace(/\p{M}/gu, "")
|
|
874
|
+
.replace(/[^\t\n\x20-\x7E]/g, "");
|
|
875
|
+
}
|
|
876
|
+
/* ------------------------------------------------------------------ */
|
|
877
|
+
/* Public API */
|
|
878
|
+
/* ------------------------------------------------------------------ */
|
|
879
|
+
export function cleanText(text, options) {
|
|
880
|
+
const o = options ?? {};
|
|
881
|
+
const normalizationRows = [];
|
|
882
|
+
// A soft hyphen at a line end marks a word the PDF split across two lines.
|
|
883
|
+
// Stage 1 would delete it and leave "hyph" + newline + "enation", so when
|
|
884
|
+
// lines are being joined, rejoin those words first.
|
|
885
|
+
let softHyphensRejoined = 0;
|
|
886
|
+
if (o.joinLines) {
|
|
887
|
+
text = text.replace(/\u00AD[ \t]*\r?\n[ \t]*(?=\p{Ll})/gu, () => {
|
|
888
|
+
softHyphensRejoined++;
|
|
889
|
+
return "";
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
// Stage 1 — detect on the ORIGINAL text and apply per-character strips.
|
|
893
|
+
const pass = runCharacterPass(text, o);
|
|
894
|
+
let cleaned = pass.out;
|
|
895
|
+
// Stage 2 — Unicode normalization (NFKC), shielding characters whose
|
|
896
|
+
// dedicated toggle is off so it never silently undercuts a choice. Every
|
|
897
|
+
// fold it performs is reported.
|
|
898
|
+
let unicodeNormalized = 0;
|
|
899
|
+
if (o.normalizeUnicode) {
|
|
900
|
+
const shield = buildNfkcShield(o);
|
|
901
|
+
// Characters actually used as emoji keep their emoji identity: NFKC would
|
|
902
|
+
// otherwise fold "™️" (U+2122 U+FE0F) to "TM" and "ℹ️" to "i".
|
|
903
|
+
for (const cp of pass.emojiBases)
|
|
904
|
+
shield.add(cp);
|
|
905
|
+
const nfkc = nfkcStage(cleaned, shield, TYPOGRAPHY_CPS);
|
|
906
|
+
cleaned = nfkc.out;
|
|
907
|
+
for (const [cp, change] of nfkc.changes) {
|
|
908
|
+
unicodeNormalized += change.count;
|
|
909
|
+
normalizationRows.push({
|
|
910
|
+
codepoint: formatCodepoint(cp),
|
|
911
|
+
name: SINGLE_NAMES[cp] ?? `Compatibility character "${String.fromCodePoint(cp)}"`,
|
|
912
|
+
count: change.count,
|
|
913
|
+
category: "normalization",
|
|
914
|
+
action: "replaced",
|
|
915
|
+
note: `Unicode NFKC rewrites this as "${change.to}"`,
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
if (nfkc.composed) {
|
|
919
|
+
unicodeNormalized += 1;
|
|
920
|
+
normalizationRows.push({
|
|
921
|
+
codepoint: "NFKC",
|
|
922
|
+
name: "Unicode normalization (NFKC)",
|
|
923
|
+
count: 1,
|
|
924
|
+
category: "normalization",
|
|
925
|
+
action: "replaced",
|
|
926
|
+
note: "Combining marks were composed into their precomposed equivalents",
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
// Stage 3 — whitespace normalization.
|
|
931
|
+
const whitespaceCounts = emptyWhitespaceCounts();
|
|
932
|
+
if (o.normalizeWhitespace) {
|
|
933
|
+
const ws = normalizeWhitespaceStage(cleaned);
|
|
934
|
+
cleaned = ws.out;
|
|
935
|
+
addWhitespaceCounts(whitespaceCounts, ws.counts);
|
|
936
|
+
}
|
|
937
|
+
// Stage 4 — typography normalization (also forced under Plain ASCII so
|
|
938
|
+
// smart quotes transliterate instead of being deleted).
|
|
939
|
+
if (o.normalizeTypography || o.plainAscii) {
|
|
940
|
+
cleaned = normalizeTypographyStage(cleaned);
|
|
941
|
+
}
|
|
942
|
+
// Stage 5 — optional Markdown residue strip.
|
|
943
|
+
let markdownArtifactsRemoved = 0;
|
|
944
|
+
if (o.stripMarkdown) {
|
|
945
|
+
const md = stripMarkdownStage(cleaned);
|
|
946
|
+
cleaned = md.out;
|
|
947
|
+
markdownArtifactsRemoved = md.removed;
|
|
948
|
+
}
|
|
949
|
+
// Stage 5b — optional joining of hard-wrapped lines (runs after Markdown
|
|
950
|
+
// stripping so list markers are judged on the text the user will get).
|
|
951
|
+
let linesJoined = 0;
|
|
952
|
+
if (o.joinLines) {
|
|
953
|
+
const jl = joinLinesStage(cleaned);
|
|
954
|
+
cleaned = jl.out;
|
|
955
|
+
linesJoined = jl.joined + jl.hyphensRejoined + softHyphensRejoined;
|
|
956
|
+
if (softHyphensRejoined > 0) {
|
|
957
|
+
normalizationRows.push({
|
|
958
|
+
codepoint: "U+00AD",
|
|
959
|
+
name: "Soft hyphen at line end",
|
|
960
|
+
count: softHyphensRejoined,
|
|
961
|
+
category: "normalization",
|
|
962
|
+
action: "removed",
|
|
963
|
+
note: "Word split across two lines rejoined",
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
if (jl.joined > 0) {
|
|
967
|
+
normalizationRows.push({
|
|
968
|
+
codepoint: "U+000A",
|
|
969
|
+
name: "Wrapped line break",
|
|
970
|
+
count: jl.joined,
|
|
971
|
+
category: "normalization",
|
|
972
|
+
action: "replaced",
|
|
973
|
+
note: "Line break inside a paragraph joined with a space",
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
if (jl.hyphensRejoined > 0) {
|
|
977
|
+
normalizationRows.push({
|
|
978
|
+
codepoint: "U+002D",
|
|
979
|
+
name: "Hyphen at line end",
|
|
980
|
+
count: jl.hyphensRejoined,
|
|
981
|
+
category: "normalization",
|
|
982
|
+
action: "removed",
|
|
983
|
+
note: "Word split across two lines rejoined. Check real hyphenated words such as well-known",
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
// Stage 6 — optional aggressive ASCII projection. Deleting non-ASCII
|
|
988
|
+
// characters leaves new trailing spaces and blank lines behind, so the
|
|
989
|
+
// whitespace pass runs again over its output (keeping the tool idempotent).
|
|
990
|
+
if (o.plainAscii) {
|
|
991
|
+
cleaned = plainAsciiStage(cleaned);
|
|
992
|
+
if (o.normalizeWhitespace) {
|
|
993
|
+
const ws = normalizeWhitespaceStage(cleaned);
|
|
994
|
+
cleaned = ws.out;
|
|
995
|
+
addWhitespaceCounts(whitespaceCounts, ws.counts);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
normalizationRows.push(...whitespaceDetections(whitespaceCounts));
|
|
999
|
+
// Build the detection report.
|
|
1000
|
+
const detections = [];
|
|
1001
|
+
for (const occ of pass.occurrences.values()) {
|
|
1002
|
+
detections.push({
|
|
1003
|
+
codepoint: formatCodepoint(occ.cp),
|
|
1004
|
+
name: codepointName(occ.cp),
|
|
1005
|
+
count: occ.count,
|
|
1006
|
+
category: occ.category,
|
|
1007
|
+
action: occ.action,
|
|
1008
|
+
note: occ.emojiKept ? EMOJI_KEPT_NOTE : codepointNote(occ.cp),
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
for (const [cp, count] of pass.typographyCounts) {
|
|
1012
|
+
detections.push({
|
|
1013
|
+
codepoint: formatCodepoint(cp),
|
|
1014
|
+
name: codepointName(cp),
|
|
1015
|
+
count,
|
|
1016
|
+
category: "typography",
|
|
1017
|
+
action: "replaced",
|
|
1018
|
+
note: codepointNote(cp),
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
detections.push(...normalizationRows);
|
|
1022
|
+
// Most frequent first; on a tie, character findings outrank formatting ones.
|
|
1023
|
+
const rank = (d) => (d.category === "normalization" ? 1 : 0);
|
|
1024
|
+
detections.sort((a, b) => b.count - a.count || rank(a) - rank(b) || a.codepoint.localeCompare(b.codepoint));
|
|
1025
|
+
// Aggregate stats (legacy fields + new totals).
|
|
1026
|
+
const stats = {
|
|
1027
|
+
invisibleCharactersRemoved: 0,
|
|
1028
|
+
directionalMarkersRemoved: 0,
|
|
1029
|
+
nbspConverted: 0,
|
|
1030
|
+
quotesDashesNormalized: 0,
|
|
1031
|
+
blankLinesCollapsed: whitespaceCounts.blankLinesCollapsed,
|
|
1032
|
+
aiArtifactsRemoved: 0,
|
|
1033
|
+
controlCharactersRemoved: 0,
|
|
1034
|
+
markdownArtifactsRemoved,
|
|
1035
|
+
unicodeNormalized,
|
|
1036
|
+
whitespaceNormalized: whitespaceTotal(whitespaceCounts),
|
|
1037
|
+
linesJoined,
|
|
1038
|
+
};
|
|
1039
|
+
for (const d of detections) {
|
|
1040
|
+
if (d.action === "kept")
|
|
1041
|
+
continue;
|
|
1042
|
+
switch (d.category) {
|
|
1043
|
+
case "invisible":
|
|
1044
|
+
stats.invisibleCharactersRemoved += d.count;
|
|
1045
|
+
break;
|
|
1046
|
+
case "bidi":
|
|
1047
|
+
stats.directionalMarkersRemoved += d.count;
|
|
1048
|
+
break;
|
|
1049
|
+
case "space":
|
|
1050
|
+
stats.nbspConverted += d.count;
|
|
1051
|
+
break;
|
|
1052
|
+
case "typography":
|
|
1053
|
+
stats.quotesDashesNormalized += d.count;
|
|
1054
|
+
break;
|
|
1055
|
+
case "ai-artifact":
|
|
1056
|
+
case "tag":
|
|
1057
|
+
case "variation-selector":
|
|
1058
|
+
stats.aiArtifactsRemoved += d.count;
|
|
1059
|
+
break;
|
|
1060
|
+
case "control":
|
|
1061
|
+
stats.controlCharactersRemoved += d.count;
|
|
1062
|
+
break;
|
|
1063
|
+
case "normalization":
|
|
1064
|
+
// Counted from the stages themselves (unicodeNormalized /
|
|
1065
|
+
// whitespaceNormalized / blankLinesCollapsed).
|
|
1066
|
+
break;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
return { cleanedText: cleaned, stats, detections };
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Scans text for hidden characters and AI watermark artifacts without
|
|
1073
|
+
* transforming it. Actions reflect what the recommended "AI Clean" preset
|
|
1074
|
+
* would do; characters it keeps (emoji parts), visible typography (em dashes,
|
|
1075
|
+
* smart quotes) and formatting-only changes are not reported here, so a
|
|
1076
|
+
* non-empty result always means real hidden characters are present.
|
|
1077
|
+
*/
|
|
1078
|
+
export function detectHiddenCharacters(text) {
|
|
1079
|
+
return cleanText(text, PRESETS[DEFAULT_PRESET]).detections.filter((d) => d.action !== "kept" && d.category !== "typography" && d.category !== "normalization");
|
|
1080
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cleanpastedtext",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Detect and remove hidden Unicode (zero-width spaces, BiDi controls, tag characters), odd spaces and AI-style typography from text. Deterministic, dependency-free, runs locally.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc -p tsconfig.build.json",
|
|
22
|
+
"prepublishOnly": "npm run build"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"unicode",
|
|
26
|
+
"invisible-characters",
|
|
27
|
+
"zero-width-space",
|
|
28
|
+
"text-cleaner",
|
|
29
|
+
"nbsp",
|
|
30
|
+
"bidi",
|
|
31
|
+
"trojan-source",
|
|
32
|
+
"ai-text",
|
|
33
|
+
"markdown"
|
|
34
|
+
],
|
|
35
|
+
"homepage": "https://cleanpastedtext.com/how-it-works",
|
|
36
|
+
"author": "Issaaf Kattan",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18"
|
|
40
|
+
}
|
|
41
|
+
}
|