@stll/text-normalize 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,8 +61,18 @@ generated with.
61
61
 
62
62
  ## Substring matching with highlight offsets
63
63
 
64
- `foldSearchMatchText` is the client-side match key for interactive
65
- filtering: NFKD, the `unaccent()`-parity ASCII folds, mark strip, Arabic
64
+ `createSearchQueryMatcher(query)` (from `@stll/text-normalize/search-query-matcher`) is the client-side answer to "does this
65
+ text match what the user typed": it trims and folds the query once and returns
66
+ a predicate over candidate texts (a blank query matches everything, a missing
67
+ candidate nothing). `filterBySearchQuery({ items, query, fields })` applies it
68
+ to a list, keeping the items any field of which matches. Use these for every
69
+ picker, list filter and typeahead, so a query typed without accents (`dvorak`,
70
+ `strasse`, `lodz`) finds the same items everywhere and in every UI locale. An
71
+ `Intl.Collator` with `sensitivity: "base"` is not an alternative: it compares
72
+ equal-length windows (`strasse` misses `Straße`), its verdict depends on the
73
+ runtime locale, and it keeps Arabic tashkeel significant.
74
+
75
+ `foldSearchMatchText` is the match key both sides are folded with: NFKD, the `unaccent()`-parity ASCII folds, mark strip, Arabic
66
76
  folds, lowercase — `capek` matches `Čapek` and `wroclaw` matches
67
77
  `Wrocław`, both ways. `findSearchMatchRanges` finds a folded query in
68
78
  folded content and returns ranges into the **original** string, so
