text-sanctifier 1.0.20 → 1.1.1

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.
@@ -1,175 +1,342 @@
1
- // ./src/inspectText.js
2
-
3
- import {
4
- CONTROL_CHARS_REGEX,
5
- INVISIBLE_TRASH_REGEX,
6
- EMOJI_REGEX,
7
- ASCII_KEYBOARD_SAFE_REGEX,
8
- normalizeTypographicJank,
9
- } from './sanctifyText.js';
10
-
11
-
12
- /**
13
- * @typedef {Object} UnicodeTrashReport
14
- * @property {boolean} hasControlChars
15
- * @property {boolean} hasInvisibleChars
16
- * @property {boolean} hasMixedNewlines
17
- * @property {'LF'|'CRLF'|'CR'|'Mixed'|null} newlineStyle
18
- * @property {boolean} hasEmojis
19
- * @property {boolean} hasNonKeyboardChars
20
- * @property {string[]} summary
21
- */
22
-
23
-
24
- /**
25
- * Safe `.test()` for global/sticky regexes.
26
- * Global regexes mutate `lastIndex`, which makes `.test()` unreliable across calls.
27
- * @param {RegExp} re
28
- * @param {string} s
29
- */
30
- function stableTest(re, s) {
31
- re.lastIndex = 0;
32
- return re.test(s);
33
- }
34
-
35
- /**
36
- * Returns true if text contains any non-keyboard characters (excluding emojis),
37
- * after typographic normalization.
38
- *
39
- * "Keyboard" here means:
40
- * - Printable ASCII (0x20–0x7E)
41
- * - CR/LF
42
- * - Emojis (per EMOJI_REGEX)
43
- *
44
- * @param {string} text
45
- * @returns {boolean}
46
- */
47
- function hasNonKeyboardCharsExcludingEmoji(text) {
48
- const normalized = normalizeTypographicJank(text);
49
-
50
- // Fast path: no non-ascii runs => no non-keyboard chars
51
- if (!stableTest(ASCII_KEYBOARD_SAFE_REGEX, normalized)) return false;
52
-
53
- // Walk code points so we can distinguish emoji from other non-ascii safely
54
- for (const ch of normalized) {
55
- // allowed: ASCII printable + newlines
56
- if (ch === '\n' || ch === '\r' || (ch >= ' ' && ch <= '~')) continue;
57
-
58
- // allowed: emoji
59
- if (stableTest(EMOJI_REGEX, ch)) continue;
60
-
61
- // anything else non-ascii is "non-keyboard"
62
- return true;
63
- }
64
-
65
- return false;
66
- }
67
-
68
- /**
69
- * Detects textual "trash" or anomalies in a given string.
70
- * @param {string} text @returns {UnicodeTrashReport}
71
- */
72
- export function inspectText(text) {
73
- if (typeof text !== 'string') {
74
- throw new TypeError('inspectText expects a string input.');
75
- }
76
-
77
- const summary = [];
78
- const report = {
79
- hasControlChars: false,
80
- hasInvisibleChars: false,
81
- hasMixedNewlines: false,
82
- newlineStyle: null,
83
- hasEmojis: false,
84
- hasNonKeyboardChars: false,
85
- summary,
86
- };
87
-
88
- const flag = (condition, key, message) => {
89
- if (condition) {
90
- report[key] = true;
91
- summary.push(message);
92
- }
93
- };
94
-
95
- // === Pattern Checks ===
96
- flag(stableTest(CONTROL_CHARS_REGEX, text), 'hasControlChars', 'Control characters detected.');
97
- flag(stableTest(INVISIBLE_TRASH_REGEX, text), 'hasInvisibleChars', 'Invisible Unicode characters detected.');
98
- flag(stableTest(EMOJI_REGEX, text), 'hasEmojis', 'Emojis detected.');
99
-
100
- // === Newline Analysis ===
101
- const { mixed, types } = getNewlineStats(text);
102
- report.hasMixedNewlines = mixed;
103
- report.newlineStyle = mixed ? 'Mixed' : types[0] || null;
104
-
105
- if (report.newlineStyle) {
106
- summary.push(
107
- mixed ? 'Mixed newline styles detected.' : `Consistent newline style: ${report.newlineStyle}`
108
- );
109
- }
110
-
111
- // === Non-keyboard characters (excluding emojis) ===
112
- flag(
113
- hasNonKeyboardCharsExcludingEmoji(text),
114
- 'hasNonKeyboardChars',
115
- 'Non-keyboard characters detected.'
116
- );
117
-
118
- return report;
119
- }
120
-
121
- /**
122
- * Counts the number of different newline types in a string.
123
- * @param {string} text
124
- * @returns {{
125
- * crlf: number,
126
- * cr: number,
127
- * lf: number,
128
- * types: string[],
129
- * mixed: boolean
130
- * }}
131
- */
132
- export function getNewlineStats(text) {
133
- if (typeof text !== 'string') {
134
- throw new TypeError('getNewlineStats expects a string input.');
135
- }
136
-
137
- const crlfMatches = text.match(/\r\n/g) || [];
138
- const textWithoutCRLF = text.replace(/\r\n/g, '');
139
-
140
- const crMatches = textWithoutCRLF.match(/\r/g) || [];
141
- const lfMatches = textWithoutCRLF.match(/\n/g) || [];
142
-
143
- const count = {
144
- crlf: crlfMatches.length,
145
- cr: crMatches.length,
146
- lf: lfMatches.length,
147
- };
148
-
149
- const types = [];
150
- if (count.crlf > 0) types.push('CRLF');
151
- if (count.cr > 0) types.push('CR');
152
- if (count.lf > 0) types.push('LF');
153
-
154
- return {
155
- ...count,
156
- types,
157
- mixed: types.length > 1,
158
- };
159
- }
160
-
161
- /**
162
- * Creates defaultOptions for summonSanctifier based on inspectText result
163
- * @param {!UnicodeTrashReport} report
164
- * @return {!SanctifyOptions}
165
- */
166
- export function getRecommendedSanctifierOptions(report) {
167
- return {
168
- purgeInvisibleChars: report.hasInvisibleChars,
169
- purgeEmojis: report.hasEmojis,
170
- nukeControls: report.hasControlChars,
171
- keyboardOnlyFilter: report.hasNonKeyboardChars,
172
- normalizeNewlines:
173
- report.hasMixedNewlines || report.newlineStyle === 'CRLF' || report.newlineStyle === 'CR',
174
- };
1
+ // ./src/inspectText.js
2
+
3
+ import {
4
+ CONTROL_CHARS_REGEX,
5
+ INVISIBLE_TRASH_REGEX,
6
+ EMOJI_REGEX,
7
+ ASCII_KEYBOARD_SAFE_REGEX,
8
+ normalizeTypographicJank,
9
+ } from './sanctifyText.js';
10
+
11
+ /** @typedef {import('./sanctifyText.js').SanctifyOptions} SanctifyOptions */
12
+
13
+
14
+ /**
15
+ * @typedef {Object} UnicodeTrashReport
16
+ * @property {boolean} hasControlChars
17
+ * @property {boolean} hasInvisibleChars
18
+ * @property {boolean} hasMixedNewlines
19
+ * @property {'LF'|'CRLF'|'CR'|'Mixed'|null} newlineStyle
20
+ * @property {boolean} hasEmojis
21
+ * @property {boolean} hasNonKeyboardChars
22
+ * @property {string[]} summary
23
+ */
24
+
25
+
26
+ /**
27
+ * Safe `.test()` for global/sticky regexes.
28
+ * Global regexes mutate `lastIndex`, which makes `.test()` unreliable across calls.
29
+ * @param {RegExp} re
30
+ * @param {string} s
31
+ */
32
+ function stableTest(re, s) {
33
+ re.lastIndex = 0;
34
+ return re.test(s);
35
+ }
36
+
37
+ /**
38
+ * Returns true if text contains any non-keyboard characters (excluding emojis),
39
+ * after typographic normalization.
40
+ *
41
+ * "Keyboard" here means:
42
+ * - Printable ASCII (0x20–0x7E)
43
+ * - CR/LF
44
+ * - Emojis (per EMOJI_REGEX)
45
+ *
46
+ * @param {string} text
47
+ * @returns {boolean}
48
+ */
49
+ function hasNonKeyboardCharsExcludingEmoji(text) {
50
+ const normalized = normalizeTypographicJank(text);
51
+
52
+ // Fast path: no non-ascii runs => no non-keyboard chars
53
+ if (!stableTest(ASCII_KEYBOARD_SAFE_REGEX, normalized)) return false;
54
+
55
+ // Walk code points so we can distinguish emoji from other non-ascii safely
56
+ for (const ch of normalized) {
57
+ // allowed: ASCII printable + newlines
58
+ if (ch === '\n' || ch === '\r' || (ch >= ' ' && ch <= '~')) continue;
59
+
60
+ // allowed: emoji
61
+ if (stableTest(EMOJI_REGEX, ch)) continue;
62
+
63
+ // anything else non-ascii is "non-keyboard"
64
+ return true;
65
+ }
66
+
67
+ return false;
68
+ }
69
+
70
+ /**
71
+ * Detects textual "trash" or anomalies in a given string.
72
+ * @param {string} text @returns {UnicodeTrashReport}
73
+ */
74
+ export function inspectText(text) {
75
+ if (typeof text !== 'string') {
76
+ throw new TypeError('inspectText expects a string input.');
77
+ }
78
+
79
+ const summary = [];
80
+ const report = {
81
+ hasControlChars: false,
82
+ hasInvisibleChars: false,
83
+ hasMixedNewlines: false,
84
+ newlineStyle: null,
85
+ hasEmojis: false,
86
+ hasNonKeyboardChars: false,
87
+ summary,
88
+ };
89
+
90
+ const flag = (condition, key, message) => {
91
+ if (condition) {
92
+ report[key] = true;
93
+ summary.push(message);
94
+ }
95
+ };
96
+
97
+ // === Pattern Checks ===
98
+ flag(stableTest(CONTROL_CHARS_REGEX, text), 'hasControlChars', 'Control characters detected.');
99
+ flag(stableTest(INVISIBLE_TRASH_REGEX, text), 'hasInvisibleChars', 'Invisible Unicode characters detected.');
100
+ flag(stableTest(EMOJI_REGEX, text), 'hasEmojis', 'Emojis detected.');
101
+
102
+ // === Newline Analysis ===
103
+ const { mixed, types } = getNewlineStats(text);
104
+ report.hasMixedNewlines = mixed;
105
+ report.newlineStyle = mixed ? 'Mixed' : types[0] || null;
106
+
107
+ if (report.newlineStyle) {
108
+ summary.push(
109
+ mixed ? 'Mixed newline styles detected.' : `Consistent newline style: ${report.newlineStyle}`
110
+ );
111
+ }
112
+
113
+ // === Non-keyboard characters (excluding emojis) ===
114
+ flag(
115
+ hasNonKeyboardCharsExcludingEmoji(text),
116
+ 'hasNonKeyboardChars',
117
+ 'Non-keyboard characters detected.'
118
+ );
119
+
120
+ return report;
121
+ }
122
+
123
+ /**
124
+ * @typedef {'bidi_control'|'zero_width'|'nonbreaking_space'|'bom'|'nul'|'c0_control'|'c1_control'} TrashCategory
125
+ */
126
+
127
+ /**
128
+ * One located character.
129
+ * - `offset`: 0-based UTF-16 index into the input (a JS string index).
130
+ * - `line`: 1-based; lines end at LF, CR, or CRLF (counted once).
131
+ * - `column`: 1-based, in UTF-16 code units from the start of the line.
132
+ * - `atStart`: present on `bom` findings only; true at offset 0, where a BOM is legitimate.
133
+ *
134
+ * @typedef {Object} TrashFinding
135
+ * @property {number} offset
136
+ * @property {number} line
137
+ * @property {number} column
138
+ * @property {number} codePoint
139
+ * @property {TrashCategory} category
140
+ * @property {boolean} [atStart]
141
+ */
142
+
143
+ /**
144
+ * @typedef {Object} TrashCounts
145
+ * @property {number} bidi_control
146
+ * @property {number} zero_width
147
+ * @property {number} nonbreaking_space
148
+ * @property {number} bom
149
+ * @property {number} nul
150
+ * @property {number} c0_control
151
+ * @property {number} c1_control
152
+ */
153
+
154
+ /**
155
+ * @typedef {Object} DetailedTrashReport
156
+ * @property {TrashFinding[]} findings - In offset order, at most `maxFindings` long.
157
+ * @property {TrashCounts} counts - Every occurrence per category, listed or not.
158
+ * @property {number} total - Sum of `counts`.
159
+ * @property {boolean} truncated - True when `total` exceeds `findings.length`.
160
+ */
161
+
162
+ /**
163
+ * @typedef {Object} InspectDetailedOptions
164
+ * @property {number} [maxFindings=100] - Cap on listed findings (non-negative integer or Infinity).
165
+ */
166
+
167
+ const DEFAULT_MAX_FINDINGS = 100;
168
+
169
+ /**
170
+ * Category of one UTF-16 code unit, or null when it is not trash.
171
+ * Tab, LF and CR are whitespace, not trash. DEL (U+007F) is counted with the C0 controls.
172
+ * @param {number} c
173
+ * @returns {TrashCategory|null}
174
+ */
175
+ function classifyCodeUnit(c) {
176
+ if (c < 0x80) {
177
+ if (c === 0) return 'nul';
178
+ if (c < 0x20) return c === 0x09 || c === 0x0A || c === 0x0D ? null : 'c0_control';
179
+ return c === 0x7F ? 'c0_control' : null;
180
+ }
181
+ if (c <= 0x9F) return 'c1_control';
182
+ if (c === 0xA0) return 'nonbreaking_space';
183
+ if (c === 0x061C) return 'bidi_control';
184
+ if (c < 0x2000) return null;
185
+ if (c <= 0x200A) return 'nonbreaking_space';
186
+ if (c <= 0x200D) return 'zero_width';
187
+ if (c <= 0x200F) return 'bidi_control';
188
+ if (c >= 0x202A && c <= 0x202E) return 'bidi_control';
189
+ if (c === 0x202F) return 'nonbreaking_space';
190
+ if (c === 0x2060) return 'zero_width';
191
+ if (c >= 0x2066 && c <= 0x2069) return 'bidi_control';
192
+ if (c === 0x3000) return 'nonbreaking_space';
193
+ if (c === 0xFEFF) return 'bom';
194
+ return null;
195
+ }
196
+
197
+ /**
198
+ * Locates invisible and control characters, one finding per character.
199
+ *
200
+ * Categories:
201
+ * - `bidi_control`: U+061C, U+200E, U+200F, U+202A–U+202E, U+2066–U+2069
202
+ * - `zero_width`: U+200B–U+200D, U+2060
203
+ * - `nonbreaking_space`: non-breaking and typographic spaces U+00A0, U+2000–U+200A, U+202F, U+3000
204
+ * - `bom`: U+FEFF (`atStart` says whether it sits at offset 0)
205
+ * - `nul`: U+0000
206
+ * - `c0_control`: U+0001–U+001F except tab, LF and CR; and U+007F
207
+ * - `c1_control`: U+0080–U+009F
208
+ *
209
+ * Every occurrence is counted; only the first `maxFindings` are listed.
210
+ * One pass over the string, no regex, no copy.
211
+ *
212
+ * @param {string} text
213
+ * @param {InspectDetailedOptions} [options]
214
+ * @returns {DetailedTrashReport}
215
+ */
216
+ export function inspectTextDetailed(text, options = {}) {
217
+ if (typeof text !== 'string') {
218
+ throw new TypeError('inspectTextDetailed expects a string input.');
219
+ }
220
+
221
+ const requested = options && options.maxFindings;
222
+ const maxFindings =
223
+ requested === Infinity || (Number.isInteger(requested) && requested >= 0)
224
+ ? requested
225
+ : DEFAULT_MAX_FINDINGS;
226
+
227
+ /** @type {TrashCounts} */
228
+ const counts = {
229
+ bidi_control: 0,
230
+ zero_width: 0,
231
+ nonbreaking_space: 0,
232
+ bom: 0,
233
+ nul: 0,
234
+ c0_control: 0,
235
+ c1_control: 0,
236
+ };
237
+ /** @type {TrashFinding[]} */
238
+ const findings = [];
239
+ let total = 0;
240
+ let line = 1;
241
+ let lineStart = 0;
242
+
243
+ for (let i = 0, n = text.length; i < n; i++) {
244
+ const c = text.charCodeAt(i);
245
+
246
+ // Printable ASCII: the common case
247
+ if (c >= 0x20 && c < 0x7F) continue;
248
+
249
+ if (c === 0x0A) {
250
+ line++;
251
+ lineStart = i + 1;
252
+ continue;
253
+ }
254
+ if (c === 0x0D) {
255
+ // CRLF ends the line at its LF
256
+ if (text.charCodeAt(i + 1) !== 0x0A) {
257
+ line++;
258
+ lineStart = i + 1;
259
+ }
260
+ continue;
261
+ }
262
+
263
+ const category = classifyCodeUnit(c);
264
+ if (category === null) continue;
265
+
266
+ counts[category]++;
267
+ total++;
268
+ if (findings.length < maxFindings) {
269
+ /** @type {TrashFinding} */
270
+ const finding = { offset: i, line, column: i - lineStart + 1, codePoint: c, category };
271
+ if (category === 'bom') finding.atStart = i === 0;
272
+ findings.push(finding);
273
+ }
274
+ }
275
+
276
+ return { findings, counts, total, truncated: total > findings.length };
277
+ }
278
+
279
+ /**
280
+ * Counts the number of different newline types in a string.
281
+ * @param {string} text
282
+ * @returns {{
283
+ * crlf: number,
284
+ * cr: number,
285
+ * lf: number,
286
+ * types: string[],
287
+ * mixed: boolean
288
+ * }}
289
+ */
290
+ export function getNewlineStats(text) {
291
+ if (typeof text !== 'string') {
292
+ throw new TypeError('getNewlineStats expects a string input.');
293
+ }
294
+
295
+ // One counting pass: a CR followed by LF is one CRLF; any other CR or LF stands alone.
296
+ let crlf = 0;
297
+ let cr = 0;
298
+ let lf = 0;
299
+
300
+ for (let i = 0, n = text.length; i < n; i++) {
301
+ const c = text.charCodeAt(i);
302
+ if (c === 0x0D) {
303
+ if (text.charCodeAt(i + 1) === 0x0A) {
304
+ crlf++;
305
+ i++;
306
+ } else {
307
+ cr++;
308
+ }
309
+ } else if (c === 0x0A) {
310
+ lf++;
311
+ }
312
+ }
313
+
314
+ const count = { crlf, cr, lf };
315
+
316
+ const types = [];
317
+ if (count.crlf > 0) types.push('CRLF');
318
+ if (count.cr > 0) types.push('CR');
319
+ if (count.lf > 0) types.push('LF');
320
+
321
+ return {
322
+ ...count,
323
+ types,
324
+ mixed: types.length > 1,
325
+ };
326
+ }
327
+
328
+ /**
329
+ * Creates defaultOptions for summonSanctifier based on inspectText result
330
+ * @param {!UnicodeTrashReport} report
331
+ * @return {!SanctifyOptions}
332
+ */
333
+ export function getRecommendedSanctifierOptions(report) {
334
+ return {
335
+ purgeInvisibleChars: report.hasInvisibleChars,
336
+ purgeEmojis: report.hasEmojis,
337
+ nukeControls: report.hasControlChars,
338
+ keyboardOnlyFilter: report.hasNonKeyboardChars,
339
+ normalizeNewlines:
340
+ report.hasMixedNewlines || report.newlineStyle === 'CRLF' || report.newlineStyle === 'CR',
341
+ };
175
342
  }