@stll/text-search 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,540 @@
1
+ import { AhoCorasick } from "@stll/aho-corasick";
2
+ import { FuzzySearch } from "@stll/fuzzy-search";
3
+ import { RegexSet } from "@stll/regex-set";
4
+
5
+ import type { ClassifiedPattern } from "./classify";
6
+ import { classifyPatterns } from "./classify";
7
+ import { mergeAndSelect } from "./merge";
8
+ import type {
9
+ Match,
10
+ PatternEntry,
11
+ TextSearchOptions,
12
+ } from "./types";
13
+
14
+ /**
15
+ * An engine instance with pattern index mapping.
16
+ */
17
+ type RegexSlot = {
18
+ type: "regex";
19
+ rs: RegexSet;
20
+ indexMap: number[];
21
+ nameMap: (string | undefined)[];
22
+ };
23
+
24
+ type AcSlot = {
25
+ type: "ac";
26
+ ac: AhoCorasick;
27
+ indexMap: number[];
28
+ nameMap: (string | undefined)[];
29
+ };
30
+
31
+ type FuzzySlot = {
32
+ type: "fuzzy";
33
+ fs: FuzzySearch;
34
+ indexMap: number[];
35
+ nameMap: (string | undefined)[];
36
+ };
37
+
38
+ type EngineSlot = RegexSlot | AcSlot | FuzzySlot;
39
+
40
+ /**
41
+ * Multi-engine text search orchestrator.
42
+ *
43
+ * Routes patterns to the optimal engine
44
+ * configuration:
45
+ * - Large alternation patterns get their own
46
+ * RegexSet instance (prevents DFA state explosion)
47
+ * - Normal patterns share a single RegexSet
48
+ * (single-pass multi-pattern DFA)
49
+ *
50
+ * Merges results from all engines into a unified
51
+ * non-overlapping Match[] sorted by position.
52
+ */
53
+ export class TextSearch {
54
+ private engines: EngineSlot[] = [];
55
+ private patternCount: number;
56
+ private overlapAll: boolean;
57
+ /**
58
+ * True when there's exactly one engine and all
59
+ * patterns map to identity indices (0→0, 1→1, ...).
60
+ * Enables zero-overhead findIter: return raw engine
61
+ * output without remapping or object allocation.
62
+ */
63
+ private zeroOverhead: boolean = false;
64
+
65
+ constructor(
66
+ patterns: PatternEntry[],
67
+ options?: TextSearchOptions,
68
+ ) {
69
+ this.patternCount = patterns.length;
70
+ this.overlapAll =
71
+ options?.overlapStrategy === "all";
72
+ const maxAlt = options?.maxAlternations ?? 50;
73
+ const classified = classifyPatterns(
74
+ patterns,
75
+ options?.allLiteral ?? false,
76
+ );
77
+
78
+ // Four buckets:
79
+ // 1. Fuzzy patterns → FuzzySearch (Levenshtein)
80
+ // 2. Pure literals → Aho-Corasick (SIMD)
81
+ // 3. Normal regex → shared RegexSet (DFA)
82
+ // 4. Large alternations → isolated RegexSet
83
+ const fuzzy: ClassifiedPattern[] = [];
84
+ const literals: ClassifiedPattern[] = [];
85
+ const shared: ClassifiedPattern[] = [];
86
+ const isolated: ClassifiedPattern[] = [];
87
+
88
+ for (const cp of classified) {
89
+ if (cp.fuzzyDistance !== undefined) {
90
+ fuzzy.push(cp);
91
+ } else if (cp.isLiteral) {
92
+ literals.push(cp);
93
+ } else if (cp.alternationCount > maxAlt) {
94
+ isolated.push(cp);
95
+ } else {
96
+ shared.push(cp);
97
+ }
98
+ }
99
+
100
+ const rsOptions = {
101
+ unicodeBoundaries:
102
+ options?.unicodeBoundaries ?? true,
103
+ wholeWords: options?.wholeWords ?? false,
104
+ caseInsensitive:
105
+ options?.caseInsensitive ?? false,
106
+ };
107
+
108
+ // Build fuzzy engine
109
+ if (fuzzy.length > 0) {
110
+ const fuzzyOpts: Parameters<
111
+ typeof buildFuzzyEngine
112
+ >[1] = {
113
+ unicodeBoundaries:
114
+ rsOptions.unicodeBoundaries,
115
+ wholeWords: rsOptions.wholeWords,
116
+ };
117
+ if (options?.fuzzyMetric !== undefined)
118
+ fuzzyOpts.metric = options.fuzzyMetric;
119
+ if (options?.normalizeDiacritics !== undefined)
120
+ fuzzyOpts.normalizeDiacritics =
121
+ options.normalizeDiacritics;
122
+ if (options?.caseInsensitive !== undefined)
123
+ fuzzyOpts.caseInsensitive =
124
+ options.caseInsensitive;
125
+ this.engines.push(
126
+ buildFuzzyEngine(fuzzy, fuzzyOpts),
127
+ );
128
+ }
129
+
130
+ // Build AC engine(s) for pure literals.
131
+ // Group by per-pattern AC options so patterns
132
+ // with different caseInsensitive/wholeWords
133
+ // settings get separate AC instances.
134
+ if (literals.length > 0) {
135
+ const groups = new Map<
136
+ string,
137
+ ClassifiedPattern[]
138
+ >();
139
+ for (const cp of literals) {
140
+ const ci =
141
+ cp.acOptions?.caseInsensitive ??
142
+ rsOptions.caseInsensitive;
143
+ const ww =
144
+ cp.acOptions?.wholeWords ??
145
+ rsOptions.wholeWords;
146
+ const key = `${ci ? 1 : 0}:${ww ? 1 : 0}`;
147
+ const group = groups.get(key);
148
+ if (group) {
149
+ group.push(cp);
150
+ } else {
151
+ groups.set(key, [cp]);
152
+ }
153
+ }
154
+ for (const [key, group] of groups) {
155
+ const [ci, ww] = key.split(":");
156
+ this.engines.push(
157
+ buildAcEngine(group, {
158
+ ...rsOptions,
159
+ caseInsensitive: ci === "1",
160
+ wholeWords: ww === "1",
161
+ }),
162
+ );
163
+ }
164
+ }
165
+
166
+ // Adaptive regex grouping: try combining shared
167
+ // patterns, measure actual search time on a
168
+ // probe string. If combined is slower than
169
+ // individual, fall back to isolation.
170
+ if (shared.length > 1) {
171
+ const combined = buildRegexEngine(
172
+ shared,
173
+ rsOptions,
174
+ );
175
+ // Probe: 1KB of mixed content
176
+ const probe = (
177
+ "Hello World 123 test@example.com " +
178
+ "2025-01-01 +420 123 456 789 " +
179
+ "Ing. Jan Novák, s.r.o. Praha 1 "
180
+ ).repeat(10);
181
+ const t0 = performance.now();
182
+ combined.rs.findIter(probe);
183
+ const combinedMs = performance.now() - t0;
184
+
185
+ // Individual baseline (sum of isolated scans)
186
+ let individualMs = 0;
187
+ const individualEngines: RegexSlot[] = [];
188
+ for (const cp of shared) {
189
+ const eng = buildRegexEngine(
190
+ [cp],
191
+ rsOptions,
192
+ );
193
+ const t1 = performance.now();
194
+ eng.rs.findIter(probe);
195
+ individualMs += performance.now() - t1;
196
+ individualEngines.push(eng);
197
+ }
198
+
199
+ if (combinedMs > individualMs * 1.5) {
200
+ // Combined is >1.5x slower — isolate
201
+ for (const eng of individualEngines) {
202
+ this.engines.push(eng);
203
+ }
204
+ } else {
205
+ this.engines.push(combined);
206
+ }
207
+ } else if (shared.length === 1) {
208
+ this.engines.push(
209
+ buildRegexEngine(shared, rsOptions),
210
+ );
211
+ }
212
+
213
+ for (const cp of isolated) {
214
+ this.engines.push(
215
+ buildRegexEngine([cp], rsOptions),
216
+ );
217
+ }
218
+
219
+ // Zero-overhead fast path: when all patterns
220
+ // land in a single engine, the indexMap is
221
+ // identity (0→0, 1→1, ...) and no names need
222
+ // attaching. findIter can return raw engine
223
+ // output without any JS-side remapping.
224
+ if (this.engines.length === 1) {
225
+ const engine = this.engines[0]!;
226
+ const hasNames = engine.nameMap.some(
227
+ (n) => n !== undefined,
228
+ );
229
+ if (!hasNames) {
230
+ this.zeroOverhead = true;
231
+ }
232
+ }
233
+ }
234
+
235
+ /** Number of patterns. */
236
+ get length(): number {
237
+ return this.patternCount;
238
+ }
239
+
240
+ /** Returns true if any pattern matches. */
241
+ isMatch(haystack: string): boolean {
242
+ for (const engine of this.engines) {
243
+ if (engineIsMatch(engine, haystack)) {
244
+ return true;
245
+ }
246
+ }
247
+ return false;
248
+ }
249
+
250
+ /**
251
+ * Find matches in text.
252
+ *
253
+ * With `overlapStrategy: "longest"` (default):
254
+ * returns non-overlapping matches, longest wins.
255
+ *
256
+ * With `overlapStrategy: "all"`: returns all
257
+ * matches including overlaps, sorted by position.
258
+ */
259
+ findIter(haystack: string): Match[] {
260
+ // Fast path: single engine, identity indexMap,
261
+ // no names → return raw engine output directly.
262
+ // Zero JS overhead: no remapping, no allocation.
263
+ if (this.zeroOverhead) {
264
+ return engineFindIter(
265
+ this.engines[0]!,
266
+ haystack,
267
+ );
268
+ }
269
+
270
+ // Single engine but needs name remapping
271
+ if (this.engines.length === 1) {
272
+ return remapMatches(
273
+ engineFindIter(this.engines[0]!, haystack),
274
+ this.engines[0]!,
275
+ );
276
+ }
277
+
278
+ // Multi-engine: collect from all, remap in-place
279
+ const all: Match[] = [];
280
+ for (const engine of this.engines) {
281
+ const matches = engineFindIter(
282
+ engine,
283
+ haystack,
284
+ );
285
+ // In-place remapping avoids .map() allocation
286
+ for (const m of remapMatches(matches, engine)) {
287
+ all.push(m);
288
+ }
289
+ }
290
+
291
+ if (this.overlapAll) {
292
+ return all.sort(
293
+ (a, b) => a.start - b.start,
294
+ );
295
+ }
296
+
297
+ return mergeAndSelect(all);
298
+ }
299
+
300
+ /** Which pattern indices matched (not where). */
301
+ whichMatch(haystack: string): number[] {
302
+ const seen = new Set<number>();
303
+
304
+ for (const engine of this.engines) {
305
+ // AC doesn't have whichMatch — use findIter
306
+ const matches = engineFindIter(
307
+ engine,
308
+ haystack,
309
+ );
310
+ for (const m of matches) {
311
+ seen.add(engine.indexMap[m.pattern]!);
312
+ }
313
+ }
314
+
315
+ return [...seen];
316
+ }
317
+
318
+ /**
319
+ * Replace all non-overlapping matches.
320
+ * replacements[i] replaces pattern i.
321
+ */
322
+ replaceAll(
323
+ haystack: string,
324
+ replacements: string[],
325
+ ): string {
326
+ if (replacements.length !== this.patternCount) {
327
+ throw new Error(
328
+ `Expected ${this.patternCount} ` +
329
+ `replacements, got ${replacements.length}`,
330
+ );
331
+ }
332
+
333
+ // Always use non-overlapping matches for
334
+ // replacement, even if overlapStrategy is "all".
335
+ const all: Match[] = [];
336
+ for (const engine of this.engines) {
337
+ const matches = engineFindIter(
338
+ engine,
339
+ haystack,
340
+ );
341
+ for (const m of remapMatches(matches, engine)) {
342
+ all.push(m);
343
+ }
344
+ }
345
+ const matches = mergeAndSelect(all);
346
+
347
+ let result = "";
348
+ let last = 0;
349
+
350
+ for (const m of matches) {
351
+ result += haystack.slice(last, m.start);
352
+ result += replacements[m.pattern]!;
353
+ last = m.end;
354
+ }
355
+
356
+ result += haystack.slice(last);
357
+ return result;
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Build a RegexSet engine from classified patterns.
363
+ */
364
+ function buildRegexEngine(
365
+ patterns: ClassifiedPattern[],
366
+ options: {
367
+ unicodeBoundaries: boolean;
368
+ wholeWords: boolean;
369
+ caseInsensitive: boolean;
370
+ },
371
+ ): RegexSlot {
372
+ const rsPatterns: (string | RegExp | {
373
+ pattern: string | RegExp;
374
+ name?: string;
375
+ })[] = [];
376
+ const indexMap: number[] = [];
377
+ const nameMap: (string | undefined)[] = [];
378
+
379
+ for (const cp of patterns) {
380
+ if (cp.name !== undefined) {
381
+ rsPatterns.push({
382
+ pattern: cp.pattern,
383
+ name: cp.name,
384
+ });
385
+ } else {
386
+ rsPatterns.push(cp.pattern);
387
+ }
388
+ indexMap.push(cp.originalIndex);
389
+ nameMap.push(cp.name);
390
+ }
391
+
392
+ const rs = new RegexSet(rsPatterns, options);
393
+
394
+ return { type: "regex", rs, indexMap, nameMap };
395
+ }
396
+
397
+ /**
398
+ * Build an Aho-Corasick engine from literal patterns.
399
+ */
400
+ function buildAcEngine(
401
+ patterns: ClassifiedPattern[],
402
+ options: {
403
+ unicodeBoundaries: boolean;
404
+ wholeWords: boolean;
405
+ caseInsensitive: boolean;
406
+ },
407
+ ): AcSlot {
408
+ const literals: string[] = [];
409
+ const indexMap: number[] = [];
410
+ const nameMap: (string | undefined)[] = [];
411
+
412
+ for (const cp of patterns) {
413
+ literals.push(cp.pattern as string);
414
+ indexMap.push(cp.originalIndex);
415
+ nameMap.push(cp.name);
416
+ }
417
+
418
+ const ac = new AhoCorasick(literals, {
419
+ wholeWords: options.wholeWords,
420
+ unicodeBoundaries: options.unicodeBoundaries,
421
+ caseInsensitive: options.caseInsensitive,
422
+ });
423
+
424
+ return { type: "ac", ac, indexMap, nameMap };
425
+ }
426
+
427
+ /**
428
+ * Build a FuzzySearch engine from fuzzy patterns.
429
+ */
430
+ function buildFuzzyEngine(
431
+ patterns: ClassifiedPattern[],
432
+ options: {
433
+ unicodeBoundaries: boolean;
434
+ wholeWords: boolean;
435
+ metric?: "levenshtein" | "damerau-levenshtein";
436
+ normalizeDiacritics?: boolean;
437
+ caseInsensitive?: boolean;
438
+ },
439
+ ): FuzzySlot {
440
+ const fsPatterns: {
441
+ pattern: string;
442
+ distance?: number | "auto";
443
+ name?: string;
444
+ }[] = [];
445
+ const indexMap: number[] = [];
446
+ const nameMap: (string | undefined)[] = [];
447
+
448
+ for (const cp of patterns) {
449
+ const entry: (typeof fsPatterns)[number] = {
450
+ pattern: cp.pattern as string,
451
+ };
452
+ if (cp.fuzzyDistance !== undefined)
453
+ entry.distance = cp.fuzzyDistance;
454
+ if (cp.name !== undefined) entry.name = cp.name;
455
+ fsPatterns.push(entry);
456
+ indexMap.push(cp.originalIndex);
457
+ nameMap.push(cp.name);
458
+ }
459
+
460
+ const fsOptions: ConstructorParameters<
461
+ typeof FuzzySearch
462
+ >[1] = {
463
+ unicodeBoundaries: options.unicodeBoundaries,
464
+ wholeWords: options.wholeWords,
465
+ };
466
+ if (options.metric !== undefined)
467
+ fsOptions.metric = options.metric;
468
+ if (options.normalizeDiacritics !== undefined)
469
+ fsOptions.normalizeDiacritics =
470
+ options.normalizeDiacritics;
471
+ if (options.caseInsensitive !== undefined)
472
+ fsOptions.caseInsensitive =
473
+ options.caseInsensitive;
474
+ const fs = new FuzzySearch(fsPatterns, fsOptions);
475
+
476
+ return { type: "fuzzy", fs, indexMap, nameMap };
477
+ }
478
+
479
+ /**
480
+ * Dispatch isMatch to the correct engine.
481
+ */
482
+ function engineIsMatch(
483
+ engine: EngineSlot,
484
+ haystack: string,
485
+ ): boolean {
486
+ switch (engine.type) {
487
+ case "ac":
488
+ return engine.ac.isMatch(haystack);
489
+ case "fuzzy":
490
+ return engine.fs.isMatch(haystack);
491
+ case "regex":
492
+ return engine.rs.isMatch(haystack);
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Dispatch findIter to the correct engine.
498
+ */
499
+ function engineFindIter(
500
+ engine: EngineSlot,
501
+ haystack: string,
502
+ ): Match[] {
503
+ switch (engine.type) {
504
+ case "ac":
505
+ return engine.ac.findIter(haystack);
506
+ case "fuzzy":
507
+ return engine.fs.findIter(haystack);
508
+ case "regex":
509
+ return engine.rs.findIter(haystack);
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Remap engine-local match indices to original
515
+ * input indices and add names.
516
+ */
517
+ function remapMatches(
518
+ matches: Match[],
519
+ engine: EngineSlot,
520
+ ): Match[] {
521
+ return matches.map((m) => {
522
+ const originalIdx =
523
+ engine.indexMap[m.pattern]!;
524
+ const name = engine.nameMap[m.pattern];
525
+ const result: Match = {
526
+ pattern: originalIdx,
527
+ start: m.start,
528
+ end: m.end,
529
+ text: m.text,
530
+ };
531
+ if (name !== undefined) {
532
+ result.name = name;
533
+ }
534
+ // Preserve edit distance from fuzzy matches
535
+ if ("distance" in m && m.distance !== undefined) {
536
+ result.distance = m.distance as number;
537
+ }
538
+ return result;
539
+ });
540
+ }
package/src/types.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * A single match result. Same shape as
3
+ * @stll/regex-set and @stll/aho-corasick.
4
+ */
5
+ export type Match = {
6
+ /** Index of the pattern that matched. */
7
+ pattern: number;
8
+ /** Start UTF-16 code unit offset. */
9
+ start: number;
10
+ /** End offset (exclusive). */
11
+ end: number;
12
+ /** The matched text. */
13
+ text: string;
14
+ /** Pattern name (if provided). */
15
+ name?: string;
16
+ /** Edit distance (fuzzy matches only). */
17
+ distance?: number;
18
+ };
19
+
20
+ /** A pattern entry for TextSearch. */
21
+ export type PatternEntry =
22
+ | string
23
+ | RegExp
24
+ | {
25
+ pattern: string | RegExp;
26
+ name?: string;
27
+ }
28
+ | {
29
+ pattern: string;
30
+ name?: string;
31
+ /** Fuzzy matching distance. Routes to
32
+ * @stll/fuzzy-search instead of regex. */
33
+ distance: number | "auto";
34
+ }
35
+ | {
36
+ pattern: string;
37
+ name?: string;
38
+ /** Force literal matching via Aho-Corasick.
39
+ * Skips regex metacharacter detection so
40
+ * patterns like "č.p." or "s.r.o." are
41
+ * matched literally, not as regex. */
42
+ literal: true;
43
+ /** Per-pattern case-insensitive for AC.
44
+ * Overrides the global option for this
45
+ * pattern only. */
46
+ caseInsensitive?: boolean;
47
+ /** Per-pattern whole-word matching for AC. */
48
+ wholeWords?: boolean;
49
+ };
50
+
51
+ /** Options for TextSearch. */
52
+ export type TextSearchOptions = {
53
+ /**
54
+ * Use Unicode word boundaries.
55
+ * @default true
56
+ */
57
+ unicodeBoundaries?: boolean;
58
+
59
+ /**
60
+ * Only match whole words.
61
+ * @default false
62
+ */
63
+ wholeWords?: boolean;
64
+
65
+ /**
66
+ * Max alternation branches before auto-splitting
67
+ * into a separate engine instance. Prevents DFA
68
+ * state explosion when large-alternation patterns
69
+ * are combined with other patterns.
70
+ * @default 50
71
+ */
72
+ maxAlternations?: number;
73
+
74
+ /**
75
+ * Fuzzy matching metric.
76
+ * @default "levenshtein"
77
+ */
78
+ fuzzyMetric?: "levenshtein" | "damerau-levenshtein";
79
+
80
+ /**
81
+ * Normalize diacritics for fuzzy matching.
82
+ * @default false
83
+ */
84
+ normalizeDiacritics?: boolean;
85
+
86
+ /**
87
+ * Case-insensitive matching for AC literals
88
+ * and fuzzy patterns.
89
+ * @default false
90
+ */
91
+ caseInsensitive?: boolean;
92
+
93
+ /**
94
+ * How to handle overlapping matches from
95
+ * different engines or patterns.
96
+ *
97
+ * - "longest": keep longest non-overlapping match
98
+ * at each position (default).
99
+ * - "all": return all matches including overlaps.
100
+ * Useful when the caller applies its own dedup.
101
+ *
102
+ * @default "longest"
103
+ */
104
+ overlapStrategy?: "longest" | "all";
105
+
106
+ /**
107
+ * Treat ALL string patterns as literals (route
108
+ * to AC, skip metacharacter detection). Useful
109
+ * for deny-list patterns where "s.r.o." means
110
+ * the literal string, not a regex with wildcards.
111
+ * @default false
112
+ */
113
+ allLiteral?: boolean;
114
+ };