@@ -80,9 +90,9 @@ import {
80
90
  ```
81
91
 
82
92
  `containsSearchMatchKey(content, query)` checks a literal substring in keys
83
- already prepared by the caller. It does not trim or fold either input, so a
84
- picker can retain locale-specific casing or accent-sensitive matching. Empty
85
- queries match every key. For accent-insensitive highlight ranges into original
93
+ already prepared by the caller, such as fixed tokens in a message or keys a
94
+ caller folded itself. It does not trim or fold either input; a user-typed query
95
+ goes through `createSearchQueryMatcher` instead. Empty queries match every key. For accent-insensitive highlight ranges into original
86
96
  text, use `findSearchMatchRanges` from `@stll/text-normalize` instead.
87
97
 
88
98
  `findSearchMatchKeyRanges(content, query, { start?, end?, maxMatches? })`
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The client-side match for user-typed queries, kept out of the package root
3
+ * so the corpus parsers that read the root do not depend on it.
4
+ */
5
+ /** Whether one candidate text contains the query a matcher was built for. */
6
+ export type SearchQueryMatcher = (candidate: string | null | undefined) => boolean;
7
+ /**
8
+ * The client-side answer to "does this text match what the user typed".
9
+ *
10
+ * Both sides go through `foldSearchMatchText`, so case, accents, letters
11
+ * without a decomposition (`ł`, `ø`, `ß` → `ss`), compatibility ligatures and
12
+ * Arabic orthographic variants are ignored identically in every UI locale,
13
+ * and a filtered list agrees with the highlights `findSearchMatchRanges`
14
+ * draws in it. The query is trimmed and folded once and candidate keys are
15
+ * cached; a blank query matches every candidate, and a missing candidate
16
+ * matches none. Lone surrogates become U+FFFD on both sides, so a query can
17
+ * never match half of an astral character.
18
+ *
19
+ * Preferred over an `Intl.Collator` with `sensitivity: "base"`: a collator
20
+ * compares equal-length windows, so `strasse` never finds `Straße`; its
21
+ * verdict depends on the runtime locale (Turkish `ISTANBUL` misses
22
+ * `istanbul`, German `Müller` misses `muller`); it keeps Arabic tashkeel
23
+ * significant; and it compares every window of every item per keystroke,
24
+ * where a fold key is computed once per text.
25
+ */
26
+ export declare const createSearchQueryMatcher: (query: string) => SearchQueryMatcher;
27
+ type FilterBySearchQueryOptions<T> = {
28
+ /** The texts an item is found by; it matches when any of them does. */
29
+ fields: (item: T) => readonly (string | null | undefined)[];
30
+ items: readonly T[];
31
+ query: string;
32
+ };
33
+ /**
34
+ * The items any of whose fields matches the query, in their given order,
35
+ * through `createSearchQueryMatcher`. A blank query keeps every item.
36
+ */
37
+ export declare const filterBySearchQuery: <T>({ fields, items, query, }: FilterBySearchQueryOptions<T>) => T[];
38
+ export {};
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The client-side match for user-typed queries, kept out of the package root
3
+ * so the corpus parsers that read the root do not depend on it.
4
+ */
5
+ import { foldSearchMatchText } from "./search-match.js";
6
+ // A list filter folds the same names on every keystroke. Remembering their
7
+ // keys turns a keystroke over 2,000 three-field rows from about 3 ms into
8
+ // about 0.2 ms, level with a bare `toLowerCase().includes()`. The fold is
9
+ // pure, so the cache is unobservable; clearing it whole when full bounds its
10
+ // memory without an eviction policy.
11
+ const CANDIDATE_KEY_CACHE_LIMIT = 10_000;
12
+ const candidateKeys = new Map();
13
+ const candidateKey = (candidate) => {
14
+ const cached = candidateKeys.get(candidate);
15
+ if (cached !== undefined) {
16
+ return cached;
17
+ }
18
+ if (candidateKeys.size >= CANDIDATE_KEY_CACHE_LIMIT) {
19
+ candidateKeys.clear();
20
+ }
21
+ const key = foldSearchMatchText(candidate.toWellFormed());
22
+ candidateKeys.set(candidate, key);
23
+ return key;
24
+ };
25
+ /**
26
+ * The client-side answer to "does this text match what the user typed".
27
+ *
28
+ * Both sides go through `foldSearchMatchText`, so case, accents, letters
29
+ * without a decomposition (`ł`, `ø`, `ß` → `ss`), compatibility ligatures and
30
+ * Arabic orthographic variants are ignored identically in every UI locale,
31
+ * and a filtered list agrees with the highlights `findSearchMatchRanges`
32
+ * draws in it. The query is trimmed and folded once and candidate keys are
33
+ * cached; a blank query matches every candidate, and a missing candidate
34
+ * matches none. Lone surrogates become U+FFFD on both sides, so a query can
35
+ * never match half of an astral character.
36
+ *
37
+ * Preferred over an `Intl.Collator` with `sensitivity: "base"`: a collator
38
+ * compares equal-length windows, so `strasse` never finds `Straße`; its
39
+ * verdict depends on the runtime locale (Turkish `ISTANBUL` misses
40
+ * `istanbul`, German `Müller` misses `muller`); it keeps Arabic tashkeel
41
+ * significant; and it compares every window of every item per keystroke,
42
+ * where a fold key is computed once per text.
43
+ */
44
+ export const createSearchQueryMatcher = (query) => {
45
+ const foldedQuery = foldSearchMatchText(query.trim().toWellFormed());
46
+ if (foldedQuery === "") {
47
+ return () => true;
48
+ }
49
+ return (candidate) => candidate !== null &&
50
+ candidate !== undefined &&
51
+ candidateKey(candidate).includes(foldedQuery);
52
+ };
53
+ /**
54
+ * The items any of whose fields matches the query, in their given order,
55
+ * through `createSearchQueryMatcher`. A blank query keeps every item.
56
+ */
57
+ export const filterBySearchQuery = ({ fields, items, query, }) => {
58
+ const matches = createSearchQueryMatcher(query);
59
+ return items.filter((item) => fields(item).some(matches));
60
+ };
61
+ //# sourceMappingURL=search-query-matcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-query-matcher.js","sourceRoot":"","sources":["../src/search-query-matcher.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,2EAA2E;AAC3E,0EAA0E;AAC1E,0EAA0E;AAC1E,6EAA6E;AAC7E,qCAAqC;AACrC,MAAM,yBAAyB,GAAG,MAAM,CAAC;AACzC,MAAM,aAAa,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEhD,MAAM,YAAY,GAAG,CAAC,SAAiB,EAAU,EAAE;IACjD,MAAM,MAAM,GAAG,aAAa,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC5C,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,IAAI,aAAa,CAAC,IAAI,IAAI,yBAAyB,EAAE,CAAC;QACpD,aAAa,CAAC,KAAK,EAAE,CAAC;IACxB,CAAC;IACD,MAAM,GAAG,GAAG,mBAAmB,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC,CAAC;IAC1D,aAAa,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IAClC,OAAO,GAAG,CAAC;AACb,CAAC,CAAC;AAOF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAa,EAAsB,EAAE;IAC5E,MAAM,WAAW,GAAG,mBAAmB,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,CAAC;IACrE,IAAI,WAAW,KAAK,EAAE,EAAE,CAAC;QACvB,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,SAAS,EAAE,EAAE,CACnB,SAAS,KAAK,IAAI;QAClB,SAAS,KAAK,SAAS;QACvB,YAAY,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAClD,CAAC,CAAC;AASF;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAI,EACrC,MAAM,EACN,KAAK,EACL,KAAK,GACyB,EAAO,EAAE;IACvC,MAAM,OAAO,GAAG,wBAAwB,CAAC,KAAK,CAAC,CAAC;IAChD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;AAC5D,CAAC,CAAC"}
package/dist/slug.d.ts CHANGED
@@ -7,10 +7,11 @@
7
7
  * characters into one separator, clip, trim a trailing separator, fall back
8
8
  * when nothing is left — was identical in all four and is fixed here.
9
9
  *
10
- * Deliberately does NOT transliterate. `slugify("café")` is `"caf"` under the
11
- * `ascii` charset, not `"cafe"`: slugs are persisted, and folding here would
12
- * quietly start minting different keys for the same labels. The folding
13
- * primitives in this package are for search text, where nothing is stored.
10
+ * The `ascii` charset transliterates Latin letters before filtering:
11
+ * `slugify("Łódź")` is `"lodz"`, not `"odz"`. A key minted before
12
+ * transliteration is not recomputed by its owner; a caller that re-derives a
13
+ * stored key at lookup (the case-law routes) recognises the earlier fold
14
+ * itself.
14
15
  *
15
16
  * Single-pass by construction: a regex pipeline over untrusted label text is
16
17
  * what the slow-regex guard exists to prevent.
@@ -19,7 +20,7 @@
19
20
  * Which characters survive.
20
21
  *
21
22
  * - `ascii` keeps `[a-z0-9]`, for keys that end up in URLs and columns
22
- * validated against that charset.
23
+ * validated against that charset. Latin letters are transliterated first.
23
24
  * - `unicode` keeps any Unicode letter or number, for paths shown back to the
24
25
  * person who typed them.
25
26
  */
package/dist/slug.js CHANGED
@@ -1,3 +1,4 @@
1
+ // parser-output-unchanged: no case-law or legislation adapter or parser calls slugify; adapters reach this module only through the package index.
1
2
  /**
2
3
  * One slug generator for the key-shaped strings the apps derive from a label.
3
4
  *
@@ -7,15 +8,28 @@
7
8
  * characters into one separator, clip, trim a trailing separator, fall back
8
9
  * when nothing is left — was identical in all four and is fixed here.
9
10
  *
10
- * Deliberately does NOT transliterate. `slugify("café")` is `"caf"` under the
11
- * `ascii` charset, not `"cafe"`: slugs are persisted, and folding here would
12
- * quietly start minting different keys for the same labels. The folding
13
- * primitives in this package are for search text, where nothing is stored.
11
+ * The `ascii` charset transliterates Latin letters before filtering:
12
+ * `slugify("Łódź")` is `"lodz"`, not `"odz"`. A key minted before
13
+ * transliteration is not recomputed by its owner; a caller that re-derives a
14
+ * stored key at lookup (the case-law routes) recognises the earlier fold
15
+ * itself.
14
16
  *
15
17
  * Single-pass by construction: a regex pipeline over untrusted label text is
16
18
  * what the slow-regex guard exists to prevent.
17
19
  */
20
+ import { applyAsciiFolds } from "./ascii-fold.js";
18
21
  const UNICODE_SLUG_CHARACTER = /[\p{L}\p{N}]/u;
22
+ /** Compatibility decomposition, the search fold's mark strip and the table. */
23
+ const spellInAscii = (text) => applyAsciiFolds(text.normalize("NFKD"));
24
+ /**
25
+ * Latin letters spelled in ASCII: compatibility decomposition (`fi`, `A`), the
26
+ * search fold's mark strip (`č`), and the `unaccent()` table for letters no
27
+ * decomposition reaches (`ł`, `ø`, `ß`, `þ`, `ı`). The table is not closed
28
+ * under case (`Ɩ` folds and its small letter `ɩ` does not; `ɡ` folds and its
29
+ * capital `Ɡ` does not), so it applies on both sides of the lowercase. Other
30
+ * scripts pass through and are filtered out.
31
+ */
32
+ const transliterateToAscii = (value) => spellInAscii(spellInAscii(value).toLowerCase()).toLowerCase();
19
33
  const isSlugCharacter = (character, charset) => {
20
34
  if (charset === "unicode") {
21
35
  return UNICODE_SLUG_CHARACTER.test(character);
@@ -24,9 +38,10 @@ const isSlugCharacter = (character, charset) => {
24
38
  (character >= "0" && character <= "9"));
25
39
  };
26
40
  export const slugify = (value, { charset, separator, maxLength, fallback }) => {
41
+ const source = charset === "ascii" ? transliterateToAscii(value) : value.toLowerCase();
27
42
  let buffer = "";
28
43
  let lastWasSeparator = true;
29
- for (const character of value.toLowerCase()) {
44
+ for (const character of source) {
30
45
  if (isSlugCharacter(character, charset)) {
31
46
  buffer += character;
32
47
  lastWasSeparator = false;
package/dist/slug.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"slug.js","sourceRoot":"","sources":["../src/slug.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAgCH,MAAM,sBAAsB,GAAG,eAAe,CAAC;AAE/C,MAAM,eAAe,GAAG,CAAC,SAAiB,EAAE,OAAoB,EAAW,EAAE;IAC3E,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,sBAAsB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,CACL,CAAC,SAAS,IAAI,GAAG,IAAI,SAAS,IAAI,GAAG,CAAC;QACtC,CAAC,SAAS,IAAI,GAAG,IAAI,SAAS,IAAI,GAAG,CAAC,CACvC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,OAAO,GAAG,CACrB,KAAa,EACb,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAkB,EACnD,EAAE;IACV,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,gBAAgB,GAAG,IAAI,CAAC;IAE5B,KAAK,MAAM,SAAS,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;QAC5C,IAAI,eAAe,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,CAAC;YACxC,MAAM,IAAI,SAAS,CAAC;YACpB,gBAAgB,GAAG,KAAK,CAAC;YACzB,SAAS;QACX,CAAC;QACD,IA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QAAQ,CAAC;AAC7B,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/text-normalize",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Search match-key text normalization — Arabic orthographic variant folding (alef/hamza/teh-marbuta/yeh, tashkeel, tatweel, digits) with per-language fold tables",
5
5
  "keywords": [
6
6
  "arabic",
@@ -36,6 +36,10 @@
36
36
  "./search-match-key": {
37
37
  "types": "./dist/search-match-key.d.ts",
38
38
  "import": "./dist/search-match-key.js"
39
+ },
40
+ "./search-query-matcher": {
41
+ "types": "./dist/search-query-matcher.d.ts",
42
+ "import": "./dist/search-query-matcher.js"
39
43
  }
40
44
  },
41
45
  "publishConfig": {
@@ -50,13 +54,12 @@
50
54
  "typecheck": "bun check --no-pretty --all --project=tsconfig.json",
51
55
  "lint": "cd ../.. && bun --bun oxlint -c oxlint.config.ts --report-unused-disable-directives-severity=error --type-aware --type-check packages/text-normalize",
52
56
  "lint:fix": "cd ../.. && bun --bun oxlint -c oxlint.config.ts --type-aware --fix packages/text-normalize",
53
- "format": "bun ../../scripts/run-oxfmt.ts .",
54
57
  "prepack": "bun run build"
55
58
  },
56
59
  "devDependencies": {
57
60
  "@stll/property-testing": "0.0.0",
58
61
  "@stll/typescript-config": "0.0.0",
59
- "bun-types": "1.4.3",
62
+ "bun-types": "1.4.4",
60
63
  "fast-check": "^4.10.2"
61
64
  }
62
65
  }