@datakable/core 2.1.0 → 2.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.
@@ -87,8 +87,8 @@ function* buildIndex(ctx, config, useExSearch) {
87
87
  const reads = [];
88
88
  for (const col of cols.list) {
89
89
  if (cols.byId.get(col.id) !== col) continue;
90
- const w = col.def.search;
91
- const weight = declared ? typeof w === "number" && w > 0 ? w : 0 : 1;
90
+ const w2 = col.def.search;
91
+ const weight = declared ? typeof w2 === "number" && w2 > 0 ? w2 : 0 : 1;
92
92
  if (weight === 0) continue;
93
93
  const path = col.format ? void 0 : col.path;
94
94
  let failed = false;
@@ -126,45 +126,101 @@ function* buildIndex(ctx, config, useExSearch) {
126
126
  yield;
127
127
  }
128
128
  if (keys.length === 0) return null;
129
+ const w = keys.map((k) => k.weight).join();
130
+ const hash = (r) => {
131
+ let a = 3735928559;
132
+ let b = 1103547991;
133
+ for (const read of reads) {
134
+ const v = read(r);
135
+ for (let j = 0; j <= v.length; j++) {
136
+ const c = v.charCodeAt(j) + 1;
137
+ a = Math.imul(a ^ c, 2654435761);
138
+ b = Math.imul(b ^ c, 1597334677);
139
+ }
140
+ }
141
+ a = Math.imul(a ^ a >>> 16, 2246822507) ^ Math.imul(b ^ b >>> 13, 3266489909);
142
+ b = Math.imul(b ^ b >>> 16, 2246822507) ^ Math.imul(a ^ a >>> 13, 3266489909);
143
+ return 4294967296 * (2097151 & b) + (a >>> 0);
144
+ };
129
145
  const fold = (v) => config.caseSensitive ? v : v.toLowerCase();
130
146
  const foldQuery = (q) => fold(q.normalize("NFC"));
131
147
  const at = (k, r) => fold(reads[k](r));
132
- return useExSearch ? exSearchIndex(keys, at, foldQuery, config) : containsIndex(keys, at, foldQuery, config);
133
- }
134
- function* chunked(rows, columns, matchChunk) {
135
- const size = Math.max(256, Math.floor(CELLS / columns));
136
- if (rows.length <= size) return rankHits(matchChunk(rows));
137
- const hits = [];
138
- for (let k = 0; k < rows.length; k += size) {
139
- for (const h of matchChunk(rows.subarray(k, k + size))) hits.push(h);
140
- yield;
141
- }
142
- return rankHits(hits);
148
+ const matchChunk = (useExSearch ? exSearchIndex : containsIndex)(keys, at, config);
149
+ const h = new Float64Array(n).fill(-1);
150
+ return {
151
+ *match(rows, query, memo) {
152
+ const q = foldQuery(query);
153
+ const prev = memo?.scores;
154
+ const old = prev?.q === query && prev.w === w ? prev : void 0;
155
+ const d = old ? old.h.length - n : 0;
156
+ const cut = !old && prev?.h === h && prev.w === w && matchChunk.narrows?.(foldQuery(prev.q), q);
157
+ const s = new Float64Array(n).fill(Number.NaN);
158
+ const size = Math.max(256, Math.floor(CELLS / keys.length));
159
+ const hits = [];
160
+ for (let k = 0; k < rows.length; k += size) {
161
+ if (k) yield;
162
+ const chunk = rows.subarray(k, k + size);
163
+ const miss = [];
164
+ for (const r of chunk) {
165
+ let x = h[r];
166
+ if (x < 0) {
167
+ x = hash(r);
168
+ h[r] = x;
169
+ }
170
+ s[r] = -1;
171
+ if (cut) {
172
+ if (prev.s[r] !== -1) miss.push(r);
173
+ continue;
174
+ }
175
+ if (!old) continue;
176
+ const j = old.h[r] === x ? r : old.h[r + d] === x ? r + d : -1;
177
+ const v = old.s[j];
178
+ if (v >= -1) {
179
+ s[r] = v;
180
+ if (v >= 0) hits.push({ i: r, score: v });
181
+ } else miss.push(r);
182
+ }
183
+ const todo = old || cut ? Uint32Array.from(miss) : chunk;
184
+ if (todo.length) {
185
+ for (const hit of matchChunk(todo, q)) {
186
+ s[hit.i] = hit.score;
187
+ hits.push(hit);
188
+ }
189
+ }
190
+ }
191
+ if (memo) memo.scores = { q: query, w, h, s };
192
+ return rankHits(hits);
193
+ }
194
+ };
143
195
  }
144
196
  function projection(keys, at) {
145
197
  let rows = new Uint32Array(0);
198
+ let held = [];
146
199
  const target = [];
147
200
  const items = new Proxy(target, {
148
201
  get(t, p) {
149
202
  if (p === "length") return rows.length;
150
203
  const j = (0, import_row.arrayIndex)(p, rows.length);
151
204
  if (j < 0) return t[p];
205
+ if (held[j]) return held[j];
152
206
  const r = rows[j];
153
207
  const o = { i: r };
154
208
  for (let k = 0; k < keys.length; k++) o[keys[k].name] = at(k, r);
209
+ held[j] = o;
155
210
  return o;
156
211
  },
157
212
  has: (t, p) => (0, import_row.arrayIndex)(p, rows.length) >= 0 || p in t
158
213
  });
159
214
  return {
160
215
  items,
161
- /** Shows `chunk` (row indices). */
216
+ /** Shows `chunk` (row indices), each item built once until the next `show`. */
162
217
  show(chunk) {
163
218
  rows = chunk;
219
+ held = [];
164
220
  }
165
221
  };
166
222
  }
167
- function exSearchIndex(keys, at, fold, config) {
223
+ function exSearchIndex(keys, at, config) {
168
224
  const engine = new import_ex_search.ExSearch({
169
225
  keys,
170
226
  ...config,
@@ -175,40 +231,32 @@ function exSearchIndex(keys, at, fold, config) {
175
231
  });
176
232
  const view = projection(keys, at);
177
233
  engine.setData(view.items);
178
- return {
179
- match(rows, query) {
180
- const q = fold(query);
181
- const fuzzyMode = /\s/.test(q) ? "value" : "word";
182
- return chunked(rows, keys.length, (chunk) => {
183
- engine.updateConfig({ fuzzyMode });
184
- view.show(chunk);
185
- const hits = engine.search(q);
186
- engine.updateConfig({});
187
- return hits;
188
- });
189
- }
234
+ const match = (chunk, q) => {
235
+ engine.updateConfig({ fuzzyMode: !config.fuzzyMaxDistance || /\s/.test(q) ? "value" : "word" });
236
+ view.show(chunk);
237
+ const hits = engine.search(q);
238
+ engine.updateConfig({});
239
+ view.show(chunk);
240
+ return hits;
190
241
  };
242
+ match.narrows = (prev, next) => engine.canNarrow?.(prev, next);
243
+ return match;
191
244
  }
192
- function containsIndex(keys, at, fold, config) {
193
- return {
194
- match(rows, query) {
195
- const q = fold(query);
196
- return chunked(rows, keys.length, (chunk) => {
197
- const hits = [];
198
- for (let j = 0; j < chunk.length; j++) {
199
- const r = chunk[j];
200
- let best = 0;
201
- for (let k = 0; k < keys.length; k++) {
202
- const v = at(k, r);
203
- const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0;
204
- const w = keys[k].weight;
205
- if (raw * w > best) best = raw * w;
206
- }
207
- if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best });
208
- }
209
- return hits;
210
- });
245
+ function containsIndex(keys, at, config) {
246
+ return (chunk, q) => {
247
+ const hits = [];
248
+ for (let j = 0; j < chunk.length; j++) {
249
+ const r = chunk[j];
250
+ let best = 0;
251
+ for (let k = 0; k < keys.length; k++) {
252
+ const v = at(k, r);
253
+ const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0;
254
+ const w = keys[k].weight;
255
+ if (raw * w > best) best = raw * w;
256
+ }
257
+ if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best });
211
258
  }
259
+ return hits;
212
260
  };
213
261
  }
214
262
  function rankHits(hits) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/features/search/search-index.ts"],"sourcesContent":["import { ExSearch } from 'ex-search'\nimport { getValue } from '../../column/get-value'\nimport '../../diagnostics/process-guard'\nimport type { Emit } from '../../diagnostics/types'\nimport type { RowModelContext } from '../../feature/types'\nimport { nullishOf, type SlicedFormatting } from '../../pipeline/column-cache'\nimport { resolveColumns } from '../../pipeline/columns'\nimport { arrayIndex } from '../../pipeline/row'\nimport { detectCapability, hasCapability } from '../../versioning/capability'\n\n/** Matcher settings (the client options of `search()`, defaults applied). */\nexport interface MatchConfig {\n readonly threshold: number\n readonly fuzzyMaxDistance: number\n readonly caseSensitive: boolean\n}\n\n/**\n * One projected row as ex-search reads it: `i` is the row index (results map back by it, never by\n * identity: ex-search returns copies), `c0`, `c1`, … the formatted values of the searchable\n * columns. Flat keys also sidestep ex-search's top-level-key limitation for nested paths. Items\n * are built per chunk while matching and dropped after it (§9.3 memory): none is kept.\n */\nexport type Item = Record<string, string | number> & { readonly i: number }\n\n/** A match: the row index and its relevance (0–1, weight applied). */\nexport interface Hit {\n readonly i: number\n readonly score: number\n}\n\n/** The matcher of one (data, columns) pair: references to column values, no per-row copy. */\nexport interface SearchIndex {\n /**\n * A time-sliced job (§9.1) matching `query` (trimmed, non-blank) against the rows `rows` (row\n * indices), in chunks: the hits in relevance order ({@link rankHits}).\n */\n match(rows: Uint32Array, query: string): Generator<undefined, Uint32Array, undefined>\n}\n\n/** Rows per chunk between two `yield`s of a scan (one value per row). */\nconst CHUNK = 4096\n\n/**\n * Cells (rows × searchable columns) matched per chunk between two `yield`s (#40): a table with\n * many searchable columns matches fewer rows per chunk, so a chunk stays a few milliseconds.\n */\nconst CELLS = 16_384\n\ninterface Key {\n readonly name: string\n readonly weight: number\n}\n\n/** The formatted value of row `r` of one searchable column. */\ntype Read = (r: number) => string\n\n// A throw (no `ExSearch`) counts as missing (hasCapability).\nconst hasExSearch = () =>\n [ExSearch.prototype.search, ExSearch.prototype.setData, ExSearch.prototype.updateConfig].every(\n (f) => typeof f === 'function',\n )\n\n/** Feature-detects ex-search once (§8.5); `false` → the contains fallback. */\nexport function probeExSearch(emit: Emit): boolean {\n // DK_DEP_INCOMPATIBLE is a development check (§8.5); the fallback is not.\n return (process.env.NODE_ENV !== \"production\")\n ? detectCapability(\n hasExSearch,\n {\n feature: 'search',\n dependency: 'ex-search',\n capability: \"ExSearch (fuzzyMode: 'word')\",\n supported: '^1.2.0',\n fallback: 'case-insensitive exact / prefix / substring matching (no fuzzy matching)',\n },\n emit,\n )\n : hasCapability(hasExSearch)\n}\n\n/**\n * A numeric column's formatted value without cached strings (#27): what the default formatter\n * shows, `String(v)`, or `''` for a `null` / `undefined` cell (stored as `NaN`, like a real `NaN`,\n * which shows `'NaN'`).\n */\nfunction numberReader(values: Float64Array): Read {\n const nullish = nullishOf(values)\n return (r) => {\n const v = values[r] as number\n return !Number.isNaN(v) ? String(v) : nullish?.[r] ? '' : 'NaN'\n }\n}\n\n/**\n * One pass over a column's values (`get(r)` per row, time-sliced by `CHUNK` rows): their text as\n * the default formatter shows a primitive (`String(v)`, `''` when nullish), read while matching\n * (#27: no formatted copy per row). `false` at the first object or function (a `Date`, an array):\n * the column cache formats those. `undefined` when a read throws. The values are read in NFC (#30),\n * normalised here, never per keystroke: the rows whose value is not NFC (rare: NFD input from\n * macOS, Thai or Vietnamese keyboards) keep their NFC form in a sparse map. Only values with a code\n * unit from U+0300 (combining marks and up) can change.\n */\nfunction* scan(\n size: number,\n get: (r: number) => unknown,\n): Generator<undefined, Read | false | undefined, undefined> {\n const over = new Map<number, string>()\n try {\n for (let r = 0; r < size; r++) {\n const v = get(r)\n if (v !== null && (typeof v === 'object' || typeof v === 'function')) return false\n if (typeof v === 'string' && /[\\u0300-\\uffff]/.test(v)) {\n const n = v.normalize('NFC')\n if (n !== v) over.set(r, n)\n }\n if (r % CHUNK === CHUNK - 1) yield\n }\n } catch {\n return undefined\n }\n const read: Read = (r) => {\n const v = get(r)\n return v === null || v === undefined ? '' : String(v)\n }\n return over.size ? (r) => over.get(r) ?? read(r) : read\n}\n\n/**\n * Builds the matcher over the formatted values of the searchable columns (what the user sees), once\n * per data + columns, as a time-sliced job (§9.1): one column read per slice. Searchable columns are\n * those with a `search` weight > 0. When no column declares `search`, the columns of primitives\n * (strings, numbers, booleans, nullable) are searchable at weight 1, and a column of dates, arrays\n * or other objects is not (#27: it would keep a formatted string per row; it opts in with a\n * weight; `DK_SEARCH_COLUMN_SKIPPED` in development). `null` when nothing is searchable. Nothing\n * is copied per row (§9.3 memory): a key column of primitives without `format` is read from the\n * rows and stringified while matching (no values array, #27); an accessor column of primitives\n * reads the column cache's values the same way; only a column with `format` or an opted-in object\n * column (dates, arrays) keeps its formatted strings in the column cache. A key column whose read\n * throws goes through the column cache too, which reports it. The case is folded per chunk while\n * matching.\n */\nexport function* buildIndex(\n ctx: RowModelContext,\n config: MatchConfig,\n useExSearch: boolean,\n): Generator<undefined, SearchIndex | null, undefined> {\n const cols = resolveColumns(ctx.columns)\n const declared = cols.list.some((c) => (c.def as { search?: unknown }).search !== undefined)\n const data = ctx.data\n const n = data.length\n const keys: Key[] = []\n const reads: Read[] = []\n for (const col of cols.list) {\n if (cols.byId.get(col.id) !== col) continue\n const w = (col.def as { search?: unknown }).search\n const weight = declared ? (typeof w === 'number' && w > 0 ? w : 0) : 1\n if (weight === 0) continue\n const path = col.format ? undefined : col.path\n let failed = false\n const onError = () => {\n failed = true\n }\n let read = path ? yield* scan(n, (r) => getValue(data[r], path, onError)) : undefined\n if (failed || (read === false && declared)) read = undefined\n if (read === undefined) {\n const values = ctx.getColumnValues(col.id)\n if (!values) continue\n yield // reading a column is a task of its own (#40)\n const numbers = values instanceof Float64Array\n if (numbers && !col.format) read = numberReader(values)\n else {\n // Zero-config: a column of objects is not searched, `format` or not (#27).\n const own =\n numbers || (declared && col.format) ? undefined : yield* scan(n, (r) => values[r])\n if (own === false && !declared) read = false\n else if (own && !col.format) read = own\n else {\n // Time-sliced in a table run (#40): dates or a heavy `format` are not one long task.\n const sliced = (ctx as RowModelContext & SlicedFormatting).formattedSliced\n const formatted = sliced ? yield* sliced(col.id) : ctx.getFormattedValues(col.id)\n if (!formatted) continue\n read = yield* scan(n, (r) => formatted[r])\n }\n }\n }\n if (!read) {\n if ((process.env.NODE_ENV !== \"production\") && read === false) {\n ctx.emit('DK_SEARCH_COLUMN_SKIPPED', { column: col.id, index: col.index })\n }\n continue\n }\n keys.push({ name: `c${keys.length}`, weight })\n reads.push(read)\n yield\n }\n if (keys.length === 0) return null\n // Values (NFC already) are folded per chunk while matching; the query is normalised as well, so\n // NFC and NFD spellings match each other like in the `contains` filter (#30).\n const fold = (v: string) => (config.caseSensitive ? v : v.toLowerCase())\n const foldQuery = (q: string) => fold(q.normalize('NFC'))\n const at = (k: number, r: number) => fold((reads[k] as Read)(r))\n return useExSearch\n ? exSearchIndex(keys, at, foldQuery, config)\n : containsIndex(keys, at, foldQuery, config)\n}\n\n/** Matches `rows` chunk by chunk (`score` decides alone, so chunks match like the whole). */\nfunction* chunked(\n rows: Uint32Array,\n columns: number,\n matchChunk: (chunk: Uint32Array) => Hit[],\n): Generator<undefined, Uint32Array, undefined> {\n const size = Math.max(256, Math.floor(CELLS / columns))\n if (rows.length <= size) return rankHits(matchChunk(rows))\n const hits: Hit[] = []\n for (let k = 0; k < rows.length; k += size) {\n for (const h of matchChunk(rows.subarray(k, k + size))) hits.push(h)\n yield\n }\n return rankHits(hits)\n}\n\n/**\n * The projection as ex-search reads it: an array (`length`, index reads) of `{ i, c0, … }` items,\n * each built when read and not kept. It shows the chunk of rows being matched; ex-search holds\n * this one view (`setData` once).\n */\nfunction projection(keys: readonly Key[], at: (k: number, r: number) => string) {\n let rows: Uint32Array = new Uint32Array(0)\n // Never written, and its own `length` stays 0: `length` is read through the trap below (setting\n // a large `length` would allocate a backing store).\n const target: Item[] = []\n const items = new Proxy(target, {\n get(t, p) {\n if (p === 'length') return rows.length\n const j = arrayIndex(p, rows.length)\n if (j < 0) return t[p as keyof Item[]]\n const r = rows[j] as number\n const o = { i: r } as Record<string, string | number>\n for (let k = 0; k < keys.length; k++) o[(keys[k] as Key).name] = at(k, r)\n return o\n },\n has: (t, p) => arrayIndex(p, rows.length) >= 0 || p in t,\n })\n return {\n items,\n /** Shows `chunk` (row indices). */\n show(chunk: Uint32Array) {\n rows = chunk\n },\n }\n}\n\nfunction exSearchIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n fold: (v: string) => string,\n config: MatchConfig,\n): SearchIndex {\n // Values and query are folded already (buildIndex).\n const engine = new ExSearch<Item>({\n keys: keys as Key[],\n ...config,\n caseSensitive: true,\n // DataKable re-ranks with exact scores and an index tie-break; tim keeps ex-search's own pass\n // stable and avoids radix's score quantisation.\n sortAlgorithm: 'tim',\n })\n // A one-word query is measured against the whole value and each of its words, the best wins: a\n // typo of one word of a multi-word cell matches (#10). ex-search's `fuzzyMode: 'word'` does it\n // with its bounded matcher (#106). A query with whitespace is measured against whole values only,\n // as before (a single word is never that query), and is decided once per query, not per row (#96).\n // ex-search caches the words per position of its data: the view shows another chunk each time,\n // and a cache kept over every row would hold a word list per row and column (tens of MB at 100k\n // rows, §9.3), so it is dropped after each chunk (`updateConfig`) and values are split per chunk.\n const view = projection(keys, at)\n engine.setData(view.items)\n return {\n match(rows, query) {\n const q = fold(query)\n const fuzzyMode = /\\s/.test(q) ? 'value' : 'word'\n return chunked(rows, keys.length, (chunk) => {\n // Set per chunk, like the view: another job may have matched in between.\n engine.updateConfig({ fuzzyMode })\n view.show(chunk)\n // Results are copies of the items (`Omit<Item, …>` drops `i` from the type, not the value).\n const hits = engine.search(q) as unknown as Hit[]\n engine.updateConfig({})\n return hits\n })\n },\n }\n}\n\n/** The fallback when ex-search is missing or incompatible: exact 1 · prefix 0.8 · substring 0.65. */\nfunction containsIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n fold: (v: string) => string,\n config: MatchConfig,\n): SearchIndex {\n return {\n match(rows, query) {\n const q = fold(query)\n return chunked(rows, keys.length, (chunk) => {\n const hits: Hit[] = []\n for (let j = 0; j < chunk.length; j++) {\n const r = chunk[j] as number\n let best = 0\n for (let k = 0; k < keys.length; k++) {\n const v = at(k, r)\n const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0\n const w = (keys[k] as Key).weight\n if (raw * w > best) best = raw * w\n }\n if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best })\n }\n return hits\n })\n },\n }\n}\n\n/**\n * Hits in relevance order (§6.3): score descending, ties by original row index. Enforced here so\n * the order never depends on the matcher's own ranking. Sorts `hits` (a fresh array) in place.\n */\nexport function rankHits(hits: Hit[]): Uint32Array {\n return Uint32Array.from(\n hits.sort((a, b) => b.score - a.score || a.i - b.i),\n (h) => h.i,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAyB;AACzB,uBAAyB;AACzB,2BAAO;AAGP,0BAAiD;AACjD,qBAA+B;AAC/B,iBAA2B;AAC3B,wBAAgD;AAiChD,IAAM,QAAQ;AAMd,IAAM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AO,QAAQ,MAAM,KAAK,QAAQ,CAAC,UAAU;AAC3C,cAAM,OAAc,CAAC;AACrB,iBAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,gBAAM,IAAI,MAAM,CAAC;AACjB,cAAI,OAAO;AACX,mBAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,kBAAM,IAAI,GAAG,GAAG,CAAC;AACjB,kBAAM,MAAM,MAAM,IAAI,IAAI,EAAE,WAAW,CAAC,IAAI,MAAM,EAAE,SAAS,CAAC,IAAI,OAAO;AACzE,kBAAM,IAAK,KAAK,CAAC,EAAU;AAC3B,gBAAI,MAAM,IAAI,KAAM,QAAO,MAAM;AAAA,UACnC;AACA,cAAI,OAAO,KAAK,QAAQ,OAAO,UAAW,MAAK,KAAK,EAAE,GAAG,GAAG,OAAO,KAAK,CAAC;AAAA,QAC3E;AACA,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAMO,SAAS,SAAS,MAA0B;AACjD,SAAO,YAAY;AAAA,IACjB,KAAK,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAAA,IAClD,CAAC,MAAM,EAAE;AAAA,EACX;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/features/search/search-index.ts"],"sourcesContent":["import { ExSearch } from 'ex-search'\nimport { getValue } from '../../column/get-value'\nimport '../../diagnostics/process-guard'\nimport type { Emit } from '../../diagnostics/types'\nimport type { RowModelContext } from '../../feature/types'\nimport { nullishOf, type SlicedFormatting } from '../../pipeline/column-cache'\nimport { resolveColumns } from '../../pipeline/columns'\nimport { arrayIndex } from '../../pipeline/row'\nimport { detectCapability, hasCapability } from '../../versioning/capability'\n\n/** Matcher settings (the client options of `search()`, defaults applied). */\nexport interface MatchConfig {\n readonly threshold: number\n readonly fuzzyMaxDistance: number\n readonly caseSensitive: boolean\n}\n\n/**\n * One projected row as ex-search reads it: `i` is the row index (results map back by it, never by\n * identity: ex-search returns copies), `c0`, `c1`, … the formatted values of the searchable\n * columns. Flat keys also sidestep ex-search's top-level-key limitation for nested paths. Items\n * are built per chunk while matching and dropped after it (§9.3 memory): none is kept.\n */\nexport type Item = Record<string, string | number> & { readonly i: number }\n\n/** A match: the row index and its relevance (0–1, weight applied). */\nexport interface Hit {\n readonly i: number\n readonly score: number\n}\n\n/**\n * The scores of the last match of a table (#95), per data row: `h` the 53-bit hashes of the rows'\n * searched texts (the index's, `-1`: not hashed), `s` its score (`-1`: no hit, `NaN`: not matched).\n * 16 bytes per row.\n */\nexport interface Scores {\n /** The query. */\n readonly q: string\n /** The weights of the searched columns, in key order. */\n readonly w: string\n readonly h: Float64Array\n readonly s: Float64Array\n}\n\n/** The matcher of one (data, columns) pair: references to column values, no per-row copy. */\nexport interface SearchIndex {\n /**\n * A time-sliced job (§9.1) matching `query` (trimmed, non-blank) against the rows `rows` (row\n * indices), in chunks: the hits in relevance order ({@link rankHits}). With `memo`, a row whose\n * searched texts hash like the same row of `memo.scores` (same position, or shifted by the\n * change in length: an insert or a delete) keeps its score and is not matched again (#95). On\n * the same data, a query that provably keeps no row the previous one dropped matches only the\n * previous hits (#96). `memo.scores` is then replaced by this match's.\n */\n match(\n rows: Uint32Array,\n query: string,\n memo?: { scores?: Scores },\n ): Generator<undefined, Uint32Array, undefined>\n}\n\n/** Rows per chunk between two `yield`s of a scan (one value per row). */\nconst CHUNK = 4096\n\n/**\n * Cells (rows × searchable columns) matched per chunk between two `yield`s (#40): a table with\n * many searchable columns matches fewer rows per chunk, so a chunk stays a few milliseconds.\n */\nconst CELLS = 16_384\n\ninterface Key {\n readonly name: string\n readonly weight: number\n}\n\n/** The formatted value of row `r` of one searchable column. */\ntype Read = (r: number) => string\n\n// A throw (no `ExSearch`) counts as missing (hasCapability).\nconst hasExSearch = () =>\n [ExSearch.prototype.search, ExSearch.prototype.setData, ExSearch.prototype.updateConfig].every(\n (f) => typeof f === 'function',\n )\n\n/** Feature-detects ex-search once (§8.5); `false` → the contains fallback. */\nexport function probeExSearch(emit: Emit): boolean {\n // DK_DEP_INCOMPATIBLE is a development check (§8.5); the fallback is not.\n return (process.env.NODE_ENV !== \"production\")\n ? detectCapability(\n hasExSearch,\n {\n feature: 'search',\n dependency: 'ex-search',\n capability: \"ExSearch (fuzzyMode: 'word')\",\n supported: '^1.2.0',\n fallback: 'case-insensitive exact / prefix / substring matching (no fuzzy matching)',\n },\n emit,\n )\n : hasCapability(hasExSearch)\n}\n\n/**\n * A numeric column's formatted value without cached strings (#27): what the default formatter\n * shows, `String(v)`, or `''` for a `null` / `undefined` cell (stored as `NaN`, like a real `NaN`,\n * which shows `'NaN'`).\n */\nfunction numberReader(values: Float64Array): Read {\n const nullish = nullishOf(values)\n return (r) => {\n const v = values[r] as number\n return !Number.isNaN(v) ? String(v) : nullish?.[r] ? '' : 'NaN'\n }\n}\n\n/**\n * One pass over a column's values (`get(r)` per row, time-sliced by `CHUNK` rows): their text as\n * the default formatter shows a primitive (`String(v)`, `''` when nullish), read while matching\n * (#27: no formatted copy per row). `false` at the first object or function (a `Date`, an array):\n * the column cache formats those. `undefined` when a read throws. The values are read in NFC (#30),\n * normalised here, never per keystroke: the rows whose value is not NFC (rare: NFD input from\n * macOS, Thai or Vietnamese keyboards) keep their NFC form in a sparse map. Only values with a code\n * unit from U+0300 (combining marks and up) can change.\n */\nfunction* scan(\n size: number,\n get: (r: number) => unknown,\n): Generator<undefined, Read | false | undefined, undefined> {\n const over = new Map<number, string>()\n try {\n for (let r = 0; r < size; r++) {\n const v = get(r)\n if (v !== null && (typeof v === 'object' || typeof v === 'function')) return false\n if (typeof v === 'string' && /[\\u0300-\\uffff]/.test(v)) {\n const n = v.normalize('NFC')\n if (n !== v) over.set(r, n)\n }\n if (r % CHUNK === CHUNK - 1) yield\n }\n } catch {\n return undefined\n }\n const read: Read = (r) => {\n const v = get(r)\n return v === null || v === undefined ? '' : String(v)\n }\n return over.size ? (r) => over.get(r) ?? read(r) : read\n}\n\n/**\n * Builds the matcher over the formatted values of the searchable columns (what the user sees), once\n * per data + columns, as a time-sliced job (§9.1): one column read per slice. Searchable columns are\n * those with a `search` weight > 0. When no column declares `search`, the columns of primitives\n * (strings, numbers, booleans, nullable) are searchable at weight 1, and a column of dates, arrays\n * or other objects is not (#27: it would keep a formatted string per row; it opts in with a\n * weight; `DK_SEARCH_COLUMN_SKIPPED` in development). `null` when nothing is searchable. Nothing\n * is copied per row (§9.3 memory): a key column of primitives without `format` is read from the\n * rows and stringified while matching (no values array, #27); an accessor column of primitives\n * reads the column cache's values the same way; only a column with `format` or an opted-in object\n * column (dates, arrays) keeps its formatted strings in the column cache. A key column whose read\n * throws goes through the column cache too, which reports it. The case is folded per chunk while\n * matching.\n */\nexport function* buildIndex(\n ctx: RowModelContext,\n config: MatchConfig,\n useExSearch: boolean,\n): Generator<undefined, SearchIndex | null, undefined> {\n const cols = resolveColumns(ctx.columns)\n const declared = cols.list.some((c) => (c.def as { search?: unknown }).search !== undefined)\n const data = ctx.data\n const n = data.length\n const keys: Key[] = []\n const reads: Read[] = []\n for (const col of cols.list) {\n if (cols.byId.get(col.id) !== col) continue\n const w = (col.def as { search?: unknown }).search\n const weight = declared ? (typeof w === 'number' && w > 0 ? w : 0) : 1\n if (weight === 0) continue\n const path = col.format ? undefined : col.path\n let failed = false\n const onError = () => {\n failed = true\n }\n let read = path ? yield* scan(n, (r) => getValue(data[r], path, onError)) : undefined\n if (failed || (read === false && declared)) read = undefined\n if (read === undefined) {\n const values = ctx.getColumnValues(col.id)\n if (!values) continue\n yield // reading a column is a task of its own (#40)\n const numbers = values instanceof Float64Array\n if (numbers && !col.format) read = numberReader(values)\n else {\n // Zero-config: a column of objects is not searched, `format` or not (#27).\n const own =\n numbers || (declared && col.format) ? undefined : yield* scan(n, (r) => values[r])\n if (own === false && !declared) read = false\n else if (own && !col.format) read = own\n else {\n // Time-sliced in a table run (#40): dates or a heavy `format` are not one long task.\n const sliced = (ctx as RowModelContext & SlicedFormatting).formattedSliced\n const formatted = sliced ? yield* sliced(col.id) : ctx.getFormattedValues(col.id)\n if (!formatted) continue\n read = yield* scan(n, (r) => formatted[r])\n }\n }\n }\n if (!read) {\n if ((process.env.NODE_ENV !== \"production\") && read === false) {\n ctx.emit('DK_SEARCH_COLUMN_SKIPPED', { column: col.id, index: col.index })\n }\n continue\n }\n keys.push({ name: `c${keys.length}`, weight })\n reads.push(read)\n yield\n }\n if (keys.length === 0) return null\n const w = keys.map((k) => k.weight).join()\n /**\n * A 53-bit hash of row `r`'s searched texts (#95), cyrb53: two 32-bit lanes over the code units\n * plus one (1–65536), each text closed by a 0 (`charCodeAt` past the end is `NaN`, read as 0 by\n * `^`), so two different lists of texts hash different sequences; the lanes are mixed at the end.\n * A changed row is compared with at most two stored hashes: the chance that it keeps a stale\n * score (a collision) is at most 2·2⁻⁵³ ≈ 2.2·10⁻¹⁶ per changed row (accepted for #95).\n */\n const hash = (r: number) => {\n let a = 0xdeadbeef\n let b = 0x41c6ce57\n for (const read of reads) {\n const v = read(r)\n for (let j = 0; j <= v.length; j++) {\n const c = v.charCodeAt(j) + 1\n a = Math.imul(a ^ c, 2654435761)\n b = Math.imul(b ^ c, 1597334677)\n }\n }\n a = Math.imul(a ^ (a >>> 16), 2246822507) ^ Math.imul(b ^ (b >>> 13), 3266489909)\n b = Math.imul(b ^ (b >>> 16), 2246822507) ^ Math.imul(a ^ (a >>> 13), 3266489909)\n return 4294967296 * (2097151 & b) + (a >>> 0)\n }\n // Values (NFC already) are folded per chunk while matching; the query is normalised as well, so\n // NFC and NFD spellings match each other like in the `contains` filter (#30).\n const fold = (v: string) => (config.caseSensitive ? v : v.toLowerCase())\n const foldQuery = (q: string) => fold(q.normalize('NFC'))\n const at = (k: number, r: number) => fold((reads[k] as Read)(r))\n const matchChunk = (useExSearch ? exSearchIndex : containsIndex)(keys, at, config)\n /**\n * The hashes of this data version, computed on a row's first match (`-1`: not yet). The texts do\n * not depend on the query: a keystroke reuses them and hashes no row (#95).\n */\n const h = new Float64Array(n).fill(-1)\n return {\n *match(rows, query, memo) {\n const q = foldQuery(query)\n const prev = memo?.scores\n const old = prev?.q === query && prev.w === w ? prev : undefined\n const d = old ? old.h.length - n : 0\n // Same data (the scores hold this index's hashes), a narrowing query: a row the previous\n // match scored without a hit is not matched again; its hits and the rows it did not see\n // (`NaN`: filtered out then) are.\n const cut =\n !old && prev?.h === h && prev.w === w && matchChunk.narrows?.(foldQuery(prev.q), q)\n const s = new Float64Array(n).fill(Number.NaN)\n const size = Math.max(256, Math.floor(CELLS / keys.length))\n const hits: Hit[] = []\n for (let k = 0; k < rows.length; k += size) {\n if (k) yield\n const chunk = rows.subarray(k, k + size)\n const miss: number[] = []\n for (const r of chunk) {\n let x = h[r] as number\n if (x < 0) {\n x = hash(r)\n h[r] = x\n }\n s[r] = -1\n if (cut) {\n if ((prev.s[r] as number) !== -1) miss.push(r)\n continue\n }\n if (!old) continue\n // Out of range reads `undefined`: never equal, never `>= -1` (like `NaN`: not matched).\n const j = old.h[r] === x ? r : old.h[r + d] === x ? r + d : -1\n const v = old.s[j] as number\n if (v >= -1) {\n s[r] = v\n if (v >= 0) hits.push({ i: r, score: v })\n } else miss.push(r)\n }\n // A new query (no scores to keep) matches the chunk as it is.\n const todo = old || cut ? Uint32Array.from(miss) : chunk\n if (todo.length) {\n for (const hit of matchChunk(todo, q)) {\n s[hit.i] = hit.score\n hits.push(hit)\n }\n }\n }\n if (memo) memo.scores = { q: query, w, h, s }\n return rankHits(hits)\n },\n }\n}\n\n/**\n * The projection as ex-search reads it: an array (`length`, index reads) of `{ i, c0, … }` items,\n * each built when read and not kept. It shows the chunk of rows being matched; ex-search holds\n * this one view (`setData` once).\n */\nfunction projection(keys: readonly Key[], at: (k: number, r: number) => string) {\n let rows: Uint32Array = new Uint32Array(0)\n /** The items built for the chunk shown (ex-search 1.2.1 reads a row to split it, then to score it). */\n let held: Record<string, string | number>[] = []\n // Never written, and its own `length` stays 0: `length` is read through the trap below (setting\n // a large `length` would allocate a backing store).\n const target: Item[] = []\n const items = new Proxy(target, {\n get(t, p) {\n if (p === 'length') return rows.length\n const j = arrayIndex(p, rows.length)\n if (j < 0) return t[p as keyof Item[]]\n if (held[j]) return held[j]\n const r = rows[j] as number\n const o = { i: r } as Record<string, string | number>\n for (let k = 0; k < keys.length; k++) o[(keys[k] as Key).name] = at(k, r)\n held[j] = o\n return o\n },\n has: (t, p) => arrayIndex(p, rows.length) >= 0 || p in t,\n })\n return {\n items,\n /** Shows `chunk` (row indices), each item built once until the next `show`. */\n show(chunk: Uint32Array) {\n rows = chunk\n held = []\n },\n }\n}\n\n/** The hits of one chunk of rows for a folded query (`score` decides alone, so chunks match like the whole). */\ntype MatchChunk = ((chunk: Uint32Array, query: string) => Hit[]) & {\n /**\n * #96 (c): matching `next` within the hits of `prev` (both folded, as ex-search scores them)\n * provably equals matching every row. Missing (or `undefined`): never.\n */\n narrows?: (prev: string, next: string) => boolean | undefined\n}\n\nfunction exSearchIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n config: MatchConfig,\n): MatchChunk {\n // Values and query are folded already (buildIndex).\n const engine = new ExSearch<Item>({\n keys: keys as Key[],\n ...config,\n caseSensitive: true,\n // DataKable re-ranks with exact scores and an index tie-break; tim keeps ex-search's own pass\n // stable and avoids radix's score quantisation.\n sortAlgorithm: 'tim',\n })\n // A one-word query is measured against the whole value and each of its words, the best wins: a\n // typo of one word of a multi-word cell matches (#10). ex-search's `fuzzyMode: 'word'` does it\n // with its bounded matcher (#106). A query with whitespace is measured against whole values only,\n // as before (a single word is never that query), and is decided once per query, not per row (#96).\n // ex-search 1.2.1 splits a value into words once per `setData` and keeps the word offsets (its\n // word index, 16 bytes per cell of two words). Kept for every row, it would take DataKable over\n // its 5 MB budget at 100k rows (§9.3, #96), so it is built for each chunk the view shows and\n // dropped after it (`updateConfig`): values are split per chunk, each row read once.\n // With `fuzzyMaxDistance: 0` no word can score (distance 0 is equality, which the exact and\n // contains tiers score already): values are not split at all, same results (#96).\n const view = projection(keys, at)\n engine.setData(view.items)\n const match = (chunk: Uint32Array, q: string) => {\n // Set per chunk, like the view: another job may have matched in between.\n engine.updateConfig({ fuzzyMode: !config.fuzzyMaxDistance || /\\s/.test(q) ? 'value' : 'word' })\n view.show(chunk)\n // Results are copies of the items (`Omit<Item, …>` drops `i` from the type, not the value).\n const hits = engine.search(q) as unknown as Hit[]\n engine.updateConfig({})\n // The same rows again: drops the items built for them.\n view.show(chunk)\n return hits\n }\n // ex-search's `canNarrow` (1.2.1; 1.2.0 never narrows): fuzzy matching off, `prev` inside `next`\n // and no weight that lets a row reach `threshold` on `next` but not on `prev`; or the same query.\n // Queries are compared as given: DataKable's own (trimmed, NFC, folded).\n match.narrows = (prev: string, next: string) => engine.canNarrow?.(prev, next)\n return match\n}\n\n/** The fallback when ex-search is missing or incompatible: exact 1 · prefix 0.8 · substring 0.65. */\nfunction containsIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n config: MatchConfig,\n): MatchChunk {\n return (chunk, q) => {\n const hits: Hit[] = []\n for (let j = 0; j < chunk.length; j++) {\n const r = chunk[j] as number\n let best = 0\n for (let k = 0; k < keys.length; k++) {\n const v = at(k, r)\n const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0\n const w = (keys[k] as Key).weight\n if (raw * w > best) best = raw * w\n }\n if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best })\n }\n return hits\n }\n}\n\n/**\n * Hits in relevance order (§6.3): score descending, ties by original row index. Enforced here so\n * the order never depends on the matcher's own ranking. Sorts `hits` (a fresh array) in place.\n */\nexport function rankHits(hits: Hit[]): Uint32Array {\n return Uint32Array.from(\n hits.sort((a, b) => b.score - a.score || a.i - b.i),\n (h) => h.i,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAyB;AACzB,uBAAyB;AACzB,2BAAO;AAGP,0BA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AAO;AAAA,EACT;AACF;AAMO,SAAS,SAAS,MAA0B;AACjD,SAAO,YAAY;AAAA,IACjB,KAAK,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAAA,IAClD,CAAC,MAAM,EAAE;AAAA,EACX;AACF;","names":["w"]}
@@ -61,8 +61,8 @@ function* buildIndex(ctx, config, useExSearch) {
61
61
  const reads = [];
62
62
  for (const col of cols.list) {
63
63
  if (cols.byId.get(col.id) !== col) continue;
64
- const w = col.def.search;
65
- const weight = declared ? typeof w === "number" && w > 0 ? w : 0 : 1;
64
+ const w2 = col.def.search;
65
+ const weight = declared ? typeof w2 === "number" && w2 > 0 ? w2 : 0 : 1;
66
66
  if (weight === 0) continue;
67
67
  const path = col.format ? void 0 : col.path;
68
68
  let failed = false;
@@ -100,45 +100,101 @@ function* buildIndex(ctx, config, useExSearch) {
100
100
  yield;
101
101
  }
102
102
  if (keys.length === 0) return null;
103
+ const w = keys.map((k) => k.weight).join();
104
+ const hash = (r) => {
105
+ let a = 3735928559;
106
+ let b = 1103547991;
107
+ for (const read of reads) {
108
+ const v = read(r);
109
+ for (let j = 0; j <= v.length; j++) {
110
+ const c = v.charCodeAt(j) + 1;
111
+ a = Math.imul(a ^ c, 2654435761);
112
+ b = Math.imul(b ^ c, 1597334677);
113
+ }
114
+ }
115
+ a = Math.imul(a ^ a >>> 16, 2246822507) ^ Math.imul(b ^ b >>> 13, 3266489909);
116
+ b = Math.imul(b ^ b >>> 16, 2246822507) ^ Math.imul(a ^ a >>> 13, 3266489909);
117
+ return 4294967296 * (2097151 & b) + (a >>> 0);
118
+ };
103
119
  const fold = (v) => config.caseSensitive ? v : v.toLowerCase();
104
120
  const foldQuery = (q) => fold(q.normalize("NFC"));
105
121
  const at = (k, r) => fold(reads[k](r));
106
- return useExSearch ? exSearchIndex(keys, at, foldQuery, config) : containsIndex(keys, at, foldQuery, config);
107
- }
108
- function* chunked(rows, columns, matchChunk) {
109
- const size = Math.max(256, Math.floor(CELLS / columns));
110
- if (rows.length <= size) return rankHits(matchChunk(rows));
111
- const hits = [];
112
- for (let k = 0; k < rows.length; k += size) {
113
- for (const h of matchChunk(rows.subarray(k, k + size))) hits.push(h);
114
- yield;
115
- }
116
- return rankHits(hits);
122
+ const matchChunk = (useExSearch ? exSearchIndex : containsIndex)(keys, at, config);
123
+ const h = new Float64Array(n).fill(-1);
124
+ return {
125
+ *match(rows, query, memo) {
126
+ const q = foldQuery(query);
127
+ const prev = memo?.scores;
128
+ const old = prev?.q === query && prev.w === w ? prev : void 0;
129
+ const d = old ? old.h.length - n : 0;
130
+ const cut = !old && prev?.h === h && prev.w === w && matchChunk.narrows?.(foldQuery(prev.q), q);
131
+ const s = new Float64Array(n).fill(Number.NaN);
132
+ const size = Math.max(256, Math.floor(CELLS / keys.length));
133
+ const hits = [];
134
+ for (let k = 0; k < rows.length; k += size) {
135
+ if (k) yield;
136
+ const chunk = rows.subarray(k, k + size);
137
+ const miss = [];
138
+ for (const r of chunk) {
139
+ let x = h[r];
140
+ if (x < 0) {
141
+ x = hash(r);
142
+ h[r] = x;
143
+ }
144
+ s[r] = -1;
145
+ if (cut) {
146
+ if (prev.s[r] !== -1) miss.push(r);
147
+ continue;
148
+ }
149
+ if (!old) continue;
150
+ const j = old.h[r] === x ? r : old.h[r + d] === x ? r + d : -1;
151
+ const v = old.s[j];
152
+ if (v >= -1) {
153
+ s[r] = v;
154
+ if (v >= 0) hits.push({ i: r, score: v });
155
+ } else miss.push(r);
156
+ }
157
+ const todo = old || cut ? Uint32Array.from(miss) : chunk;
158
+ if (todo.length) {
159
+ for (const hit of matchChunk(todo, q)) {
160
+ s[hit.i] = hit.score;
161
+ hits.push(hit);
162
+ }
163
+ }
164
+ }
165
+ if (memo) memo.scores = { q: query, w, h, s };
166
+ return rankHits(hits);
167
+ }
168
+ };
117
169
  }
118
170
  function projection(keys, at) {
119
171
  let rows = new Uint32Array(0);
172
+ let held = [];
120
173
  const target = [];
121
174
  const items = new Proxy(target, {
122
175
  get(t, p) {
123
176
  if (p === "length") return rows.length;
124
177
  const j = arrayIndex(p, rows.length);
125
178
  if (j < 0) return t[p];
179
+ if (held[j]) return held[j];
126
180
  const r = rows[j];
127
181
  const o = { i: r };
128
182
  for (let k = 0; k < keys.length; k++) o[keys[k].name] = at(k, r);
183
+ held[j] = o;
129
184
  return o;
130
185
  },
131
186
  has: (t, p) => arrayIndex(p, rows.length) >= 0 || p in t
132
187
  });
133
188
  return {
134
189
  items,
135
- /** Shows `chunk` (row indices). */
190
+ /** Shows `chunk` (row indices), each item built once until the next `show`. */
136
191
  show(chunk) {
137
192
  rows = chunk;
193
+ held = [];
138
194
  }
139
195
  };
140
196
  }
141
- function exSearchIndex(keys, at, fold, config) {
197
+ function exSearchIndex(keys, at, config) {
142
198
  const engine = new ExSearch({
143
199
  keys,
144
200
  ...config,
@@ -149,40 +205,32 @@ function exSearchIndex(keys, at, fold, config) {
149
205
  });
150
206
  const view = projection(keys, at);
151
207
  engine.setData(view.items);
152
- return {
153
- match(rows, query) {
154
- const q = fold(query);
155
- const fuzzyMode = /\s/.test(q) ? "value" : "word";
156
- return chunked(rows, keys.length, (chunk) => {
157
- engine.updateConfig({ fuzzyMode });
158
- view.show(chunk);
159
- const hits = engine.search(q);
160
- engine.updateConfig({});
161
- return hits;
162
- });
163
- }
208
+ const match = (chunk, q) => {
209
+ engine.updateConfig({ fuzzyMode: !config.fuzzyMaxDistance || /\s/.test(q) ? "value" : "word" });
210
+ view.show(chunk);
211
+ const hits = engine.search(q);
212
+ engine.updateConfig({});
213
+ view.show(chunk);
214
+ return hits;
164
215
  };
216
+ match.narrows = (prev, next) => engine.canNarrow?.(prev, next);
217
+ return match;
165
218
  }
166
- function containsIndex(keys, at, fold, config) {
167
- return {
168
- match(rows, query) {
169
- const q = fold(query);
170
- return chunked(rows, keys.length, (chunk) => {
171
- const hits = [];
172
- for (let j = 0; j < chunk.length; j++) {
173
- const r = chunk[j];
174
- let best = 0;
175
- for (let k = 0; k < keys.length; k++) {
176
- const v = at(k, r);
177
- const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0;
178
- const w = keys[k].weight;
179
- if (raw * w > best) best = raw * w;
180
- }
181
- if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best });
182
- }
183
- return hits;
184
- });
219
+ function containsIndex(keys, at, config) {
220
+ return (chunk, q) => {
221
+ const hits = [];
222
+ for (let j = 0; j < chunk.length; j++) {
223
+ const r = chunk[j];
224
+ let best = 0;
225
+ for (let k = 0; k < keys.length; k++) {
226
+ const v = at(k, r);
227
+ const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0;
228
+ const w = keys[k].weight;
229
+ if (raw * w > best) best = raw * w;
230
+ }
231
+ if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best });
185
232
  }
233
+ return hits;
186
234
  };
187
235
  }
188
236
  function rankHits(hits) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/features/search/search-index.ts"],"sourcesContent":["import { ExSearch } from 'ex-search'\nimport { getValue } from '../../column/get-value'\nimport '../../diagnostics/process-guard'\nimport type { Emit } from '../../diagnostics/types'\nimport type { RowModelContext } from '../../feature/types'\nimport { nullishOf, type SlicedFormatting } from '../../pipeline/column-cache'\nimport { resolveColumns } from '../../pipeline/columns'\nimport { arrayIndex } from '../../pipeline/row'\nimport { detectCapability, hasCapability } from '../../versioning/capability'\n\n/** Matcher settings (the client options of `search()`, defaults applied). */\nexport interface MatchConfig {\n readonly threshold: number\n readonly fuzzyMaxDistance: number\n readonly caseSensitive: boolean\n}\n\n/**\n * One projected row as ex-search reads it: `i` is the row index (results map back by it, never by\n * identity: ex-search returns copies), `c0`, `c1`, … the formatted values of the searchable\n * columns. Flat keys also sidestep ex-search's top-level-key limitation for nested paths. Items\n * are built per chunk while matching and dropped after it (§9.3 memory): none is kept.\n */\nexport type Item = Record<string, string | number> & { readonly i: number }\n\n/** A match: the row index and its relevance (0–1, weight applied). */\nexport interface Hit {\n readonly i: number\n readonly score: number\n}\n\n/** The matcher of one (data, columns) pair: references to column values, no per-row copy. */\nexport interface SearchIndex {\n /**\n * A time-sliced job (§9.1) matching `query` (trimmed, non-blank) against the rows `rows` (row\n * indices), in chunks: the hits in relevance order ({@link rankHits}).\n */\n match(rows: Uint32Array, query: string): Generator<undefined, Uint32Array, undefined>\n}\n\n/** Rows per chunk between two `yield`s of a scan (one value per row). */\nconst CHUNK = 4096\n\n/**\n * Cells (rows × searchable columns) matched per chunk between two `yield`s (#40): a table with\n * many searchable columns matches fewer rows per chunk, so a chunk stays a few milliseconds.\n */\nconst CELLS = 16_384\n\ninterface Key {\n readonly name: string\n readonly weight: number\n}\n\n/** The formatted value of row `r` of one searchable column. */\ntype Read = (r: number) => string\n\n// A throw (no `ExSearch`) counts as missing (hasCapability).\nconst hasExSearch = () =>\n [ExSearch.prototype.search, ExSearch.prototype.setData, ExSearch.prototype.updateConfig].every(\n (f) => typeof f === 'function',\n )\n\n/** Feature-detects ex-search once (§8.5); `false` → the contains fallback. */\nexport function probeExSearch(emit: Emit): boolean {\n // DK_DEP_INCOMPATIBLE is a development check (§8.5); the fallback is not.\n return (process.env.NODE_ENV !== \"production\")\n ? detectCapability(\n hasExSearch,\n {\n feature: 'search',\n dependency: 'ex-search',\n capability: \"ExSearch (fuzzyMode: 'word')\",\n supported: '^1.2.0',\n fallback: 'case-insensitive exact / prefix / substring matching (no fuzzy matching)',\n },\n emit,\n )\n : hasCapability(hasExSearch)\n}\n\n/**\n * A numeric column's formatted value without cached strings (#27): what the default formatter\n * shows, `String(v)`, or `''` for a `null` / `undefined` cell (stored as `NaN`, like a real `NaN`,\n * which shows `'NaN'`).\n */\nfunction numberReader(values: Float64Array): Read {\n const nullish = nullishOf(values)\n return (r) => {\n const v = values[r] as number\n return !Number.isNaN(v) ? String(v) : nullish?.[r] ? '' : 'NaN'\n }\n}\n\n/**\n * One pass over a column's values (`get(r)` per row, time-sliced by `CHUNK` rows): their text as\n * the default formatter shows a primitive (`String(v)`, `''` when nullish), read while matching\n * (#27: no formatted copy per row). `false` at the first object or function (a `Date`, an array):\n * the column cache formats those. `undefined` when a read throws. The values are read in NFC (#30),\n * normalised here, never per keystroke: the rows whose value is not NFC (rare: NFD input from\n * macOS, Thai or Vietnamese keyboards) keep their NFC form in a sparse map. Only values with a code\n * unit from U+0300 (combining marks and up) can change.\n */\nfunction* scan(\n size: number,\n get: (r: number) => unknown,\n): Generator<undefined, Read | false | undefined, undefined> {\n const over = new Map<number, string>()\n try {\n for (let r = 0; r < size; r++) {\n const v = get(r)\n if (v !== null && (typeof v === 'object' || typeof v === 'function')) return false\n if (typeof v === 'string' && /[\\u0300-\\uffff]/.test(v)) {\n const n = v.normalize('NFC')\n if (n !== v) over.set(r, n)\n }\n if (r % CHUNK === CHUNK - 1) yield\n }\n } catch {\n return undefined\n }\n const read: Read = (r) => {\n const v = get(r)\n return v === null || v === undefined ? '' : String(v)\n }\n return over.size ? (r) => over.get(r) ?? read(r) : read\n}\n\n/**\n * Builds the matcher over the formatted values of the searchable columns (what the user sees), once\n * per data + columns, as a time-sliced job (§9.1): one column read per slice. Searchable columns are\n * those with a `search` weight > 0. When no column declares `search`, the columns of primitives\n * (strings, numbers, booleans, nullable) are searchable at weight 1, and a column of dates, arrays\n * or other objects is not (#27: it would keep a formatted string per row; it opts in with a\n * weight; `DK_SEARCH_COLUMN_SKIPPED` in development). `null` when nothing is searchable. Nothing\n * is copied per row (§9.3 memory): a key column of primitives without `format` is read from the\n * rows and stringified while matching (no values array, #27); an accessor column of primitives\n * reads the column cache's values the same way; only a column with `format` or an opted-in object\n * column (dates, arrays) keeps its formatted strings in the column cache. A key column whose read\n * throws goes through the column cache too, which reports it. The case is folded per chunk while\n * matching.\n */\nexport function* buildIndex(\n ctx: RowModelContext,\n config: MatchConfig,\n useExSearch: boolean,\n): Generator<undefined, SearchIndex | null, undefined> {\n const cols = resolveColumns(ctx.columns)\n const declared = cols.list.some((c) => (c.def as { search?: unknown }).search !== undefined)\n const data = ctx.data\n const n = data.length\n const keys: Key[] = []\n const reads: Read[] = []\n for (const col of cols.list) {\n if (cols.byId.get(col.id) !== col) continue\n const w = (col.def as { search?: unknown }).search\n const weight = declared ? (typeof w === 'number' && w > 0 ? w : 0) : 1\n if (weight === 0) continue\n const path = col.format ? undefined : col.path\n let failed = false\n const onError = () => {\n failed = true\n }\n let read = path ? yield* scan(n, (r) => getValue(data[r], path, onError)) : undefined\n if (failed || (read === false && declared)) read = undefined\n if (read === undefined) {\n const values = ctx.getColumnValues(col.id)\n if (!values) continue\n yield // reading a column is a task of its own (#40)\n const numbers = values instanceof Float64Array\n if (numbers && !col.format) read = numberReader(values)\n else {\n // Zero-config: a column of objects is not searched, `format` or not (#27).\n const own =\n numbers || (declared && col.format) ? undefined : yield* scan(n, (r) => values[r])\n if (own === false && !declared) read = false\n else if (own && !col.format) read = own\n else {\n // Time-sliced in a table run (#40): dates or a heavy `format` are not one long task.\n const sliced = (ctx as RowModelContext & SlicedFormatting).formattedSliced\n const formatted = sliced ? yield* sliced(col.id) : ctx.getFormattedValues(col.id)\n if (!formatted) continue\n read = yield* scan(n, (r) => formatted[r])\n }\n }\n }\n if (!read) {\n if ((process.env.NODE_ENV !== \"production\") && read === false) {\n ctx.emit('DK_SEARCH_COLUMN_SKIPPED', { column: col.id, index: col.index })\n }\n continue\n }\n keys.push({ name: `c${keys.length}`, weight })\n reads.push(read)\n yield\n }\n if (keys.length === 0) return null\n // Values (NFC already) are folded per chunk while matching; the query is normalised as well, so\n // NFC and NFD spellings match each other like in the `contains` filter (#30).\n const fold = (v: string) => (config.caseSensitive ? v : v.toLowerCase())\n const foldQuery = (q: string) => fold(q.normalize('NFC'))\n const at = (k: number, r: number) => fold((reads[k] as Read)(r))\n return useExSearch\n ? exSearchIndex(keys, at, foldQuery, config)\n : containsIndex(keys, at, foldQuery, config)\n}\n\n/** Matches `rows` chunk by chunk (`score` decides alone, so chunks match like the whole). */\nfunction* chunked(\n rows: Uint32Array,\n columns: number,\n matchChunk: (chunk: Uint32Array) => Hit[],\n): Generator<undefined, Uint32Array, undefined> {\n const size = Math.max(256, Math.floor(CELLS / columns))\n if (rows.length <= size) return rankHits(matchChunk(rows))\n const hits: Hit[] = []\n for (let k = 0; k < rows.length; k += size) {\n for (const h of matchChunk(rows.subarray(k, k + size))) hits.push(h)\n yield\n }\n return rankHits(hits)\n}\n\n/**\n * The projection as ex-search reads it: an array (`length`, index reads) of `{ i, c0, … }` items,\n * each built when read and not kept. It shows the chunk of rows being matched; ex-search holds\n * this one view (`setData` once).\n */\nfunction projection(keys: readonly Key[], at: (k: number, r: number) => string) {\n let rows: Uint32Array = new Uint32Array(0)\n // Never written, and its own `length` stays 0: `length` is read through the trap below (setting\n // a large `length` would allocate a backing store).\n const target: Item[] = []\n const items = new Proxy(target, {\n get(t, p) {\n if (p === 'length') return rows.length\n const j = arrayIndex(p, rows.length)\n if (j < 0) return t[p as keyof Item[]]\n const r = rows[j] as number\n const o = { i: r } as Record<string, string | number>\n for (let k = 0; k < keys.length; k++) o[(keys[k] as Key).name] = at(k, r)\n return o\n },\n has: (t, p) => arrayIndex(p, rows.length) >= 0 || p in t,\n })\n return {\n items,\n /** Shows `chunk` (row indices). */\n show(chunk: Uint32Array) {\n rows = chunk\n },\n }\n}\n\nfunction exSearchIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n fold: (v: string) => string,\n config: MatchConfig,\n): SearchIndex {\n // Values and query are folded already (buildIndex).\n const engine = new ExSearch<Item>({\n keys: keys as Key[],\n ...config,\n caseSensitive: true,\n // DataKable re-ranks with exact scores and an index tie-break; tim keeps ex-search's own pass\n // stable and avoids radix's score quantisation.\n sortAlgorithm: 'tim',\n })\n // A one-word query is measured against the whole value and each of its words, the best wins: a\n // typo of one word of a multi-word cell matches (#10). ex-search's `fuzzyMode: 'word'` does it\n // with its bounded matcher (#106). A query with whitespace is measured against whole values only,\n // as before (a single word is never that query), and is decided once per query, not per row (#96).\n // ex-search caches the words per position of its data: the view shows another chunk each time,\n // and a cache kept over every row would hold a word list per row and column (tens of MB at 100k\n // rows, §9.3), so it is dropped after each chunk (`updateConfig`) and values are split per chunk.\n const view = projection(keys, at)\n engine.setData(view.items)\n return {\n match(rows, query) {\n const q = fold(query)\n const fuzzyMode = /\\s/.test(q) ? 'value' : 'word'\n return chunked(rows, keys.length, (chunk) => {\n // Set per chunk, like the view: another job may have matched in between.\n engine.updateConfig({ fuzzyMode })\n view.show(chunk)\n // Results are copies of the items (`Omit<Item, …>` drops `i` from the type, not the value).\n const hits = engine.search(q) as unknown as Hit[]\n engine.updateConfig({})\n return hits\n })\n },\n }\n}\n\n/** The fallback when ex-search is missing or incompatible: exact 1 · prefix 0.8 · substring 0.65. */\nfunction containsIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n fold: (v: string) => string,\n config: MatchConfig,\n): SearchIndex {\n return {\n match(rows, query) {\n const q = fold(query)\n return chunked(rows, keys.length, (chunk) => {\n const hits: Hit[] = []\n for (let j = 0; j < chunk.length; j++) {\n const r = chunk[j] as number\n let best = 0\n for (let k = 0; k < keys.length; k++) {\n const v = at(k, r)\n const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0\n const w = (keys[k] as Key).weight\n if (raw * w > best) best = raw * w\n }\n if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best })\n }\n return hits\n })\n },\n }\n}\n\n/**\n * Hits in relevance order (§6.3): score descending, ties by original row index. Enforced here so\n * the order never depends on the matcher's own ranking. Sorts `hits` (a fresh array) in place.\n */\nexport function rankHits(hits: Hit[]): Uint32Array {\n return Uint32Array.from(\n hits.sort((a, b) => b.score - a.score || a.i - b.i),\n (h) => h.i,\n )\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,OAAO;AAGP,SAAS,iBAAwC;AACjD,SAAS,sBAAsB;AAC/B,SAAS,kBAAkB;AAC3B,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O;AACjB,YAAM,IAAI,KAAK,KAAK;AACpB,aAAO,QAAQ,MAAM,KAAK,QAAQ,CAAC,UAAU;AAC3C,cAAM,OAAc,CAAC;AACrB,iBAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,gBAAM,IAAI,MAAM,CAAC;AACjB,cAAI,OAAO;AACX,mBAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,kBAAM,IAAI,GAAG,GAAG,CAAC;AACjB,kBAAM,MAAM,MAAM,IAAI,IAAI,EAAE,WAAW,CAAC,IAAI,MAAM,EAAE,SAAS,CAAC,IAAI,OAAO;AACzE,kBAAM,IAAK,KAAK,CAAC,EAAU;AAC3B,gBAAI,MAAM,IAAI,KAAM,QAAO,MAAM;AAAA,UACnC;AACA,cAAI,OAAO,KAAK,QAAQ,OAAO,UAAW,MAAK,KAAK,EAAE,GAAG,GAAG,OAAO,KAAK,CAAC;AAAA,QAC3E;AACA,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAMO,SAAS,SAAS,MAA0B;AACjD,SAAO,YAAY;AAAA,IACjB,KAAK,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAAA,IAClD,CAAC,MAAM,EAAE;AAAA,EACX;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/features/search/search-index.ts"],"sourcesContent":["import { ExSearch } from 'ex-search'\nimport { getValue } from '../../column/get-value'\nimport '../../diagnostics/process-guard'\nimport type { Emit } from '../../diagnostics/types'\nimport type { RowModelContext } from '../../feature/types'\nimport { nullishOf, type SlicedFormatting } from '../../pipeline/column-cache'\nimport { resolveColumns } from '../../pipeline/columns'\nimport { arrayIndex } from '../../pipeline/row'\nimport { detectCapability, hasCapability } from '../../versioning/capability'\n\n/** Matcher settings (the client options of `search()`, defaults applied). */\nexport interface MatchConfig {\n readonly threshold: number\n readonly fuzzyMaxDistance: number\n readonly caseSensitive: boolean\n}\n\n/**\n * One projected row as ex-search reads it: `i` is the row index (results map back by it, never by\n * identity: ex-search returns copies), `c0`, `c1`, … the formatted values of the searchable\n * columns. Flat keys also sidestep ex-search's top-level-key limitation for nested paths. Items\n * are built per chunk while matching and dropped after it (§9.3 memory): none is kept.\n */\nexport type Item = Record<string, string | number> & { readonly i: number }\n\n/** A match: the row index and its relevance (0–1, weight applied). */\nexport interface Hit {\n readonly i: number\n readonly score: number\n}\n\n/**\n * The scores of the last match of a table (#95), per data row: `h` the 53-bit hashes of the rows'\n * searched texts (the index's, `-1`: not hashed), `s` its score (`-1`: no hit, `NaN`: not matched).\n * 16 bytes per row.\n */\nexport interface Scores {\n /** The query. */\n readonly q: string\n /** The weights of the searched columns, in key order. */\n readonly w: string\n readonly h: Float64Array\n readonly s: Float64Array\n}\n\n/** The matcher of one (data, columns) pair: references to column values, no per-row copy. */\nexport interface SearchIndex {\n /**\n * A time-sliced job (§9.1) matching `query` (trimmed, non-blank) against the rows `rows` (row\n * indices), in chunks: the hits in relevance order ({@link rankHits}). With `memo`, a row whose\n * searched texts hash like the same row of `memo.scores` (same position, or shifted by the\n * change in length: an insert or a delete) keeps its score and is not matched again (#95). On\n * the same data, a query that provably keeps no row the previous one dropped matches only the\n * previous hits (#96). `memo.scores` is then replaced by this match's.\n */\n match(\n rows: Uint32Array,\n query: string,\n memo?: { scores?: Scores },\n ): Generator<undefined, Uint32Array, undefined>\n}\n\n/** Rows per chunk between two `yield`s of a scan (one value per row). */\nconst CHUNK = 4096\n\n/**\n * Cells (rows × searchable columns) matched per chunk between two `yield`s (#40): a table with\n * many searchable columns matches fewer rows per chunk, so a chunk stays a few milliseconds.\n */\nconst CELLS = 16_384\n\ninterface Key {\n readonly name: string\n readonly weight: number\n}\n\n/** The formatted value of row `r` of one searchable column. */\ntype Read = (r: number) => string\n\n// A throw (no `ExSearch`) counts as missing (hasCapability).\nconst hasExSearch = () =>\n [ExSearch.prototype.search, ExSearch.prototype.setData, ExSearch.prototype.updateConfig].every(\n (f) => typeof f === 'function',\n )\n\n/** Feature-detects ex-search once (§8.5); `false` → the contains fallback. */\nexport function probeExSearch(emit: Emit): boolean {\n // DK_DEP_INCOMPATIBLE is a development check (§8.5); the fallback is not.\n return (process.env.NODE_ENV !== \"production\")\n ? detectCapability(\n hasExSearch,\n {\n feature: 'search',\n dependency: 'ex-search',\n capability: \"ExSearch (fuzzyMode: 'word')\",\n supported: '^1.2.0',\n fallback: 'case-insensitive exact / prefix / substring matching (no fuzzy matching)',\n },\n emit,\n )\n : hasCapability(hasExSearch)\n}\n\n/**\n * A numeric column's formatted value without cached strings (#27): what the default formatter\n * shows, `String(v)`, or `''` for a `null` / `undefined` cell (stored as `NaN`, like a real `NaN`,\n * which shows `'NaN'`).\n */\nfunction numberReader(values: Float64Array): Read {\n const nullish = nullishOf(values)\n return (r) => {\n const v = values[r] as number\n return !Number.isNaN(v) ? String(v) : nullish?.[r] ? '' : 'NaN'\n }\n}\n\n/**\n * One pass over a column's values (`get(r)` per row, time-sliced by `CHUNK` rows): their text as\n * the default formatter shows a primitive (`String(v)`, `''` when nullish), read while matching\n * (#27: no formatted copy per row). `false` at the first object or function (a `Date`, an array):\n * the column cache formats those. `undefined` when a read throws. The values are read in NFC (#30),\n * normalised here, never per keystroke: the rows whose value is not NFC (rare: NFD input from\n * macOS, Thai or Vietnamese keyboards) keep their NFC form in a sparse map. Only values with a code\n * unit from U+0300 (combining marks and up) can change.\n */\nfunction* scan(\n size: number,\n get: (r: number) => unknown,\n): Generator<undefined, Read | false | undefined, undefined> {\n const over = new Map<number, string>()\n try {\n for (let r = 0; r < size; r++) {\n const v = get(r)\n if (v !== null && (typeof v === 'object' || typeof v === 'function')) return false\n if (typeof v === 'string' && /[\\u0300-\\uffff]/.test(v)) {\n const n = v.normalize('NFC')\n if (n !== v) over.set(r, n)\n }\n if (r % CHUNK === CHUNK - 1) yield\n }\n } catch {\n return undefined\n }\n const read: Read = (r) => {\n const v = get(r)\n return v === null || v === undefined ? '' : String(v)\n }\n return over.size ? (r) => over.get(r) ?? read(r) : read\n}\n\n/**\n * Builds the matcher over the formatted values of the searchable columns (what the user sees), once\n * per data + columns, as a time-sliced job (§9.1): one column read per slice. Searchable columns are\n * those with a `search` weight > 0. When no column declares `search`, the columns of primitives\n * (strings, numbers, booleans, nullable) are searchable at weight 1, and a column of dates, arrays\n * or other objects is not (#27: it would keep a formatted string per row; it opts in with a\n * weight; `DK_SEARCH_COLUMN_SKIPPED` in development). `null` when nothing is searchable. Nothing\n * is copied per row (§9.3 memory): a key column of primitives without `format` is read from the\n * rows and stringified while matching (no values array, #27); an accessor column of primitives\n * reads the column cache's values the same way; only a column with `format` or an opted-in object\n * column (dates, arrays) keeps its formatted strings in the column cache. A key column whose read\n * throws goes through the column cache too, which reports it. The case is folded per chunk while\n * matching.\n */\nexport function* buildIndex(\n ctx: RowModelContext,\n config: MatchConfig,\n useExSearch: boolean,\n): Generator<undefined, SearchIndex | null, undefined> {\n const cols = resolveColumns(ctx.columns)\n const declared = cols.list.some((c) => (c.def as { search?: unknown }).search !== undefined)\n const data = ctx.data\n const n = data.length\n const keys: Key[] = []\n const reads: Read[] = []\n for (const col of cols.list) {\n if (cols.byId.get(col.id) !== col) continue\n const w = (col.def as { search?: unknown }).search\n const weight = declared ? (typeof w === 'number' && w > 0 ? w : 0) : 1\n if (weight === 0) continue\n const path = col.format ? undefined : col.path\n let failed = false\n const onError = () => {\n failed = true\n }\n let read = path ? yield* scan(n, (r) => getValue(data[r], path, onError)) : undefined\n if (failed || (read === false && declared)) read = undefined\n if (read === undefined) {\n const values = ctx.getColumnValues(col.id)\n if (!values) continue\n yield // reading a column is a task of its own (#40)\n const numbers = values instanceof Float64Array\n if (numbers && !col.format) read = numberReader(values)\n else {\n // Zero-config: a column of objects is not searched, `format` or not (#27).\n const own =\n numbers || (declared && col.format) ? undefined : yield* scan(n, (r) => values[r])\n if (own === false && !declared) read = false\n else if (own && !col.format) read = own\n else {\n // Time-sliced in a table run (#40): dates or a heavy `format` are not one long task.\n const sliced = (ctx as RowModelContext & SlicedFormatting).formattedSliced\n const formatted = sliced ? yield* sliced(col.id) : ctx.getFormattedValues(col.id)\n if (!formatted) continue\n read = yield* scan(n, (r) => formatted[r])\n }\n }\n }\n if (!read) {\n if ((process.env.NODE_ENV !== \"production\") && read === false) {\n ctx.emit('DK_SEARCH_COLUMN_SKIPPED', { column: col.id, index: col.index })\n }\n continue\n }\n keys.push({ name: `c${keys.length}`, weight })\n reads.push(read)\n yield\n }\n if (keys.length === 0) return null\n const w = keys.map((k) => k.weight).join()\n /**\n * A 53-bit hash of row `r`'s searched texts (#95), cyrb53: two 32-bit lanes over the code units\n * plus one (1–65536), each text closed by a 0 (`charCodeAt` past the end is `NaN`, read as 0 by\n * `^`), so two different lists of texts hash different sequences; the lanes are mixed at the end.\n * A changed row is compared with at most two stored hashes: the chance that it keeps a stale\n * score (a collision) is at most 2·2⁻⁵³ ≈ 2.2·10⁻¹⁶ per changed row (accepted for #95).\n */\n const hash = (r: number) => {\n let a = 0xdeadbeef\n let b = 0x41c6ce57\n for (const read of reads) {\n const v = read(r)\n for (let j = 0; j <= v.length; j++) {\n const c = v.charCodeAt(j) + 1\n a = Math.imul(a ^ c, 2654435761)\n b = Math.imul(b ^ c, 1597334677)\n }\n }\n a = Math.imul(a ^ (a >>> 16), 2246822507) ^ Math.imul(b ^ (b >>> 13), 3266489909)\n b = Math.imul(b ^ (b >>> 16), 2246822507) ^ Math.imul(a ^ (a >>> 13), 3266489909)\n return 4294967296 * (2097151 & b) + (a >>> 0)\n }\n // Values (NFC already) are folded per chunk while matching; the query is normalised as well, so\n // NFC and NFD spellings match each other like in the `contains` filter (#30).\n const fold = (v: string) => (config.caseSensitive ? v : v.toLowerCase())\n const foldQuery = (q: string) => fold(q.normalize('NFC'))\n const at = (k: number, r: number) => fold((reads[k] as Read)(r))\n const matchChunk = (useExSearch ? exSearchIndex : containsIndex)(keys, at, config)\n /**\n * The hashes of this data version, computed on a row's first match (`-1`: not yet). The texts do\n * not depend on the query: a keystroke reuses them and hashes no row (#95).\n */\n const h = new Float64Array(n).fill(-1)\n return {\n *match(rows, query, memo) {\n const q = foldQuery(query)\n const prev = memo?.scores\n const old = prev?.q === query && prev.w === w ? prev : undefined\n const d = old ? old.h.length - n : 0\n // Same data (the scores hold this index's hashes), a narrowing query: a row the previous\n // match scored without a hit is not matched again; its hits and the rows it did not see\n // (`NaN`: filtered out then) are.\n const cut =\n !old && prev?.h === h && prev.w === w && matchChunk.narrows?.(foldQuery(prev.q), q)\n const s = new Float64Array(n).fill(Number.NaN)\n const size = Math.max(256, Math.floor(CELLS / keys.length))\n const hits: Hit[] = []\n for (let k = 0; k < rows.length; k += size) {\n if (k) yield\n const chunk = rows.subarray(k, k + size)\n const miss: number[] = []\n for (const r of chunk) {\n let x = h[r] as number\n if (x < 0) {\n x = hash(r)\n h[r] = x\n }\n s[r] = -1\n if (cut) {\n if ((prev.s[r] as number) !== -1) miss.push(r)\n continue\n }\n if (!old) continue\n // Out of range reads `undefined`: never equal, never `>= -1` (like `NaN`: not matched).\n const j = old.h[r] === x ? r : old.h[r + d] === x ? r + d : -1\n const v = old.s[j] as number\n if (v >= -1) {\n s[r] = v\n if (v >= 0) hits.push({ i: r, score: v })\n } else miss.push(r)\n }\n // A new query (no scores to keep) matches the chunk as it is.\n const todo = old || cut ? Uint32Array.from(miss) : chunk\n if (todo.length) {\n for (const hit of matchChunk(todo, q)) {\n s[hit.i] = hit.score\n hits.push(hit)\n }\n }\n }\n if (memo) memo.scores = { q: query, w, h, s }\n return rankHits(hits)\n },\n }\n}\n\n/**\n * The projection as ex-search reads it: an array (`length`, index reads) of `{ i, c0, … }` items,\n * each built when read and not kept. It shows the chunk of rows being matched; ex-search holds\n * this one view (`setData` once).\n */\nfunction projection(keys: readonly Key[], at: (k: number, r: number) => string) {\n let rows: Uint32Array = new Uint32Array(0)\n /** The items built for the chunk shown (ex-search 1.2.1 reads a row to split it, then to score it). */\n let held: Record<string, string | number>[] = []\n // Never written, and its own `length` stays 0: `length` is read through the trap below (setting\n // a large `length` would allocate a backing store).\n const target: Item[] = []\n const items = new Proxy(target, {\n get(t, p) {\n if (p === 'length') return rows.length\n const j = arrayIndex(p, rows.length)\n if (j < 0) return t[p as keyof Item[]]\n if (held[j]) return held[j]\n const r = rows[j] as number\n const o = { i: r } as Record<string, string | number>\n for (let k = 0; k < keys.length; k++) o[(keys[k] as Key).name] = at(k, r)\n held[j] = o\n return o\n },\n has: (t, p) => arrayIndex(p, rows.length) >= 0 || p in t,\n })\n return {\n items,\n /** Shows `chunk` (row indices), each item built once until the next `show`. */\n show(chunk: Uint32Array) {\n rows = chunk\n held = []\n },\n }\n}\n\n/** The hits of one chunk of rows for a folded query (`score` decides alone, so chunks match like the whole). */\ntype MatchChunk = ((chunk: Uint32Array, query: string) => Hit[]) & {\n /**\n * #96 (c): matching `next` within the hits of `prev` (both folded, as ex-search scores them)\n * provably equals matching every row. Missing (or `undefined`): never.\n */\n narrows?: (prev: string, next: string) => boolean | undefined\n}\n\nfunction exSearchIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n config: MatchConfig,\n): MatchChunk {\n // Values and query are folded already (buildIndex).\n const engine = new ExSearch<Item>({\n keys: keys as Key[],\n ...config,\n caseSensitive: true,\n // DataKable re-ranks with exact scores and an index tie-break; tim keeps ex-search's own pass\n // stable and avoids radix's score quantisation.\n sortAlgorithm: 'tim',\n })\n // A one-word query is measured against the whole value and each of its words, the best wins: a\n // typo of one word of a multi-word cell matches (#10). ex-search's `fuzzyMode: 'word'` does it\n // with its bounded matcher (#106). A query with whitespace is measured against whole values only,\n // as before (a single word is never that query), and is decided once per query, not per row (#96).\n // ex-search 1.2.1 splits a value into words once per `setData` and keeps the word offsets (its\n // word index, 16 bytes per cell of two words). Kept for every row, it would take DataKable over\n // its 5 MB budget at 100k rows (§9.3, #96), so it is built for each chunk the view shows and\n // dropped after it (`updateConfig`): values are split per chunk, each row read once.\n // With `fuzzyMaxDistance: 0` no word can score (distance 0 is equality, which the exact and\n // contains tiers score already): values are not split at all, same results (#96).\n const view = projection(keys, at)\n engine.setData(view.items)\n const match = (chunk: Uint32Array, q: string) => {\n // Set per chunk, like the view: another job may have matched in between.\n engine.updateConfig({ fuzzyMode: !config.fuzzyMaxDistance || /\\s/.test(q) ? 'value' : 'word' })\n view.show(chunk)\n // Results are copies of the items (`Omit<Item, …>` drops `i` from the type, not the value).\n const hits = engine.search(q) as unknown as Hit[]\n engine.updateConfig({})\n // The same rows again: drops the items built for them.\n view.show(chunk)\n return hits\n }\n // ex-search's `canNarrow` (1.2.1; 1.2.0 never narrows): fuzzy matching off, `prev` inside `next`\n // and no weight that lets a row reach `threshold` on `next` but not on `prev`; or the same query.\n // Queries are compared as given: DataKable's own (trimmed, NFC, folded).\n match.narrows = (prev: string, next: string) => engine.canNarrow?.(prev, next)\n return match\n}\n\n/** The fallback when ex-search is missing or incompatible: exact 1 · prefix 0.8 · substring 0.65. */\nfunction containsIndex(\n keys: readonly Key[],\n at: (k: number, r: number) => string,\n config: MatchConfig,\n): MatchChunk {\n return (chunk, q) => {\n const hits: Hit[] = []\n for (let j = 0; j < chunk.length; j++) {\n const r = chunk[j] as number\n let best = 0\n for (let k = 0; k < keys.length; k++) {\n const v = at(k, r)\n const raw = v === q ? 1 : v.startsWith(q) ? 0.8 : v.includes(q) ? 0.65 : 0\n const w = (keys[k] as Key).weight\n if (raw * w > best) best = raw * w\n }\n if (best > 0 && best >= config.threshold) hits.push({ i: r, score: best })\n }\n return hits\n }\n}\n\n/**\n * Hits in relevance order (§6.3): score descending, ties by original row index. Enforced here so\n * the order never depends on the matcher's own ranking. Sorts `hits` (a fresh array) in place.\n */\nexport function rankHits(hits: Hit[]): Uint32Array {\n return Uint32Array.from(\n hits.sort((a, b) => b.score - a.score || a.i - b.i),\n (h) => h.i,\n )\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,OAAO;AAGP,SAAS,iBAAwC;AAC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AACA,WAAO;AAAA,EACT;AACF;AAMO,SAAS,SAAS,MAA0B;AACjD,SAAO,YAAY;AAAA,IACjB,KAAK,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAAA,IAClD,CAAC,MAAM,EAAE;AAAA,EACX;AACF;","names":["w"]}
@@ -105,6 +105,7 @@ var search = (opts = {}) => {
105
105
  let useExSearch;
106
106
  const reported = /* @__PURE__ */ new WeakSet();
107
107
  let last;
108
+ const memo = {};
108
109
  let matching2;
109
110
  let shown;
110
111
  const server = opts.mode === "server";
@@ -153,7 +154,7 @@ var search = (opts = {}) => {
153
154
  if (!matching2 || matching2.rows !== rows || matching2.index !== index || matching2.query !== query) {
154
155
  matching2 = { rows, index, query, key: {} };
155
156
  }
156
- return (0, import_slice.sliced)(ctx, matching2.key, () => index.match(rows, query));
157
+ return (0, import_slice.sliced)(ctx, matching2.key, () => index.match(rows, query, memo));
157
158
  }
158
159
  const standIn = (indices) => {
159
160
  waited = true;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/features/search/search.ts"],"sourcesContent":["import { debounce } from 'kk-debounce/debounce'\nimport { debouncedSignal } from 'kk-debounce/debounceSignal'\nimport { throttle } from 'kk-debounce/throttle'\nimport { optionDiagnostics } from '../../catalog/codes'\nimport { defineOptions } from '../../catalog/options'\nimport { throwConfigError } from '../../diagnostics/build'\nimport { keepDiagnostics } from '../../diagnostics/catalog'\nimport '../../diagnostics/process-guard'\nimport { defineFeature } from '../../feature/define'\nimport type { AnyRow, RowModelContext } from '../../feature/types'\nimport { defineInterceptor } from '../../intercept/define'\nimport { runJob, sliced } from '../../pipeline/slice'\nimport { type DataMode, modeOption } from '../../source/mode'\nimport {\n APPLIED,\n type AsyncSearchFn,\n SEARCH_ENGINE,\n type SearchEngine,\n type SearchOutcome,\n type SearchSession,\n type SearchState,\n type SearchStatus,\n SUPERSEDED,\n type Waiter,\n} from './search-fn-brand'\nimport { buildIndex, type MatchConfig, probeExSearch, type SearchIndex } from './search-index'\nimport { skippedColumnDiagnostics } from './skipped-codes'\n\nkeepDiagnostics(optionDiagnostics, skippedColumnDiagnostics)\n\nexport type {\n AsyncSearchFn,\n SearchFn,\n SearchFnContext,\n SearchOutcome,\n SearchResult,\n SearchState,\n SearchStatus,\n} from './search-fn-brand'\n\nexport interface SearchApi {\n /** Sets `input` (and `query`, with the client's immediate typing strategy). */\n setSearch(query: string): Promise<SearchOutcome>\n /** Applies the current `input` now (Enter). */\n flushSearch(): Promise<SearchOutcome>\n /** Drops a pending (debounced) query; `input` and the applied `query` stay. */\n cancelSearch(): void\n /** Empties `input` and `query`: every row is shown again. */\n clearSearch(): void\n}\n\n/** A duration: milliseconds, or a kk-debounce temporal object (`{ seconds: 1, ms: 500 }`). */\nexport type SearchWait =\n | number\n | { hours?: number; minutes?: number; seconds?: number; ms?: number }\n\n/** When `query` follows `input` (§6.3). */\nexport interface SearchTyping {\n /**\n * `'immediate'` (default): every keystroke is applied. `'debounce'`: applied after `wait` of\n * quiet (kk-debounce `debouncedSignal`). `'throttle'`: at most once per `wait` (the first\n * keystroke at once, the latest one at the end of the window).\n */\n strategy?: 'immediate' | 'debounce' | 'throttle'\n /** Default 300 ms. Used by `'debounce'` and `'throttle'`. */\n wait?: SearchWait\n /**\n * Debounce only. `'trailing'` (default): apply after the burst. `'leading'`: apply the first\n * keystroke at once and drop the rest of the burst (`flushSearch()` applies them; otherwise\n * their `setSearch()` promises resolve `'superseded'` when the silence window ends).\n */\n behavior?: 'trailing' | 'leading'\n /** A trimmed input shorter than this is applied as an empty query (all rows). Default 0. */\n minLength?: number\n /** `'type'` (default): typing commits. `'enter'`: only `flushSearch()` commits. */\n commitOn?: 'type' | 'enter'\n}\n\n/** Client matching options (§6.3). */\nexport interface SearchOptions<T = AnyRow> {\n /** Minimum relevance (0–1, weight applied) to keep a row. Default `0.3`. */\n threshold?: number\n /** Maximum Levenshtein distance for a fuzzy match. Default `3`. */\n fuzzyMaxDistance?: number\n /** Default `false`. */\n caseSensitive?: boolean\n /**\n * Typing timing: when `query` follows `input`. Default: immediate; with `mode: 'server'`,\n * debounce 300 ms and `minLength` 2 (§6.3).\n */\n typing?: SearchTyping\n /**\n * `'server'`: the server matches `query` (its state goes to `options.fetcher`, or the app\n * fetches); core skips this step (§7.1). Default `'client'`.\n */\n mode?: DataMode\n /**\n * Replaces the built-in matching (§6.3): called with each applied non-blank query; while it runs\n * `status` is `'searching'` and the previous results stay. A failure keeps them too\n * (`DK_SEARCH_FAILED`, `status: 'error'`); an `AbortError` is not a failure. New data runs it\n * again for the applied query. Wrap it with `withSearchFn()` from `@datakable/core/search-async`\n * (client search does not bundle the async engine): `searchFn: withSearchFn(fn)`.\n */\n searchFn?: AsyncSearchFn<T>\n}\n\nconst DEFAULT_WAIT = 300\n\nconst isDuration = (v: unknown): boolean => {\n if (typeof v === 'number') return Number.isFinite(v) && v >= 0\n for (const k of ['hours', 'minutes', 'seconds', 'ms'] as const) {\n const n = (v as Record<string, unknown>)[k]\n if (n !== undefined && !(typeof n === 'number' && Number.isFinite(n) && n >= 0)) return false\n }\n return true\n}\n\nconst typingOptions = {\n strategy: { type: 'string', oneOf: ['immediate', 'debounce', 'throttle'] },\n wait: {\n type: ['number', 'object'],\n check: isDuration,\n expected: 'milliseconds >= 0 or { hours?, minutes?, seconds?, ms? } with values >= 0',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce' && o.strategy !== 'throttle'\n ? \"only the 'debounce' and 'throttle' strategies wait\"\n : undefined,\n },\n behavior: {\n type: 'string',\n oneOf: ['trailing', 'leading'],\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce'\n ? \"behavior applies to the 'debounce' strategy only\"\n : undefined,\n },\n minLength: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n },\n commitOn: { type: 'string', oneOf: ['type', 'enter'] },\n} as const\n\n/** Built-in matching options do nothing when `searchFn` matches. */\nconst matching = (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.searchFn === undefined ? undefined : 'searchFn replaces the built-in matching'\n\nconst searchOptions = {\n threshold: {\n type: 'number',\n check: (v: number) => v >= 0 && v <= 1,\n expected: 'a number from 0 to 1',\n noEffect: matching,\n },\n fuzzyMaxDistance: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n noEffect: matching,\n },\n caseSensitive: { type: 'boolean', noEffect: matching },\n typing: { type: 'object', shape: typingOptions },\n mode: modeOption,\n searchFn: {\n type: 'function',\n check: (v: object) => typeof (v as { [SEARCH_ENGINE]?: unknown })[SEARCH_ENGINE] === 'function',\n expected:\n \"a function wrapped with withSearchFn() from '@datakable/core/search-async': \" +\n 'searchFn: withSearchFn(fn)',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.mode === 'server'\n ? \"mode is 'server': the server (options.fetcher, or the app) matches the query\"\n : undefined,\n },\n} as const\n\nconst settledSuperseded = () => Promise.resolve(SUPERSEDED)\n\nconst toText = (q: unknown): string => (q == null ? '' : String(q))\n\n/**\n * Global search (§6.3), client mode: fuzzy matching with `ex-search` on the formatted values of the\n * searchable columns (`search: weight`; when none declares one, every column of primitives at\n * weight 1, #27).\n *\n * - The matcher is built on the first non-blank query, once per data + columns (not per keystroke),\n * over the column cache's values; ex-search reads the projection `{ i, c0, c1, … }` one chunk of\n * rows at a time, built while matching and not kept (§9.3 memory); results map back by index.\n * - A blank or whitespace-only query keeps every row. The query is trimmed before matching.\n * - Rows are ordered by relevance (score descending, ties by original index); a sort stage after\n * search overrides that order.\n */\nexport const search = <T = AnyRow>(opts: SearchOptions<T> = {}) => {\n const config: MatchConfig = {\n threshold: opts.threshold ?? 0.3,\n fuzzyMaxDistance: opts.fuzzyMaxDistance ?? 3,\n caseSensitive: opts.caseSensitive ?? false,\n }\n /**\n * data → columns → the key of the projection job (`ctx.slice`, §9.1): its result is the index\n * (`null`: nothing searchable). Released with the data.\n */\n const indexes = new WeakMap<object, WeakMap<object, object>>()\n /** Job key → its finished index, also for runs without slicing (`explainRow` replays). */\n const built = new WeakMap<object, SearchIndex | null>()\n /** `ex-search` usable (probed once per feature instance, on the first build). */\n let useExSearch: boolean | undefined\n /** Columns references already reported as having no searchable column. */\n const reported = new WeakSet<object>()\n /** The last step: a slice change that keeps the query (typing, status) reuses its output. */\n let last:\n | { input: Uint32Array; query: string; index: SearchIndex; output: Uint32Array }\n | undefined\n /** The key of the latest matching job (one query over one set of rows). */\n let matching: { rows: Uint32Array; index: SearchIndex; query: string; key: object } | undefined\n /** The step's last output and its input: the stand-in while sliced work runs (§9.1). */\n let shown: { input: Uint32Array; output: Uint32Array } | undefined\n const server = opts.mode === 'server'\n // Server defaults (§6.3): debounce, minLength 2. Filled in before the option check, so `wait` /\n // `behavior` alone are not reported as having no effect.\n const typing: SearchTyping = server\n ? { strategy: 'debounce', minLength: 2, ...opts.typing }\n : (opts.typing ?? {})\n const strategy = typing.commitOn === 'enter' ? 'enter' : (typing.strategy ?? 'immediate')\n const wait = typing.wait ?? DEFAULT_WAIT\n const minLength = typing.minLength ?? 0\n /** The query an input applies (a shorter trimmed input is no search). */\n const target = (input: string) => (input.trim().length < minLength ? '' : input)\n /** The async engine a `withSearchFn` searchFn brings (§6.3); `undefined` for client search. */\n const engine: SearchEngine | undefined = opts.searchFn?.[SEARCH_ENGINE]?.(opts.searchFn as never)\n // Never silent (§8.6): in production (no option validator) an unwrapped searchFn would be\n // ignored; in development the validator reports it at createTable(), with the full text.\n if (!(process.env.NODE_ENV !== \"production\") && opts.searchFn && !engine) {\n throwConfigError('DK_INVALID_OPTION', {\n path: 'searchFn',\n feature: 'search',\n expected: 'wrapped|withSearchFn|searchFn|search-async', // prose key (diagnostics/prose.ts)\n received: typeof opts.searchFn,\n suggestions: [],\n phase: 'init',\n })\n }\n /** Per table: ends its timers, searches and waiters on `table:destroy`. */\n const instances = new WeakMap<object, () => void>()\n /** Per table: finishes a restored `'pending'` / `'searching'` slice nothing works on (#22). */\n const resumes = new WeakMap<object, () => void>()\n /** Per table: after each `pipeline:run`, whether the step waited on sliced work (#6). */\n const ran = new WeakMap<object, (waited: boolean) => void>()\n /** The step of the run in progress returned a stand-in (sliced work runs, §9.1). */\n let waited = false\n\n /** The projection of (data, columns): built by a sliced job; `undefined` while it runs. */\n function indexFor(ctx: RowModelContext): SearchIndex | null | undefined {\n let byColumns = indexes.get(ctx.data)\n if (!byColumns) {\n byColumns = new WeakMap()\n indexes.set(ctx.data, byColumns)\n }\n let key = byColumns.get(ctx.columns)\n if (!key) {\n key = {}\n byColumns.set(ctx.columns, key)\n }\n const done = built.get(key)\n if (done !== undefined) return done\n useExSearch ??= probeExSearch(ctx.emit)\n const exSearch = useExSearch\n const index = sliced(ctx, key, () => buildIndex(ctx, config, exSearch))\n if (index !== undefined) built.set(key, index)\n return index\n }\n\n /** The ranked matches of `query` over `rows`: a sliced job; `undefined` while it runs. */\n function matchFor(\n ctx: RowModelContext,\n index: SearchIndex,\n rows: Uint32Array,\n query: string,\n ): Uint32Array | undefined {\n // A replay (`explainRow`) matches its one row at once, leaving the table's job alone.\n if (!ctx.slice) return runJob(() => index.match(rows, query))\n if (\n !matching ||\n matching.rows !== rows ||\n matching.index !== index ||\n matching.query !== query\n ) {\n matching = { rows, index, query, key: {} }\n }\n return sliced(ctx, matching.key, () => index.match(rows, query))\n }\n\n /** While sliced work runs: the previous output for the same input, else the input. */\n const standIn = (indices: Uint32Array) => {\n waited = true\n return shown && shown.input === indices ? shown.output : indices\n }\n\n /** The client step (§6.3); the rowModel below records its output for {@link standIn}. */\n function step(indices: Uint32Array, state: SearchState, ctx: RowModelContext): Uint32Array {\n const query = typeof state?.query === 'string' ? state.query.trim() : ''\n // ex-search returns [] for a blank query: blank means \"no search\".\n if (query === '') return indices\n if (engine) return engine.step(indices, ctx)\n const index = indexFor(ctx)\n // The projection is still being built (time-sliced, §9.1): the row model is 'pending'.\n if (index === undefined) return standIn(indices)\n if (index === null) {\n if (!reported.has(ctx.columns)) {\n reported.add(ctx.columns)\n ctx.emit('DK_OPTION_NO_EFFECT', {\n path: 'query',\n feature: 'search',\n reason: 'not-searchable',\n once: false,\n })\n }\n return indices\n }\n if (last && last.input === indices && last.query === query && last.index === index) {\n return last.output\n }\n // Search runs after filters: only the input rows are matched (order is re-ranked anyway).\n const output = matchFor(ctx, index, indices, query)\n if (output === undefined) return standIn(indices)\n last = { input: indices, query, index, output }\n return output\n }\n\n return defineFeature({\n name: 'search',\n stage: 'search',\n mode: opts.mode ?? 'client',\n options: defineOptions(\n // The option validator runs in development only (§9.3): production drops the schema.\n (process.env.NODE_ENV !== \"production\") ? searchOptions : ({} as typeof searchOptions),\n server ? { ...opts, typing } : opts,\n ),\n initialState: (): SearchState => ({ input: '', query: '', status: 'idle' }),\n // After destroy(): still a promise, so `setSearch(q).then(…)` never throws.\n destroyedResult: { setSearch: settledSuperseded, flushSearch: settledSuperseded },\n interceptors: [\n defineInterceptor({\n name: 'search',\n on: ['table:destroy', 'pipeline:run', 'table:init', 'state:dispatch', 'table:setOptions'],\n intercept(ctx, next) {\n const table = ctx.table as object\n if (ctx.op === 'table:destroy') {\n instances.get(table)?.()\n return next()\n }\n if (ctx.op !== 'pipeline:run') {\n // A slice set from outside (initialState, setState, controlled state) is checked.\n const out = next()\n resumes.get(table)?.()\n return out\n }\n const prev = waited\n waited = false\n try {\n return engine ? engine.run(table, next) : next()\n } finally {\n const w = waited\n waited = prev\n ran.get(table)?.(w)\n }\n },\n }),\n ],\n createApi: (ctx): SearchApi => {\n const table = ctx.table as unknown as object\n /** Writes the slice; `true` when the state changed (a pipeline run follows). */\n const write = (input: string, query: string, status: SearchStatus, error?: unknown) => {\n const s = ctx.getState()\n if (\n status !== 'error' &&\n s?.input === input &&\n s.query === query &&\n s.status === status &&\n !('error' in s)\n ) {\n return false\n }\n ctx.setState(\n status === 'error' ? { input, query, status, error } : { input, query, status },\n )\n return ctx.getState() !== s\n }\n const applied = () => ctx.getState()?.query ?? ''\n const input = () => ctx.getState()?.input ?? ''\n\n // --- promise outcomes (§6.3): resolved when the query is applied, replaced, or failed ---\n /** Waiters of queries not handed to a search yet (typing, pending debounce, Enter mode). */\n let waiting: Waiter[] = []\n const waitFor = (query: string) =>\n new Promise<SearchOutcome>((resolve) => {\n waiting.push({ query, resolve })\n })\n /** A newer query replaces the waiting ones that differ from it. */\n const replaceWaiting = (query: string) => {\n if (waiting.length === 0) return\n const keep: Waiter[] = []\n for (const w of waiting) {\n if (w.query === query) keep.push(w)\n else w.resolve(SUPERSEDED)\n }\n waiting = keep\n }\n\n /** Takes the waiters of `query`; every other waiting one resolves `'superseded'`. */\n const claim = (query: string) => {\n replaceWaiting(query)\n const keep = waiting\n waiting = []\n return keep\n }\n /**\n * Waiters of the applied query until the row model reflects it (#6): sliced work (§9.1)\n * keeps the row model 'pending' after the query is written.\n */\n let held: Waiter[] = []\n /** The last run's step waited on sliced work. */\n let busy = false\n const release = (outcome: SearchOutcome) => {\n const list = held\n held = []\n for (const w of list) w.resolve(outcome)\n }\n /** Cancel, destroy: every waiter, waiting then held, resolves `'superseded'`. */\n const supersede = () => {\n held = [...waiting, ...held]\n waiting = []\n release(SUPERSEDED)\n }\n ran.set(table, (w) => {\n busy = w\n if (!w) release(APPLIED)\n })\n const session: SearchSession | undefined = engine?.session({\n ctx,\n write,\n applied,\n input,\n claim,\n })\n\n /** A typing commit waits on the strategy's timer (the slice shows `'pending'`). */\n let scheduled = false\n /**\n * Applies `query` (typing committed it, Enter, clear): at once, or with `searchFn` through a\n * request (the slice shows `'searching'`).\n */\n const applyQuery = (query: string, inp: string = input()) => {\n scheduled = false\n if (session?.apply(query, inp)) return\n if (held[0]?.query !== query) release(SUPERSEDED)\n held.push(...claim(query))\n // A changed state runs the pipeline (its end releases them); else the last run decides.\n if (!write(inp, query, 'idle') && !busy) release(APPLIED)\n }\n\n // --- typing (T17) ---\n /** Inside a strategy call: a synchronous apply is collected here (one update, not two). */\n let calling = false\n let appliedNow: string | undefined\n const apply = (query: string) => {\n if (calling) appliedNow = query\n else applyQuery(query)\n }\n const timer =\n strategy === 'debounce'\n ? debouncedSignal(applied, apply, wait, { behavior: typing.behavior ?? 'trailing' })\n : strategy === 'throttle'\n ? throttle(apply, wait)\n : undefined\n /** The slice status while nothing new is applied: a search may still be in flight. */\n const resting = (): SearchStatus => (session?.busy() ? 'searching' : 'idle')\n // A restored transient status (URL / storage restore through initialState, setState or a\n // controlled slice) that nothing is working on would stay forever (#22). 'pending' commits the\n // restored input (Enter mode: keeps it), 'searching' ends; a searchFn then runs for the query.\n resumes.set(table, () => {\n const s = ctx.getState()\n const pending = s?.status === 'pending'\n if (pending ? !scheduled : s?.status === 'searching' && !session?.busy()) {\n const inp = toText(s.input)\n write(inp, pending && strategy !== 'enter' ? target(inp) : toText(s.query), resting())\n }\n })\n\n /**\n * Leading debounce (#28): the keystrokes it drops settle `'superseded'` when the silence\n * window ends (it restarts with each keystroke, like kk-debounce's), unless `flushSearch()`\n * applies them first.\n */\n const drop = debounce(() => {\n const list = waiting\n waiting = []\n for (const w of list) w.resolve(SUPERSEDED)\n }, wait)\n /** Drops the scheduled commit (and the end of a leading silence window). */\n const stop = () => {\n timer?.cancel()\n drop.cancel()\n }\n\n instances.set(table, () => {\n stop()\n session?.destroy()\n supersede()\n })\n\n /** Typing: `input` at once; `query` through the strategy (`pending` while scheduled). */\n const commit = (next: string): Promise<SearchOutcome> => {\n const current = applied()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n if (strategy === 'enter') {\n write(next, current, resting())\n return p\n }\n if (!timer || query === current) {\n stop()\n applyQuery(query, next)\n return p\n }\n calling = true\n appliedNow = undefined\n try {\n timer(query)\n } finally {\n calling = false\n }\n if (appliedNow !== undefined) {\n applyQuery(appliedNow, next)\n return p\n }\n // A leading debounce drops the rest of the burst: nothing is scheduled to commit it (the\n // silence window keeps running; `flushSearch()` commits the input), and its promise settles\n // when the window ends.\n if (strategy === 'debounce' && typing.behavior === 'leading') {\n write(next, current, resting())\n drop()\n return p\n }\n scheduled = true\n write(next, current, 'pending')\n return p\n }\n /** Applies `input` now (Enter, clear): any scheduled commit is dropped. */\n const applyNow = (next: string): Promise<SearchOutcome> => {\n stop()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n applyQuery(query, next)\n return p\n }\n return {\n setSearch: (query) => commit(toText(query)),\n flushSearch: () => applyNow(input()),\n cancelSearch: () => {\n scheduled = false\n stop()\n session?.abort()\n supersede()\n const s = ctx.getState()\n if (s?.status === 'pending' || s?.status === 'searching') {\n ctx.setState({ ...s, status: 'idle' })\n }\n },\n clearSearch: () => {\n void applyNow('')\n },\n }\n },\n rowModel: (indices, state, ctx) => {\n const output = step(indices, state, ctx)\n shown = { input: indices, output }\n return output\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAyB;AACzB,4BAAgC;AAChC,sBAAyB;AACzB,mBAAkC;AAClC,qBAA8B;AAC9B,mBAAiC;AACjC,qBAAgC;AAChC,2BAAO;AACP,oBAA8B;AAE9B,IAAAA,iBAAkC;AAClC,mBAA+B;AAC/B,kBAA0C;AAC1C,6BAWO;AACP,0BAA8E;AAC9E,2BAAyC;AAAA,IAEzC,gCAAgB,gCAAmB,6CAAwB;AA8E3D,IAAM,eAAe;AAErB,IAAM,aAAa,CAAC,MAAwB;AAC1C,MAAI,OAAO,MAAM,SAAU,QAAO,OAAO,SAAS,CAAC,KAAK,KAAK;AAC7D,aAAW,KAAK,CAAC,SAAS,WAAW,WAAW,IAAI,GAAY;AAC9D,UAAM,IAAK,EAA8B,CAAC;AAC1C,QAAI,MAAM,UAAa,EAAE,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,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AC;AAC9B,eAAK;AACL,iBAAO;AAAA,QACT;AACA,oBAAY;AACZ,cAAM,MAAM,SAAS,SAAS;AAC9B,eAAO;AAAA,MACT;AAEA,YAAM,WAAW,CAAC,SAAyC;AACzD,aAAK;AACL,cAAM,QAAQ,OAAO,IAAI;AACzB,uBAAe,KAAK;AACpB,cAAM,IAAI,QAAQ,KAAK;AACvB,mBAAW,OAAO,IAAI;AACtB,eAAO;AAAA,MACT;AACA,aAAO;AAAA,QACL,WAAW,CAAC,UAAU,OAAO,OAAO,KAAK,CAAC;AAAA,QAC1C,aAAa,MAAM,SAAS,MAAM,CAAC;AAAA,QACnC,cAAc,MAAM;AAClB,sBAAY;AACZ,eAAK;AACL,mBAAS,MAAM;AACf,oBAAU;AACV,gBAAM,IAAI,IAAI,SAAS;AACvB,cAAI,GAAG,WAAW,aAAa,GAAG,WAAW,aAAa;AACxD,gBAAI,SAAS,EAAE,GAAG,GAAG,QAAQ,OAAO,CAAC;AAAA,UACvC;AAAA,QACF;AAAA,QACA,aAAa,MAAM;AACjB,eAAK,SAAS,EAAE;AAAA,QAClB;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU,CAAC,SAAS,OAAO,QAAQ;AACjC,YAAM,SAAS,KAAK,SAAS,OAAO,GAAG;AACvC,cAAQ,EAAE,OAAO,SAAS,OAAO;AACjC,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":["import_define","matching","input"]}
1
+ {"version":3,"sources":["../../../src/features/search/search.ts"],"sourcesContent":["import { debounce } from 'kk-debounce/debounce'\nimport { debouncedSignal } from 'kk-debounce/debounceSignal'\nimport { throttle } from 'kk-debounce/throttle'\nimport { optionDiagnostics } from '../../catalog/codes'\nimport { defineOptions } from '../../catalog/options'\nimport { throwConfigError } from '../../diagnostics/build'\nimport { keepDiagnostics } from '../../diagnostics/catalog'\nimport '../../diagnostics/process-guard'\nimport { defineFeature } from '../../feature/define'\nimport type { AnyRow, RowModelContext } from '../../feature/types'\nimport { defineInterceptor } from '../../intercept/define'\nimport { runJob, sliced } from '../../pipeline/slice'\nimport { type DataMode, modeOption } from '../../source/mode'\nimport {\n APPLIED,\n type AsyncSearchFn,\n SEARCH_ENGINE,\n type SearchEngine,\n type SearchOutcome,\n type SearchSession,\n type SearchState,\n type SearchStatus,\n SUPERSEDED,\n type Waiter,\n} from './search-fn-brand'\nimport {\n buildIndex,\n type MatchConfig,\n probeExSearch,\n type Scores,\n type SearchIndex,\n} from './search-index'\nimport { skippedColumnDiagnostics } from './skipped-codes'\n\nkeepDiagnostics(optionDiagnostics, skippedColumnDiagnostics)\n\nexport type {\n AsyncSearchFn,\n SearchFn,\n SearchFnContext,\n SearchOutcome,\n SearchResult,\n SearchState,\n SearchStatus,\n} from './search-fn-brand'\n\nexport interface SearchApi {\n /** Sets `input` (and `query`, with the client's immediate typing strategy). */\n setSearch(query: string): Promise<SearchOutcome>\n /** Applies the current `input` now (Enter). */\n flushSearch(): Promise<SearchOutcome>\n /** Drops a pending (debounced) query; `input` and the applied `query` stay. */\n cancelSearch(): void\n /** Empties `input` and `query`: every row is shown again. */\n clearSearch(): void\n}\n\n/** A duration: milliseconds, or a kk-debounce temporal object (`{ seconds: 1, ms: 500 }`). */\nexport type SearchWait =\n | number\n | { hours?: number; minutes?: number; seconds?: number; ms?: number }\n\n/** When `query` follows `input` (§6.3). */\nexport interface SearchTyping {\n /**\n * `'immediate'` (default): every keystroke is applied. `'debounce'`: applied after `wait` of\n * quiet (kk-debounce `debouncedSignal`). `'throttle'`: at most once per `wait` (the first\n * keystroke at once, the latest one at the end of the window).\n */\n strategy?: 'immediate' | 'debounce' | 'throttle'\n /** Default 300 ms. Used by `'debounce'` and `'throttle'`. */\n wait?: SearchWait\n /**\n * Debounce only. `'trailing'` (default): apply after the burst. `'leading'`: apply the first\n * keystroke at once and drop the rest of the burst (`flushSearch()` applies them; otherwise\n * their `setSearch()` promises resolve `'superseded'` when the silence window ends).\n */\n behavior?: 'trailing' | 'leading'\n /** A trimmed input shorter than this is applied as an empty query (all rows). Default 0. */\n minLength?: number\n /** `'type'` (default): typing commits. `'enter'`: only `flushSearch()` commits. */\n commitOn?: 'type' | 'enter'\n}\n\n/** Client matching options (§6.3). */\nexport interface SearchOptions<T = AnyRow> {\n /** Minimum relevance (0–1, weight applied) to keep a row. Default `0.3`. */\n threshold?: number\n /** Maximum Levenshtein distance for a fuzzy match. Default `3`. */\n fuzzyMaxDistance?: number\n /** Default `false`. */\n caseSensitive?: boolean\n /**\n * Typing timing: when `query` follows `input`. Default: immediate; with `mode: 'server'`,\n * debounce 300 ms and `minLength` 2 (§6.3).\n */\n typing?: SearchTyping\n /**\n * `'server'`: the server matches `query` (its state goes to `options.fetcher`, or the app\n * fetches); core skips this step (§7.1). Default `'client'`.\n */\n mode?: DataMode\n /**\n * Replaces the built-in matching (§6.3): called with each applied non-blank query; while it runs\n * `status` is `'searching'` and the previous results stay. A failure keeps them too\n * (`DK_SEARCH_FAILED`, `status: 'error'`); an `AbortError` is not a failure. New data runs it\n * again for the applied query. Wrap it with `withSearchFn()` from `@datakable/core/search-async`\n * (client search does not bundle the async engine): `searchFn: withSearchFn(fn)`.\n */\n searchFn?: AsyncSearchFn<T>\n}\n\nconst DEFAULT_WAIT = 300\n\nconst isDuration = (v: unknown): boolean => {\n if (typeof v === 'number') return Number.isFinite(v) && v >= 0\n for (const k of ['hours', 'minutes', 'seconds', 'ms'] as const) {\n const n = (v as Record<string, unknown>)[k]\n if (n !== undefined && !(typeof n === 'number' && Number.isFinite(n) && n >= 0)) return false\n }\n return true\n}\n\nconst typingOptions = {\n strategy: { type: 'string', oneOf: ['immediate', 'debounce', 'throttle'] },\n wait: {\n type: ['number', 'object'],\n check: isDuration,\n expected: 'milliseconds >= 0 or { hours?, minutes?, seconds?, ms? } with values >= 0',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce' && o.strategy !== 'throttle'\n ? \"only the 'debounce' and 'throttle' strategies wait\"\n : undefined,\n },\n behavior: {\n type: 'string',\n oneOf: ['trailing', 'leading'],\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce'\n ? \"behavior applies to the 'debounce' strategy only\"\n : undefined,\n },\n minLength: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n },\n commitOn: { type: 'string', oneOf: ['type', 'enter'] },\n} as const\n\n/** Built-in matching options do nothing when `searchFn` matches. */\nconst matching = (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.searchFn === undefined ? undefined : 'searchFn replaces the built-in matching'\n\nconst searchOptions = {\n threshold: {\n type: 'number',\n check: (v: number) => v >= 0 && v <= 1,\n expected: 'a number from 0 to 1',\n noEffect: matching,\n },\n fuzzyMaxDistance: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n noEffect: matching,\n },\n caseSensitive: { type: 'boolean', noEffect: matching },\n typing: { type: 'object', shape: typingOptions },\n mode: modeOption,\n searchFn: {\n type: 'function',\n check: (v: object) => typeof (v as { [SEARCH_ENGINE]?: unknown })[SEARCH_ENGINE] === 'function',\n expected:\n \"a function wrapped with withSearchFn() from '@datakable/core/search-async': \" +\n 'searchFn: withSearchFn(fn)',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.mode === 'server'\n ? \"mode is 'server': the server (options.fetcher, or the app) matches the query\"\n : undefined,\n },\n} as const\n\nconst settledSuperseded = () => Promise.resolve(SUPERSEDED)\n\nconst toText = (q: unknown): string => (q == null ? '' : String(q))\n\n/**\n * Global search (§6.3), client mode: fuzzy matching with `ex-search` on the formatted values of the\n * searchable columns (`search: weight`; when none declares one, every column of primitives at\n * weight 1, #27).\n *\n * - The matcher is built on the first non-blank query, once per data + columns (not per keystroke),\n * over the column cache's values; ex-search reads the projection `{ i, c0, c1, … }` one chunk of\n * rows at a time, built while matching and not kept (§9.3 memory); results map back by index.\n * - A blank or whitespace-only query keeps every row. The query is trimmed before matching.\n * - Rows are ordered by relevance (score descending, ties by original index); a sort stage after\n * search overrides that order.\n */\nexport const search = <T = AnyRow>(opts: SearchOptions<T> = {}) => {\n const config: MatchConfig = {\n threshold: opts.threshold ?? 0.3,\n fuzzyMaxDistance: opts.fuzzyMaxDistance ?? 3,\n caseSensitive: opts.caseSensitive ?? false,\n }\n /**\n * data → columns → the key of the projection job (`ctx.slice`, §9.1): its result is the index\n * (`null`: nothing searchable). Released with the data.\n */\n const indexes = new WeakMap<object, WeakMap<object, object>>()\n /** Job key → its finished index, also for runs without slicing (`explainRow` replays). */\n const built = new WeakMap<object, SearchIndex | null>()\n /** `ex-search` usable (probed once per feature instance, on the first build). */\n let useExSearch: boolean | undefined\n /** Columns references already reported as having no searchable column. */\n const reported = new WeakSet<object>()\n /** The last step: a slice change that keeps the query (typing, status) reuses its output. */\n let last:\n | { input: Uint32Array; query: string; index: SearchIndex; output: Uint32Array }\n | undefined\n /**\n * The scores of the last finished match (#95): a new data array re-matches only the rows whose\n * searched texts changed (search-index.ts `match`). 16 bytes per data row.\n */\n const memo: { scores?: Scores } = {}\n /** The key of the latest matching job (one query over one set of rows). */\n let matching: { rows: Uint32Array; index: SearchIndex; query: string; key: object } | undefined\n /** The step's last output and its input: the stand-in while sliced work runs (§9.1). */\n let shown: { input: Uint32Array; output: Uint32Array } | undefined\n const server = opts.mode === 'server'\n // Server defaults (§6.3): debounce, minLength 2. Filled in before the option check, so `wait` /\n // `behavior` alone are not reported as having no effect.\n const typing: SearchTyping = server\n ? { strategy: 'debounce', minLength: 2, ...opts.typing }\n : (opts.typing ?? {})\n const strategy = typing.commitOn === 'enter' ? 'enter' : (typing.strategy ?? 'immediate')\n const wait = typing.wait ?? DEFAULT_WAIT\n const minLength = typing.minLength ?? 0\n /** The query an input applies (a shorter trimmed input is no search). */\n const target = (input: string) => (input.trim().length < minLength ? '' : input)\n /** The async engine a `withSearchFn` searchFn brings (§6.3); `undefined` for client search. */\n const engine: SearchEngine | undefined = opts.searchFn?.[SEARCH_ENGINE]?.(opts.searchFn as never)\n // Never silent (§8.6): in production (no option validator) an unwrapped searchFn would be\n // ignored; in development the validator reports it at createTable(), with the full text.\n if (!(process.env.NODE_ENV !== \"production\") && opts.searchFn && !engine) {\n throwConfigError('DK_INVALID_OPTION', {\n path: 'searchFn',\n feature: 'search',\n expected: 'wrapped|withSearchFn|searchFn|search-async', // prose key (diagnostics/prose.ts)\n received: typeof opts.searchFn,\n suggestions: [],\n phase: 'init',\n })\n }\n /** Per table: ends its timers, searches and waiters on `table:destroy`. */\n const instances = new WeakMap<object, () => void>()\n /** Per table: finishes a restored `'pending'` / `'searching'` slice nothing works on (#22). */\n const resumes = new WeakMap<object, () => void>()\n /** Per table: after each `pipeline:run`, whether the step waited on sliced work (#6). */\n const ran = new WeakMap<object, (waited: boolean) => void>()\n /** The step of the run in progress returned a stand-in (sliced work runs, §9.1). */\n let waited = false\n\n /** The projection of (data, columns): built by a sliced job; `undefined` while it runs. */\n function indexFor(ctx: RowModelContext): SearchIndex | null | undefined {\n let byColumns = indexes.get(ctx.data)\n if (!byColumns) {\n byColumns = new WeakMap()\n indexes.set(ctx.data, byColumns)\n }\n let key = byColumns.get(ctx.columns)\n if (!key) {\n key = {}\n byColumns.set(ctx.columns, key)\n }\n const done = built.get(key)\n if (done !== undefined) return done\n useExSearch ??= probeExSearch(ctx.emit)\n const exSearch = useExSearch\n const index = sliced(ctx, key, () => buildIndex(ctx, config, exSearch))\n if (index !== undefined) built.set(key, index)\n return index\n }\n\n /** The ranked matches of `query` over `rows`: a sliced job; `undefined` while it runs. */\n function matchFor(\n ctx: RowModelContext,\n index: SearchIndex,\n rows: Uint32Array,\n query: string,\n ): Uint32Array | undefined {\n // A replay (`explainRow`) matches its one row at once, leaving the table's job alone.\n if (!ctx.slice) return runJob(() => index.match(rows, query))\n if (\n !matching ||\n matching.rows !== rows ||\n matching.index !== index ||\n matching.query !== query\n ) {\n matching = { rows, index, query, key: {} }\n }\n return sliced(ctx, matching.key, () => index.match(rows, query, memo))\n }\n\n /** While sliced work runs: the previous output for the same input, else the input. */\n const standIn = (indices: Uint32Array) => {\n waited = true\n return shown && shown.input === indices ? shown.output : indices\n }\n\n /** The client step (§6.3); the rowModel below records its output for {@link standIn}. */\n function step(indices: Uint32Array, state: SearchState, ctx: RowModelContext): Uint32Array {\n const query = typeof state?.query === 'string' ? state.query.trim() : ''\n // ex-search returns [] for a blank query: blank means \"no search\".\n if (query === '') return indices\n if (engine) return engine.step(indices, ctx)\n const index = indexFor(ctx)\n // The projection is still being built (time-sliced, §9.1): the row model is 'pending'.\n if (index === undefined) return standIn(indices)\n if (index === null) {\n if (!reported.has(ctx.columns)) {\n reported.add(ctx.columns)\n ctx.emit('DK_OPTION_NO_EFFECT', {\n path: 'query',\n feature: 'search',\n reason: 'not-searchable',\n once: false,\n })\n }\n return indices\n }\n if (last && last.input === indices && last.query === query && last.index === index) {\n return last.output\n }\n // Search runs after filters: only the input rows are matched (order is re-ranked anyway).\n const output = matchFor(ctx, index, indices, query)\n if (output === undefined) return standIn(indices)\n last = { input: indices, query, index, output }\n return output\n }\n\n return defineFeature({\n name: 'search',\n stage: 'search',\n mode: opts.mode ?? 'client',\n options: defineOptions(\n // The option validator runs in development only (§9.3): production drops the schema.\n (process.env.NODE_ENV !== \"production\") ? searchOptions : ({} as typeof searchOptions),\n server ? { ...opts, typing } : opts,\n ),\n initialState: (): SearchState => ({ input: '', query: '', status: 'idle' }),\n // After destroy(): still a promise, so `setSearch(q).then(…)` never throws.\n destroyedResult: { setSearch: settledSuperseded, flushSearch: settledSuperseded },\n interceptors: [\n defineInterceptor({\n name: 'search',\n on: ['table:destroy', 'pipeline:run', 'table:init', 'state:dispatch', 'table:setOptions'],\n intercept(ctx, next) {\n const table = ctx.table as object\n if (ctx.op === 'table:destroy') {\n instances.get(table)?.()\n return next()\n }\n if (ctx.op !== 'pipeline:run') {\n // A slice set from outside (initialState, setState, controlled state) is checked.\n const out = next()\n resumes.get(table)?.()\n return out\n }\n const prev = waited\n waited = false\n try {\n return engine ? engine.run(table, next) : next()\n } finally {\n const w = waited\n waited = prev\n ran.get(table)?.(w)\n }\n },\n }),\n ],\n createApi: (ctx): SearchApi => {\n const table = ctx.table as unknown as object\n /** Writes the slice; `true` when the state changed (a pipeline run follows). */\n const write = (input: string, query: string, status: SearchStatus, error?: unknown) => {\n const s = ctx.getState()\n if (\n status !== 'error' &&\n s?.input === input &&\n s.query === query &&\n s.status === status &&\n !('error' in s)\n ) {\n return false\n }\n ctx.setState(\n status === 'error' ? { input, query, status, error } : { input, query, status },\n )\n return ctx.getState() !== s\n }\n const applied = () => ctx.getState()?.query ?? ''\n const input = () => ctx.getState()?.input ?? ''\n\n // --- promise outcomes (§6.3): resolved when the query is applied, replaced, or failed ---\n /** Waiters of queries not handed to a search yet (typing, pending debounce, Enter mode). */\n let waiting: Waiter[] = []\n const waitFor = (query: string) =>\n new Promise<SearchOutcome>((resolve) => {\n waiting.push({ query, resolve })\n })\n /** A newer query replaces the waiting ones that differ from it. */\n const replaceWaiting = (query: string) => {\n if (waiting.length === 0) return\n const keep: Waiter[] = []\n for (const w of waiting) {\n if (w.query === query) keep.push(w)\n else w.resolve(SUPERSEDED)\n }\n waiting = keep\n }\n\n /** Takes the waiters of `query`; every other waiting one resolves `'superseded'`. */\n const claim = (query: string) => {\n replaceWaiting(query)\n const keep = waiting\n waiting = []\n return keep\n }\n /**\n * Waiters of the applied query until the row model reflects it (#6): sliced work (§9.1)\n * keeps the row model 'pending' after the query is written.\n */\n let held: Waiter[] = []\n /** The last run's step waited on sliced work. */\n let busy = false\n const release = (outcome: SearchOutcome) => {\n const list = held\n held = []\n for (const w of list) w.resolve(outcome)\n }\n /** Cancel, destroy: every waiter, waiting then held, resolves `'superseded'`. */\n const supersede = () => {\n held = [...waiting, ...held]\n waiting = []\n release(SUPERSEDED)\n }\n ran.set(table, (w) => {\n busy = w\n if (!w) release(APPLIED)\n })\n const session: SearchSession | undefined = engine?.session({\n ctx,\n write,\n applied,\n input,\n claim,\n })\n\n /** A typing commit waits on the strategy's timer (the slice shows `'pending'`). */\n let scheduled = false\n /**\n * Applies `query` (typing committed it, Enter, clear): at once, or with `searchFn` through a\n * request (the slice shows `'searching'`).\n */\n const applyQuery = (query: string, inp: string = input()) => {\n scheduled = false\n if (session?.apply(query, inp)) return\n if (held[0]?.query !== query) release(SUPERSEDED)\n held.push(...claim(query))\n // A changed state runs the pipeline (its end releases them); else the last run decides.\n if (!write(inp, query, 'idle') && !busy) release(APPLIED)\n }\n\n // --- typing (T17) ---\n /** Inside a strategy call: a synchronous apply is collected here (one update, not two). */\n let calling = false\n let appliedNow: string | undefined\n const apply = (query: string) => {\n if (calling) appliedNow = query\n else applyQuery(query)\n }\n const timer =\n strategy === 'debounce'\n ? debouncedSignal(applied, apply, wait, { behavior: typing.behavior ?? 'trailing' })\n : strategy === 'throttle'\n ? throttle(apply, wait)\n : undefined\n /** The slice status while nothing new is applied: a search may still be in flight. */\n const resting = (): SearchStatus => (session?.busy() ? 'searching' : 'idle')\n // A restored transient status (URL / storage restore through initialState, setState or a\n // controlled slice) that nothing is working on would stay forever (#22). 'pending' commits the\n // restored input (Enter mode: keeps it), 'searching' ends; a searchFn then runs for the query.\n resumes.set(table, () => {\n const s = ctx.getState()\n const pending = s?.status === 'pending'\n if (pending ? !scheduled : s?.status === 'searching' && !session?.busy()) {\n const inp = toText(s.input)\n write(inp, pending && strategy !== 'enter' ? target(inp) : toText(s.query), resting())\n }\n })\n\n /**\n * Leading debounce (#28): the keystrokes it drops settle `'superseded'` when the silence\n * window ends (it restarts with each keystroke, like kk-debounce's), unless `flushSearch()`\n * applies them first.\n */\n const drop = debounce(() => {\n const list = waiting\n waiting = []\n for (const w of list) w.resolve(SUPERSEDED)\n }, wait)\n /** Drops the scheduled commit (and the end of a leading silence window). */\n const stop = () => {\n timer?.cancel()\n drop.cancel()\n }\n\n instances.set(table, () => {\n stop()\n session?.destroy()\n supersede()\n })\n\n /** Typing: `input` at once; `query` through the strategy (`pending` while scheduled). */\n const commit = (next: string): Promise<SearchOutcome> => {\n const current = applied()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n if (strategy === 'enter') {\n write(next, current, resting())\n return p\n }\n if (!timer || query === current) {\n stop()\n applyQuery(query, next)\n return p\n }\n calling = true\n appliedNow = undefined\n try {\n timer(query)\n } finally {\n calling = false\n }\n if (appliedNow !== undefined) {\n applyQuery(appliedNow, next)\n return p\n }\n // A leading debounce drops the rest of the burst: nothing is scheduled to commit it (the\n // silence window keeps running; `flushSearch()` commits the input), and its promise settles\n // when the window ends.\n if (strategy === 'debounce' && typing.behavior === 'leading') {\n write(next, current, resting())\n drop()\n return p\n }\n scheduled = true\n write(next, current, 'pending')\n return p\n }\n /** Applies `input` now (Enter, clear): any scheduled commit is dropped. */\n const applyNow = (next: string): Promise<SearchOutcome> => {\n stop()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n applyQuery(query, next)\n return p\n }\n return {\n setSearch: (query) => commit(toText(query)),\n flushSearch: () => applyNow(input()),\n cancelSearch: () => {\n scheduled = false\n stop()\n session?.abort()\n supersede()\n const s = ctx.getState()\n if (s?.status === 'pending' || s?.status === 'searching') {\n ctx.setState({ ...s, status: 'idle' })\n }\n },\n clearSearch: () => {\n void applyNow('')\n },\n }\n },\n rowModel: (indices, state, ctx) => {\n const output = step(indices, state, ctx)\n shown = { input: indices, output }\n return output\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAyB;AACzB,4BAAgC;AAChC,sBAAyB;AACzB,mBAAkC;AAClC,qBAA8B;AAC9B,mBAAiC;AACjC,qBAAgC;AAChC,2BAAO;AACP,oBAA8B;AAE9B,IAAAA,iBAAkC;AAClC,mBAA+B;AAC/B,kBAA0C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A,IACT;AAAA,EACF,CAAC;AACH;","names":["import_define","matching","input"]}
@@ -16,7 +16,10 @@ import {
16
16
  SEARCH_ENGINE,
17
17
  SUPERSEDED
18
18
  } from "./search-fn-brand.js";
19
- import { buildIndex, probeExSearch } from "./search-index.js";
19
+ import {
20
+ buildIndex,
21
+ probeExSearch
22
+ } from "./search-index.js";
20
23
  import { skippedColumnDiagnostics } from "./skipped-codes.js";
21
24
  keepDiagnostics(optionDiagnostics, skippedColumnDiagnostics);
22
25
  var DEFAULT_WAIT = 300;
@@ -85,6 +88,7 @@ var search = (opts = {}) => {
85
88
  let useExSearch;
86
89
  const reported = /* @__PURE__ */ new WeakSet();
87
90
  let last;
91
+ const memo = {};
88
92
  let matching2;
89
93
  let shown;
90
94
  const server = opts.mode === "server";
@@ -133,7 +137,7 @@ var search = (opts = {}) => {
133
137
  if (!matching2 || matching2.rows !== rows || matching2.index !== index || matching2.query !== query) {
134
138
  matching2 = { rows, index, query, key: {} };
135
139
  }
136
- return sliced(ctx, matching2.key, () => index.match(rows, query));
140
+ return sliced(ctx, matching2.key, () => index.match(rows, query, memo));
137
141
  }
138
142
  const standIn = (indices) => {
139
143
  waited = true;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/features/search/search.ts"],"sourcesContent":["import { debounce } from 'kk-debounce/debounce'\nimport { debouncedSignal } from 'kk-debounce/debounceSignal'\nimport { throttle } from 'kk-debounce/throttle'\nimport { optionDiagnostics } from '../../catalog/codes'\nimport { defineOptions } from '../../catalog/options'\nimport { throwConfigError } from '../../diagnostics/build'\nimport { keepDiagnostics } from '../../diagnostics/catalog'\nimport '../../diagnostics/process-guard'\nimport { defineFeature } from '../../feature/define'\nimport type { AnyRow, RowModelContext } from '../../feature/types'\nimport { defineInterceptor } from '../../intercept/define'\nimport { runJob, sliced } from '../../pipeline/slice'\nimport { type DataMode, modeOption } from '../../source/mode'\nimport {\n APPLIED,\n type AsyncSearchFn,\n SEARCH_ENGINE,\n type SearchEngine,\n type SearchOutcome,\n type SearchSession,\n type SearchState,\n type SearchStatus,\n SUPERSEDED,\n type Waiter,\n} from './search-fn-brand'\nimport { buildIndex, type MatchConfig, probeExSearch, type SearchIndex } from './search-index'\nimport { skippedColumnDiagnostics } from './skipped-codes'\n\nkeepDiagnostics(optionDiagnostics, skippedColumnDiagnostics)\n\nexport type {\n AsyncSearchFn,\n SearchFn,\n SearchFnContext,\n SearchOutcome,\n SearchResult,\n SearchState,\n SearchStatus,\n} from './search-fn-brand'\n\nexport interface SearchApi {\n /** Sets `input` (and `query`, with the client's immediate typing strategy). */\n setSearch(query: string): Promise<SearchOutcome>\n /** Applies the current `input` now (Enter). */\n flushSearch(): Promise<SearchOutcome>\n /** Drops a pending (debounced) query; `input` and the applied `query` stay. */\n cancelSearch(): void\n /** Empties `input` and `query`: every row is shown again. */\n clearSearch(): void\n}\n\n/** A duration: milliseconds, or a kk-debounce temporal object (`{ seconds: 1, ms: 500 }`). */\nexport type SearchWait =\n | number\n | { hours?: number; minutes?: number; seconds?: number; ms?: number }\n\n/** When `query` follows `input` (§6.3). */\nexport interface SearchTyping {\n /**\n * `'immediate'` (default): every keystroke is applied. `'debounce'`: applied after `wait` of\n * quiet (kk-debounce `debouncedSignal`). `'throttle'`: at most once per `wait` (the first\n * keystroke at once, the latest one at the end of the window).\n */\n strategy?: 'immediate' | 'debounce' | 'throttle'\n /** Default 300 ms. Used by `'debounce'` and `'throttle'`. */\n wait?: SearchWait\n /**\n * Debounce only. `'trailing'` (default): apply after the burst. `'leading'`: apply the first\n * keystroke at once and drop the rest of the burst (`flushSearch()` applies them; otherwise\n * their `setSearch()` promises resolve `'superseded'` when the silence window ends).\n */\n behavior?: 'trailing' | 'leading'\n /** A trimmed input shorter than this is applied as an empty query (all rows). Default 0. */\n minLength?: number\n /** `'type'` (default): typing commits. `'enter'`: only `flushSearch()` commits. */\n commitOn?: 'type' | 'enter'\n}\n\n/** Client matching options (§6.3). */\nexport interface SearchOptions<T = AnyRow> {\n /** Minimum relevance (0–1, weight applied) to keep a row. Default `0.3`. */\n threshold?: number\n /** Maximum Levenshtein distance for a fuzzy match. Default `3`. */\n fuzzyMaxDistance?: number\n /** Default `false`. */\n caseSensitive?: boolean\n /**\n * Typing timing: when `query` follows `input`. Default: immediate; with `mode: 'server'`,\n * debounce 300 ms and `minLength` 2 (§6.3).\n */\n typing?: SearchTyping\n /**\n * `'server'`: the server matches `query` (its state goes to `options.fetcher`, or the app\n * fetches); core skips this step (§7.1). Default `'client'`.\n */\n mode?: DataMode\n /**\n * Replaces the built-in matching (§6.3): called with each applied non-blank query; while it runs\n * `status` is `'searching'` and the previous results stay. A failure keeps them too\n * (`DK_SEARCH_FAILED`, `status: 'error'`); an `AbortError` is not a failure. New data runs it\n * again for the applied query. Wrap it with `withSearchFn()` from `@datakable/core/search-async`\n * (client search does not bundle the async engine): `searchFn: withSearchFn(fn)`.\n */\n searchFn?: AsyncSearchFn<T>\n}\n\nconst DEFAULT_WAIT = 300\n\nconst isDuration = (v: unknown): boolean => {\n if (typeof v === 'number') return Number.isFinite(v) && v >= 0\n for (const k of ['hours', 'minutes', 'seconds', 'ms'] as const) {\n const n = (v as Record<string, unknown>)[k]\n if (n !== undefined && !(typeof n === 'number' && Number.isFinite(n) && n >= 0)) return false\n }\n return true\n}\n\nconst typingOptions = {\n strategy: { type: 'string', oneOf: ['immediate', 'debounce', 'throttle'] },\n wait: {\n type: ['number', 'object'],\n check: isDuration,\n expected: 'milliseconds >= 0 or { hours?, minutes?, seconds?, ms? } with values >= 0',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce' && o.strategy !== 'throttle'\n ? \"only the 'debounce' and 'throttle' strategies wait\"\n : undefined,\n },\n behavior: {\n type: 'string',\n oneOf: ['trailing', 'leading'],\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce'\n ? \"behavior applies to the 'debounce' strategy only\"\n : undefined,\n },\n minLength: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n },\n commitOn: { type: 'string', oneOf: ['type', 'enter'] },\n} as const\n\n/** Built-in matching options do nothing when `searchFn` matches. */\nconst matching = (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.searchFn === undefined ? undefined : 'searchFn replaces the built-in matching'\n\nconst searchOptions = {\n threshold: {\n type: 'number',\n check: (v: number) => v >= 0 && v <= 1,\n expected: 'a number from 0 to 1',\n noEffect: matching,\n },\n fuzzyMaxDistance: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n noEffect: matching,\n },\n caseSensitive: { type: 'boolean', noEffect: matching },\n typing: { type: 'object', shape: typingOptions },\n mode: modeOption,\n searchFn: {\n type: 'function',\n check: (v: object) => typeof (v as { [SEARCH_ENGINE]?: unknown })[SEARCH_ENGINE] === 'function',\n expected:\n \"a function wrapped with withSearchFn() from '@datakable/core/search-async': \" +\n 'searchFn: withSearchFn(fn)',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.mode === 'server'\n ? \"mode is 'server': the server (options.fetcher, or the app) matches the query\"\n : undefined,\n },\n} as const\n\nconst settledSuperseded = () => Promise.resolve(SUPERSEDED)\n\nconst toText = (q: unknown): string => (q == null ? '' : String(q))\n\n/**\n * Global search (§6.3), client mode: fuzzy matching with `ex-search` on the formatted values of the\n * searchable columns (`search: weight`; when none declares one, every column of primitives at\n * weight 1, #27).\n *\n * - The matcher is built on the first non-blank query, once per data + columns (not per keystroke),\n * over the column cache's values; ex-search reads the projection `{ i, c0, c1, … }` one chunk of\n * rows at a time, built while matching and not kept (§9.3 memory); results map back by index.\n * - A blank or whitespace-only query keeps every row. The query is trimmed before matching.\n * - Rows are ordered by relevance (score descending, ties by original index); a sort stage after\n * search overrides that order.\n */\nexport const search = <T = AnyRow>(opts: SearchOptions<T> = {}) => {\n const config: MatchConfig = {\n threshold: opts.threshold ?? 0.3,\n fuzzyMaxDistance: opts.fuzzyMaxDistance ?? 3,\n caseSensitive: opts.caseSensitive ?? false,\n }\n /**\n * data → columns → the key of the projection job (`ctx.slice`, §9.1): its result is the index\n * (`null`: nothing searchable). Released with the data.\n */\n const indexes = new WeakMap<object, WeakMap<object, object>>()\n /** Job key → its finished index, also for runs without slicing (`explainRow` replays). */\n const built = new WeakMap<object, SearchIndex | null>()\n /** `ex-search` usable (probed once per feature instance, on the first build). */\n let useExSearch: boolean | undefined\n /** Columns references already reported as having no searchable column. */\n const reported = new WeakSet<object>()\n /** The last step: a slice change that keeps the query (typing, status) reuses its output. */\n let last:\n | { input: Uint32Array; query: string; index: SearchIndex; output: Uint32Array }\n | undefined\n /** The key of the latest matching job (one query over one set of rows). */\n let matching: { rows: Uint32Array; index: SearchIndex; query: string; key: object } | undefined\n /** The step's last output and its input: the stand-in while sliced work runs (§9.1). */\n let shown: { input: Uint32Array; output: Uint32Array } | undefined\n const server = opts.mode === 'server'\n // Server defaults (§6.3): debounce, minLength 2. Filled in before the option check, so `wait` /\n // `behavior` alone are not reported as having no effect.\n const typing: SearchTyping = server\n ? { strategy: 'debounce', minLength: 2, ...opts.typing }\n : (opts.typing ?? {})\n const strategy = typing.commitOn === 'enter' ? 'enter' : (typing.strategy ?? 'immediate')\n const wait = typing.wait ?? DEFAULT_WAIT\n const minLength = typing.minLength ?? 0\n /** The query an input applies (a shorter trimmed input is no search). */\n const target = (input: string) => (input.trim().length < minLength ? '' : input)\n /** The async engine a `withSearchFn` searchFn brings (§6.3); `undefined` for client search. */\n const engine: SearchEngine | undefined = opts.searchFn?.[SEARCH_ENGINE]?.(opts.searchFn as never)\n // Never silent (§8.6): in production (no option validator) an unwrapped searchFn would be\n // ignored; in development the validator reports it at createTable(), with the full text.\n if (!(process.env.NODE_ENV !== \"production\") && opts.searchFn && !engine) {\n throwConfigError('DK_INVALID_OPTION', {\n path: 'searchFn',\n feature: 'search',\n expected: 'wrapped|withSearchFn|searchFn|search-async', // prose key (diagnostics/prose.ts)\n received: typeof opts.searchFn,\n suggestions: [],\n phase: 'init',\n })\n }\n /** Per table: ends its timers, searches and waiters on `table:destroy`. */\n const instances = new WeakMap<object, () => void>()\n /** Per table: finishes a restored `'pending'` / `'searching'` slice nothing works on (#22). */\n const resumes = new WeakMap<object, () => void>()\n /** Per table: after each `pipeline:run`, whether the step waited on sliced work (#6). */\n const ran = new WeakMap<object, (waited: boolean) => void>()\n /** The step of the run in progress returned a stand-in (sliced work runs, §9.1). */\n let waited = false\n\n /** The projection of (data, columns): built by a sliced job; `undefined` while it runs. */\n function indexFor(ctx: RowModelContext): SearchIndex | null | undefined {\n let byColumns = indexes.get(ctx.data)\n if (!byColumns) {\n byColumns = new WeakMap()\n indexes.set(ctx.data, byColumns)\n }\n let key = byColumns.get(ctx.columns)\n if (!key) {\n key = {}\n byColumns.set(ctx.columns, key)\n }\n const done = built.get(key)\n if (done !== undefined) return done\n useExSearch ??= probeExSearch(ctx.emit)\n const exSearch = useExSearch\n const index = sliced(ctx, key, () => buildIndex(ctx, config, exSearch))\n if (index !== undefined) built.set(key, index)\n return index\n }\n\n /** The ranked matches of `query` over `rows`: a sliced job; `undefined` while it runs. */\n function matchFor(\n ctx: RowModelContext,\n index: SearchIndex,\n rows: Uint32Array,\n query: string,\n ): Uint32Array | undefined {\n // A replay (`explainRow`) matches its one row at once, leaving the table's job alone.\n if (!ctx.slice) return runJob(() => index.match(rows, query))\n if (\n !matching ||\n matching.rows !== rows ||\n matching.index !== index ||\n matching.query !== query\n ) {\n matching = { rows, index, query, key: {} }\n }\n return sliced(ctx, matching.key, () => index.match(rows, query))\n }\n\n /** While sliced work runs: the previous output for the same input, else the input. */\n const standIn = (indices: Uint32Array) => {\n waited = true\n return shown && shown.input === indices ? shown.output : indices\n }\n\n /** The client step (§6.3); the rowModel below records its output for {@link standIn}. */\n function step(indices: Uint32Array, state: SearchState, ctx: RowModelContext): Uint32Array {\n const query = typeof state?.query === 'string' ? state.query.trim() : ''\n // ex-search returns [] for a blank query: blank means \"no search\".\n if (query === '') return indices\n if (engine) return engine.step(indices, ctx)\n const index = indexFor(ctx)\n // The projection is still being built (time-sliced, §9.1): the row model is 'pending'.\n if (index === undefined) return standIn(indices)\n if (index === null) {\n if (!reported.has(ctx.columns)) {\n reported.add(ctx.columns)\n ctx.emit('DK_OPTION_NO_EFFECT', {\n path: 'query',\n feature: 'search',\n reason: 'not-searchable',\n once: false,\n })\n }\n return indices\n }\n if (last && last.input === indices && last.query === query && last.index === index) {\n return last.output\n }\n // Search runs after filters: only the input rows are matched (order is re-ranked anyway).\n const output = matchFor(ctx, index, indices, query)\n if (output === undefined) return standIn(indices)\n last = { input: indices, query, index, output }\n return output\n }\n\n return defineFeature({\n name: 'search',\n stage: 'search',\n mode: opts.mode ?? 'client',\n options: defineOptions(\n // The option validator runs in development only (§9.3): production drops the schema.\n (process.env.NODE_ENV !== \"production\") ? searchOptions : ({} as typeof searchOptions),\n server ? { ...opts, typing } : opts,\n ),\n initialState: (): SearchState => ({ input: '', query: '', status: 'idle' }),\n // After destroy(): still a promise, so `setSearch(q).then(…)` never throws.\n destroyedResult: { setSearch: settledSuperseded, flushSearch: settledSuperseded },\n interceptors: [\n defineInterceptor({\n name: 'search',\n on: ['table:destroy', 'pipeline:run', 'table:init', 'state:dispatch', 'table:setOptions'],\n intercept(ctx, next) {\n const table = ctx.table as object\n if (ctx.op === 'table:destroy') {\n instances.get(table)?.()\n return next()\n }\n if (ctx.op !== 'pipeline:run') {\n // A slice set from outside (initialState, setState, controlled state) is checked.\n const out = next()\n resumes.get(table)?.()\n return out\n }\n const prev = waited\n waited = false\n try {\n return engine ? engine.run(table, next) : next()\n } finally {\n const w = waited\n waited = prev\n ran.get(table)?.(w)\n }\n },\n }),\n ],\n createApi: (ctx): SearchApi => {\n const table = ctx.table as unknown as object\n /** Writes the slice; `true` when the state changed (a pipeline run follows). */\n const write = (input: string, query: string, status: SearchStatus, error?: unknown) => {\n const s = ctx.getState()\n if (\n status !== 'error' &&\n s?.input === input &&\n s.query === query &&\n s.status === status &&\n !('error' in s)\n ) {\n return false\n }\n ctx.setState(\n status === 'error' ? { input, query, status, error } : { input, query, status },\n )\n return ctx.getState() !== s\n }\n const applied = () => ctx.getState()?.query ?? ''\n const input = () => ctx.getState()?.input ?? ''\n\n // --- promise outcomes (§6.3): resolved when the query is applied, replaced, or failed ---\n /** Waiters of queries not handed to a search yet (typing, pending debounce, Enter mode). */\n let waiting: Waiter[] = []\n const waitFor = (query: string) =>\n new Promise<SearchOutcome>((resolve) => {\n waiting.push({ query, resolve })\n })\n /** A newer query replaces the waiting ones that differ from it. */\n const replaceWaiting = (query: string) => {\n if (waiting.length === 0) return\n const keep: Waiter[] = []\n for (const w of waiting) {\n if (w.query === query) keep.push(w)\n else w.resolve(SUPERSEDED)\n }\n waiting = keep\n }\n\n /** Takes the waiters of `query`; every other waiting one resolves `'superseded'`. */\n const claim = (query: string) => {\n replaceWaiting(query)\n const keep = waiting\n waiting = []\n return keep\n }\n /**\n * Waiters of the applied query until the row model reflects it (#6): sliced work (§9.1)\n * keeps the row model 'pending' after the query is written.\n */\n let held: Waiter[] = []\n /** The last run's step waited on sliced work. */\n let busy = false\n const release = (outcome: SearchOutcome) => {\n const list = held\n held = []\n for (const w of list) w.resolve(outcome)\n }\n /** Cancel, destroy: every waiter, waiting then held, resolves `'superseded'`. */\n const supersede = () => {\n held = [...waiting, ...held]\n waiting = []\n release(SUPERSEDED)\n }\n ran.set(table, (w) => {\n busy = w\n if (!w) release(APPLIED)\n })\n const session: SearchSession | undefined = engine?.session({\n ctx,\n write,\n applied,\n input,\n claim,\n })\n\n /** A typing commit waits on the strategy's timer (the slice shows `'pending'`). */\n let scheduled = false\n /**\n * Applies `query` (typing committed it, Enter, clear): at once, or with `searchFn` through a\n * request (the slice shows `'searching'`).\n */\n const applyQuery = (query: string, inp: string = input()) => {\n scheduled = false\n if (session?.apply(query, inp)) return\n if (held[0]?.query !== query) release(SUPERSEDED)\n held.push(...claim(query))\n // A changed state runs the pipeline (its end releases them); else the last run decides.\n if (!write(inp, query, 'idle') && !busy) release(APPLIED)\n }\n\n // --- typing (T17) ---\n /** Inside a strategy call: a synchronous apply is collected here (one update, not two). */\n let calling = false\n let appliedNow: string | undefined\n const apply = (query: string) => {\n if (calling) appliedNow = query\n else applyQuery(query)\n }\n const timer =\n strategy === 'debounce'\n ? debouncedSignal(applied, apply, wait, { behavior: typing.behavior ?? 'trailing' })\n : strategy === 'throttle'\n ? throttle(apply, wait)\n : undefined\n /** The slice status while nothing new is applied: a search may still be in flight. */\n const resting = (): SearchStatus => (session?.busy() ? 'searching' : 'idle')\n // A restored transient status (URL / storage restore through initialState, setState or a\n // controlled slice) that nothing is working on would stay forever (#22). 'pending' commits the\n // restored input (Enter mode: keeps it), 'searching' ends; a searchFn then runs for the query.\n resumes.set(table, () => {\n const s = ctx.getState()\n const pending = s?.status === 'pending'\n if (pending ? !scheduled : s?.status === 'searching' && !session?.busy()) {\n const inp = toText(s.input)\n write(inp, pending && strategy !== 'enter' ? target(inp) : toText(s.query), resting())\n }\n })\n\n /**\n * Leading debounce (#28): the keystrokes it drops settle `'superseded'` when the silence\n * window ends (it restarts with each keystroke, like kk-debounce's), unless `flushSearch()`\n * applies them first.\n */\n const drop = debounce(() => {\n const list = waiting\n waiting = []\n for (const w of list) w.resolve(SUPERSEDED)\n }, wait)\n /** Drops the scheduled commit (and the end of a leading silence window). */\n const stop = () => {\n timer?.cancel()\n drop.cancel()\n }\n\n instances.set(table, () => {\n stop()\n session?.destroy()\n supersede()\n })\n\n /** Typing: `input` at once; `query` through the strategy (`pending` while scheduled). */\n const commit = (next: string): Promise<SearchOutcome> => {\n const current = applied()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n if (strategy === 'enter') {\n write(next, current, resting())\n return p\n }\n if (!timer || query === current) {\n stop()\n applyQuery(query, next)\n return p\n }\n calling = true\n appliedNow = undefined\n try {\n timer(query)\n } finally {\n calling = false\n }\n if (appliedNow !== undefined) {\n applyQuery(appliedNow, next)\n return p\n }\n // A leading debounce drops the rest of the burst: nothing is scheduled to commit it (the\n // silence window keeps running; `flushSearch()` commits the input), and its promise settles\n // when the window ends.\n if (strategy === 'debounce' && typing.behavior === 'leading') {\n write(next, current, resting())\n drop()\n return p\n }\n scheduled = true\n write(next, current, 'pending')\n return p\n }\n /** Applies `input` now (Enter, clear): any scheduled commit is dropped. */\n const applyNow = (next: string): Promise<SearchOutcome> => {\n stop()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n applyQuery(query, next)\n return p\n }\n return {\n setSearch: (query) => commit(toText(query)),\n flushSearch: () => applyNow(input()),\n cancelSearch: () => {\n scheduled = false\n stop()\n session?.abort()\n supersede()\n const s = ctx.getState()\n if (s?.status === 'pending' || s?.status === 'searching') {\n ctx.setState({ ...s, status: 'idle' })\n }\n },\n clearSearch: () => {\n void applyNow('')\n },\n }\n },\n rowModel: (indices, state, ctx) => {\n const output = step(indices, state, ctx)\n shown = { input: indices, output }\n return output\n },\n })\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC,SAAS,gBAAgB;AACzB,SAAS,yBAAyB;AAClC,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SAAS,uBAAuB;AAChC,OAAO;AACP,SAAS,qBAAqB;AAE9B,SAAS,yBAAyB;AAClC,SAAS,QAAQ,cAAc;AAC/B,SAAwB,kBAAkB;AAC1C;AAAA,EACE;AAAA,EAEA;AAAA,EAMA;AAAA,OAEK;AACP,SAAS,YAA8B,qBAAuC;AAC9E,SAAS,gCAAgC;AAEzC,gBAAgB,mBAAmB,wBAAwB;AA8E3D,IAAM,eAAe;AAErB,IAAM,aAAa,CAAC,MAAwB;AAC1C,MAAI,OAAO,MAAM,SAAU,QAAO,OAAO,SAAS,CAAC,KAAK,KAAK;AAC7D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W;AAC5B,qBAAW,YAAY,IAAI;AAC3B,iBAAO;AAAA,QACT;AAIA,YAAI,aAAa,cAAc,OAAO,aAAa,WAAW;AAC5D,gBAAM,MAAM,SAAS,QAAQ,CAAC;AAC9B,eAAK;AACL,iBAAO;AAAA,QACT;AACA,oBAAY;AACZ,cAAM,MAAM,SAAS,SAAS;AAC9B,eAAO;AAAA,MACT;AAEA,YAAM,WAAW,CAAC,SAAyC;AACzD,aAAK;AACL,cAAM,QAAQ,OAAO,IAAI;AACzB,uBAAe,KAAK;AACpB,cAAM,IAAI,QAAQ,KAAK;AACvB,mBAAW,OAAO,IAAI;AACtB,eAAO;AAAA,MACT;AACA,aAAO;AAAA,QACL,WAAW,CAAC,UAAU,OAAO,OAAO,KAAK,CAAC;AAAA,QAC1C,aAAa,MAAM,SAAS,MAAM,CAAC;AAAA,QACnC,cAAc,MAAM;AAClB,sBAAY;AACZ,eAAK;AACL,mBAAS,MAAM;AACf,oBAAU;AACV,gBAAM,IAAI,IAAI,SAAS;AACvB,cAAI,GAAG,WAAW,aAAa,GAAG,WAAW,aAAa;AACxD,gBAAI,SAAS,EAAE,GAAG,GAAG,QAAQ,OAAO,CAAC;AAAA,UACvC;AAAA,QACF;AAAA,QACA,aAAa,MAAM;AACjB,eAAK,SAAS,EAAE;AAAA,QAClB;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU,CAAC,SAAS,OAAO,QAAQ;AACjC,YAAM,SAAS,KAAK,SAAS,OAAO,GAAG;AACvC,cAAQ,EAAE,OAAO,SAAS,OAAO;AACjC,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":["matching","input"]}
1
+ {"version":3,"sources":["../../../src/features/search/search.ts"],"sourcesContent":["import { debounce } from 'kk-debounce/debounce'\nimport { debouncedSignal } from 'kk-debounce/debounceSignal'\nimport { throttle } from 'kk-debounce/throttle'\nimport { optionDiagnostics } from '../../catalog/codes'\nimport { defineOptions } from '../../catalog/options'\nimport { throwConfigError } from '../../diagnostics/build'\nimport { keepDiagnostics } from '../../diagnostics/catalog'\nimport '../../diagnostics/process-guard'\nimport { defineFeature } from '../../feature/define'\nimport type { AnyRow, RowModelContext } from '../../feature/types'\nimport { defineInterceptor } from '../../intercept/define'\nimport { runJob, sliced } from '../../pipeline/slice'\nimport { type DataMode, modeOption } from '../../source/mode'\nimport {\n APPLIED,\n type AsyncSearchFn,\n SEARCH_ENGINE,\n type SearchEngine,\n type SearchOutcome,\n type SearchSession,\n type SearchState,\n type SearchStatus,\n SUPERSEDED,\n type Waiter,\n} from './search-fn-brand'\nimport {\n buildIndex,\n type MatchConfig,\n probeExSearch,\n type Scores,\n type SearchIndex,\n} from './search-index'\nimport { skippedColumnDiagnostics } from './skipped-codes'\n\nkeepDiagnostics(optionDiagnostics, skippedColumnDiagnostics)\n\nexport type {\n AsyncSearchFn,\n SearchFn,\n SearchFnContext,\n SearchOutcome,\n SearchResult,\n SearchState,\n SearchStatus,\n} from './search-fn-brand'\n\nexport interface SearchApi {\n /** Sets `input` (and `query`, with the client's immediate typing strategy). */\n setSearch(query: string): Promise<SearchOutcome>\n /** Applies the current `input` now (Enter). */\n flushSearch(): Promise<SearchOutcome>\n /** Drops a pending (debounced) query; `input` and the applied `query` stay. */\n cancelSearch(): void\n /** Empties `input` and `query`: every row is shown again. */\n clearSearch(): void\n}\n\n/** A duration: milliseconds, or a kk-debounce temporal object (`{ seconds: 1, ms: 500 }`). */\nexport type SearchWait =\n | number\n | { hours?: number; minutes?: number; seconds?: number; ms?: number }\n\n/** When `query` follows `input` (§6.3). */\nexport interface SearchTyping {\n /**\n * `'immediate'` (default): every keystroke is applied. `'debounce'`: applied after `wait` of\n * quiet (kk-debounce `debouncedSignal`). `'throttle'`: at most once per `wait` (the first\n * keystroke at once, the latest one at the end of the window).\n */\n strategy?: 'immediate' | 'debounce' | 'throttle'\n /** Default 300 ms. Used by `'debounce'` and `'throttle'`. */\n wait?: SearchWait\n /**\n * Debounce only. `'trailing'` (default): apply after the burst. `'leading'`: apply the first\n * keystroke at once and drop the rest of the burst (`flushSearch()` applies them; otherwise\n * their `setSearch()` promises resolve `'superseded'` when the silence window ends).\n */\n behavior?: 'trailing' | 'leading'\n /** A trimmed input shorter than this is applied as an empty query (all rows). Default 0. */\n minLength?: number\n /** `'type'` (default): typing commits. `'enter'`: only `flushSearch()` commits. */\n commitOn?: 'type' | 'enter'\n}\n\n/** Client matching options (§6.3). */\nexport interface SearchOptions<T = AnyRow> {\n /** Minimum relevance (0–1, weight applied) to keep a row. Default `0.3`. */\n threshold?: number\n /** Maximum Levenshtein distance for a fuzzy match. Default `3`. */\n fuzzyMaxDistance?: number\n /** Default `false`. */\n caseSensitive?: boolean\n /**\n * Typing timing: when `query` follows `input`. Default: immediate; with `mode: 'server'`,\n * debounce 300 ms and `minLength` 2 (§6.3).\n */\n typing?: SearchTyping\n /**\n * `'server'`: the server matches `query` (its state goes to `options.fetcher`, or the app\n * fetches); core skips this step (§7.1). Default `'client'`.\n */\n mode?: DataMode\n /**\n * Replaces the built-in matching (§6.3): called with each applied non-blank query; while it runs\n * `status` is `'searching'` and the previous results stay. A failure keeps them too\n * (`DK_SEARCH_FAILED`, `status: 'error'`); an `AbortError` is not a failure. New data runs it\n * again for the applied query. Wrap it with `withSearchFn()` from `@datakable/core/search-async`\n * (client search does not bundle the async engine): `searchFn: withSearchFn(fn)`.\n */\n searchFn?: AsyncSearchFn<T>\n}\n\nconst DEFAULT_WAIT = 300\n\nconst isDuration = (v: unknown): boolean => {\n if (typeof v === 'number') return Number.isFinite(v) && v >= 0\n for (const k of ['hours', 'minutes', 'seconds', 'ms'] as const) {\n const n = (v as Record<string, unknown>)[k]\n if (n !== undefined && !(typeof n === 'number' && Number.isFinite(n) && n >= 0)) return false\n }\n return true\n}\n\nconst typingOptions = {\n strategy: { type: 'string', oneOf: ['immediate', 'debounce', 'throttle'] },\n wait: {\n type: ['number', 'object'],\n check: isDuration,\n expected: 'milliseconds >= 0 or { hours?, minutes?, seconds?, ms? } with values >= 0',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce' && o.strategy !== 'throttle'\n ? \"only the 'debounce' and 'throttle' strategies wait\"\n : undefined,\n },\n behavior: {\n type: 'string',\n oneOf: ['trailing', 'leading'],\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.commitOn === 'enter'\n ? \"commitOn is 'enter': only flushSearch() commits\"\n : o.strategy !== 'debounce'\n ? \"behavior applies to the 'debounce' strategy only\"\n : undefined,\n },\n minLength: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n },\n commitOn: { type: 'string', oneOf: ['type', 'enter'] },\n} as const\n\n/** Built-in matching options do nothing when `searchFn` matches. */\nconst matching = (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.searchFn === undefined ? undefined : 'searchFn replaces the built-in matching'\n\nconst searchOptions = {\n threshold: {\n type: 'number',\n check: (v: number) => v >= 0 && v <= 1,\n expected: 'a number from 0 to 1',\n noEffect: matching,\n },\n fuzzyMaxDistance: {\n type: 'number',\n check: (v: number) => Number.isInteger(v) && v >= 0,\n expected: 'a non-negative integer',\n noEffect: matching,\n },\n caseSensitive: { type: 'boolean', noEffect: matching },\n typing: { type: 'object', shape: typingOptions },\n mode: modeOption,\n searchFn: {\n type: 'function',\n check: (v: object) => typeof (v as { [SEARCH_ENGINE]?: unknown })[SEARCH_ENGINE] === 'function',\n expected:\n \"a function wrapped with withSearchFn() from '@datakable/core/search-async': \" +\n 'searchFn: withSearchFn(fn)',\n noEffect: (_: unknown, o: Readonly<Record<string, unknown>>) =>\n o.mode === 'server'\n ? \"mode is 'server': the server (options.fetcher, or the app) matches the query\"\n : undefined,\n },\n} as const\n\nconst settledSuperseded = () => Promise.resolve(SUPERSEDED)\n\nconst toText = (q: unknown): string => (q == null ? '' : String(q))\n\n/**\n * Global search (§6.3), client mode: fuzzy matching with `ex-search` on the formatted values of the\n * searchable columns (`search: weight`; when none declares one, every column of primitives at\n * weight 1, #27).\n *\n * - The matcher is built on the first non-blank query, once per data + columns (not per keystroke),\n * over the column cache's values; ex-search reads the projection `{ i, c0, c1, … }` one chunk of\n * rows at a time, built while matching and not kept (§9.3 memory); results map back by index.\n * - A blank or whitespace-only query keeps every row. The query is trimmed before matching.\n * - Rows are ordered by relevance (score descending, ties by original index); a sort stage after\n * search overrides that order.\n */\nexport const search = <T = AnyRow>(opts: SearchOptions<T> = {}) => {\n const config: MatchConfig = {\n threshold: opts.threshold ?? 0.3,\n fuzzyMaxDistance: opts.fuzzyMaxDistance ?? 3,\n caseSensitive: opts.caseSensitive ?? false,\n }\n /**\n * data → columns → the key of the projection job (`ctx.slice`, §9.1): its result is the index\n * (`null`: nothing searchable). Released with the data.\n */\n const indexes = new WeakMap<object, WeakMap<object, object>>()\n /** Job key → its finished index, also for runs without slicing (`explainRow` replays). */\n const built = new WeakMap<object, SearchIndex | null>()\n /** `ex-search` usable (probed once per feature instance, on the first build). */\n let useExSearch: boolean | undefined\n /** Columns references already reported as having no searchable column. */\n const reported = new WeakSet<object>()\n /** The last step: a slice change that keeps the query (typing, status) reuses its output. */\n let last:\n | { input: Uint32Array; query: string; index: SearchIndex; output: Uint32Array }\n | undefined\n /**\n * The scores of the last finished match (#95): a new data array re-matches only the rows whose\n * searched texts changed (search-index.ts `match`). 16 bytes per data row.\n */\n const memo: { scores?: Scores } = {}\n /** The key of the latest matching job (one query over one set of rows). */\n let matching: { rows: Uint32Array; index: SearchIndex; query: string; key: object } | undefined\n /** The step's last output and its input: the stand-in while sliced work runs (§9.1). */\n let shown: { input: Uint32Array; output: Uint32Array } | undefined\n const server = opts.mode === 'server'\n // Server defaults (§6.3): debounce, minLength 2. Filled in before the option check, so `wait` /\n // `behavior` alone are not reported as having no effect.\n const typing: SearchTyping = server\n ? { strategy: 'debounce', minLength: 2, ...opts.typing }\n : (opts.typing ?? {})\n const strategy = typing.commitOn === 'enter' ? 'enter' : (typing.strategy ?? 'immediate')\n const wait = typing.wait ?? DEFAULT_WAIT\n const minLength = typing.minLength ?? 0\n /** The query an input applies (a shorter trimmed input is no search). */\n const target = (input: string) => (input.trim().length < minLength ? '' : input)\n /** The async engine a `withSearchFn` searchFn brings (§6.3); `undefined` for client search. */\n const engine: SearchEngine | undefined = opts.searchFn?.[SEARCH_ENGINE]?.(opts.searchFn as never)\n // Never silent (§8.6): in production (no option validator) an unwrapped searchFn would be\n // ignored; in development the validator reports it at createTable(), with the full text.\n if (!(process.env.NODE_ENV !== \"production\") && opts.searchFn && !engine) {\n throwConfigError('DK_INVALID_OPTION', {\n path: 'searchFn',\n feature: 'search',\n expected: 'wrapped|withSearchFn|searchFn|search-async', // prose key (diagnostics/prose.ts)\n received: typeof opts.searchFn,\n suggestions: [],\n phase: 'init',\n })\n }\n /** Per table: ends its timers, searches and waiters on `table:destroy`. */\n const instances = new WeakMap<object, () => void>()\n /** Per table: finishes a restored `'pending'` / `'searching'` slice nothing works on (#22). */\n const resumes = new WeakMap<object, () => void>()\n /** Per table: after each `pipeline:run`, whether the step waited on sliced work (#6). */\n const ran = new WeakMap<object, (waited: boolean) => void>()\n /** The step of the run in progress returned a stand-in (sliced work runs, §9.1). */\n let waited = false\n\n /** The projection of (data, columns): built by a sliced job; `undefined` while it runs. */\n function indexFor(ctx: RowModelContext): SearchIndex | null | undefined {\n let byColumns = indexes.get(ctx.data)\n if (!byColumns) {\n byColumns = new WeakMap()\n indexes.set(ctx.data, byColumns)\n }\n let key = byColumns.get(ctx.columns)\n if (!key) {\n key = {}\n byColumns.set(ctx.columns, key)\n }\n const done = built.get(key)\n if (done !== undefined) return done\n useExSearch ??= probeExSearch(ctx.emit)\n const exSearch = useExSearch\n const index = sliced(ctx, key, () => buildIndex(ctx, config, exSearch))\n if (index !== undefined) built.set(key, index)\n return index\n }\n\n /** The ranked matches of `query` over `rows`: a sliced job; `undefined` while it runs. */\n function matchFor(\n ctx: RowModelContext,\n index: SearchIndex,\n rows: Uint32Array,\n query: string,\n ): Uint32Array | undefined {\n // A replay (`explainRow`) matches its one row at once, leaving the table's job alone.\n if (!ctx.slice) return runJob(() => index.match(rows, query))\n if (\n !matching ||\n matching.rows !== rows ||\n matching.index !== index ||\n matching.query !== query\n ) {\n matching = { rows, index, query, key: {} }\n }\n return sliced(ctx, matching.key, () => index.match(rows, query, memo))\n }\n\n /** While sliced work runs: the previous output for the same input, else the input. */\n const standIn = (indices: Uint32Array) => {\n waited = true\n return shown && shown.input === indices ? shown.output : indices\n }\n\n /** The client step (§6.3); the rowModel below records its output for {@link standIn}. */\n function step(indices: Uint32Array, state: SearchState, ctx: RowModelContext): Uint32Array {\n const query = typeof state?.query === 'string' ? state.query.trim() : ''\n // ex-search returns [] for a blank query: blank means \"no search\".\n if (query === '') return indices\n if (engine) return engine.step(indices, ctx)\n const index = indexFor(ctx)\n // The projection is still being built (time-sliced, §9.1): the row model is 'pending'.\n if (index === undefined) return standIn(indices)\n if (index === null) {\n if (!reported.has(ctx.columns)) {\n reported.add(ctx.columns)\n ctx.emit('DK_OPTION_NO_EFFECT', {\n path: 'query',\n feature: 'search',\n reason: 'not-searchable',\n once: false,\n })\n }\n return indices\n }\n if (last && last.input === indices && last.query === query && last.index === index) {\n return last.output\n }\n // Search runs after filters: only the input rows are matched (order is re-ranked anyway).\n const output = matchFor(ctx, index, indices, query)\n if (output === undefined) return standIn(indices)\n last = { input: indices, query, index, output }\n return output\n }\n\n return defineFeature({\n name: 'search',\n stage: 'search',\n mode: opts.mode ?? 'client',\n options: defineOptions(\n // The option validator runs in development only (§9.3): production drops the schema.\n (process.env.NODE_ENV !== \"production\") ? searchOptions : ({} as typeof searchOptions),\n server ? { ...opts, typing } : opts,\n ),\n initialState: (): SearchState => ({ input: '', query: '', status: 'idle' }),\n // After destroy(): still a promise, so `setSearch(q).then(…)` never throws.\n destroyedResult: { setSearch: settledSuperseded, flushSearch: settledSuperseded },\n interceptors: [\n defineInterceptor({\n name: 'search',\n on: ['table:destroy', 'pipeline:run', 'table:init', 'state:dispatch', 'table:setOptions'],\n intercept(ctx, next) {\n const table = ctx.table as object\n if (ctx.op === 'table:destroy') {\n instances.get(table)?.()\n return next()\n }\n if (ctx.op !== 'pipeline:run') {\n // A slice set from outside (initialState, setState, controlled state) is checked.\n const out = next()\n resumes.get(table)?.()\n return out\n }\n const prev = waited\n waited = false\n try {\n return engine ? engine.run(table, next) : next()\n } finally {\n const w = waited\n waited = prev\n ran.get(table)?.(w)\n }\n },\n }),\n ],\n createApi: (ctx): SearchApi => {\n const table = ctx.table as unknown as object\n /** Writes the slice; `true` when the state changed (a pipeline run follows). */\n const write = (input: string, query: string, status: SearchStatus, error?: unknown) => {\n const s = ctx.getState()\n if (\n status !== 'error' &&\n s?.input === input &&\n s.query === query &&\n s.status === status &&\n !('error' in s)\n ) {\n return false\n }\n ctx.setState(\n status === 'error' ? { input, query, status, error } : { input, query, status },\n )\n return ctx.getState() !== s\n }\n const applied = () => ctx.getState()?.query ?? ''\n const input = () => ctx.getState()?.input ?? ''\n\n // --- promise outcomes (§6.3): resolved when the query is applied, replaced, or failed ---\n /** Waiters of queries not handed to a search yet (typing, pending debounce, Enter mode). */\n let waiting: Waiter[] = []\n const waitFor = (query: string) =>\n new Promise<SearchOutcome>((resolve) => {\n waiting.push({ query, resolve })\n })\n /** A newer query replaces the waiting ones that differ from it. */\n const replaceWaiting = (query: string) => {\n if (waiting.length === 0) return\n const keep: Waiter[] = []\n for (const w of waiting) {\n if (w.query === query) keep.push(w)\n else w.resolve(SUPERSEDED)\n }\n waiting = keep\n }\n\n /** Takes the waiters of `query`; every other waiting one resolves `'superseded'`. */\n const claim = (query: string) => {\n replaceWaiting(query)\n const keep = waiting\n waiting = []\n return keep\n }\n /**\n * Waiters of the applied query until the row model reflects it (#6): sliced work (§9.1)\n * keeps the row model 'pending' after the query is written.\n */\n let held: Waiter[] = []\n /** The last run's step waited on sliced work. */\n let busy = false\n const release = (outcome: SearchOutcome) => {\n const list = held\n held = []\n for (const w of list) w.resolve(outcome)\n }\n /** Cancel, destroy: every waiter, waiting then held, resolves `'superseded'`. */\n const supersede = () => {\n held = [...waiting, ...held]\n waiting = []\n release(SUPERSEDED)\n }\n ran.set(table, (w) => {\n busy = w\n if (!w) release(APPLIED)\n })\n const session: SearchSession | undefined = engine?.session({\n ctx,\n write,\n applied,\n input,\n claim,\n })\n\n /** A typing commit waits on the strategy's timer (the slice shows `'pending'`). */\n let scheduled = false\n /**\n * Applies `query` (typing committed it, Enter, clear): at once, or with `searchFn` through a\n * request (the slice shows `'searching'`).\n */\n const applyQuery = (query: string, inp: string = input()) => {\n scheduled = false\n if (session?.apply(query, inp)) return\n if (held[0]?.query !== query) release(SUPERSEDED)\n held.push(...claim(query))\n // A changed state runs the pipeline (its end releases them); else the last run decides.\n if (!write(inp, query, 'idle') && !busy) release(APPLIED)\n }\n\n // --- typing (T17) ---\n /** Inside a strategy call: a synchronous apply is collected here (one update, not two). */\n let calling = false\n let appliedNow: string | undefined\n const apply = (query: string) => {\n if (calling) appliedNow = query\n else applyQuery(query)\n }\n const timer =\n strategy === 'debounce'\n ? debouncedSignal(applied, apply, wait, { behavior: typing.behavior ?? 'trailing' })\n : strategy === 'throttle'\n ? throttle(apply, wait)\n : undefined\n /** The slice status while nothing new is applied: a search may still be in flight. */\n const resting = (): SearchStatus => (session?.busy() ? 'searching' : 'idle')\n // A restored transient status (URL / storage restore through initialState, setState or a\n // controlled slice) that nothing is working on would stay forever (#22). 'pending' commits the\n // restored input (Enter mode: keeps it), 'searching' ends; a searchFn then runs for the query.\n resumes.set(table, () => {\n const s = ctx.getState()\n const pending = s?.status === 'pending'\n if (pending ? !scheduled : s?.status === 'searching' && !session?.busy()) {\n const inp = toText(s.input)\n write(inp, pending && strategy !== 'enter' ? target(inp) : toText(s.query), resting())\n }\n })\n\n /**\n * Leading debounce (#28): the keystrokes it drops settle `'superseded'` when the silence\n * window ends (it restarts with each keystroke, like kk-debounce's), unless `flushSearch()`\n * applies them first.\n */\n const drop = debounce(() => {\n const list = waiting\n waiting = []\n for (const w of list) w.resolve(SUPERSEDED)\n }, wait)\n /** Drops the scheduled commit (and the end of a leading silence window). */\n const stop = () => {\n timer?.cancel()\n drop.cancel()\n }\n\n instances.set(table, () => {\n stop()\n session?.destroy()\n supersede()\n })\n\n /** Typing: `input` at once; `query` through the strategy (`pending` while scheduled). */\n const commit = (next: string): Promise<SearchOutcome> => {\n const current = applied()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n if (strategy === 'enter') {\n write(next, current, resting())\n return p\n }\n if (!timer || query === current) {\n stop()\n applyQuery(query, next)\n return p\n }\n calling = true\n appliedNow = undefined\n try {\n timer(query)\n } finally {\n calling = false\n }\n if (appliedNow !== undefined) {\n applyQuery(appliedNow, next)\n return p\n }\n // A leading debounce drops the rest of the burst: nothing is scheduled to commit it (the\n // silence window keeps running; `flushSearch()` commits the input), and its promise settles\n // when the window ends.\n if (strategy === 'debounce' && typing.behavior === 'leading') {\n write(next, current, resting())\n drop()\n return p\n }\n scheduled = true\n write(next, current, 'pending')\n return p\n }\n /** Applies `input` now (Enter, clear): any scheduled commit is dropped. */\n const applyNow = (next: string): Promise<SearchOutcome> => {\n stop()\n const query = target(next)\n replaceWaiting(query)\n const p = waitFor(query)\n applyQuery(query, next)\n return p\n }\n return {\n setSearch: (query) => commit(toText(query)),\n flushSearch: () => applyNow(input()),\n cancelSearch: () => {\n scheduled = false\n stop()\n session?.abort()\n supersede()\n const s = ctx.getState()\n if (s?.status === 'pending' || s?.status === 'searching') {\n ctx.setState({ ...s, status: 'idle' })\n }\n },\n clearSearch: () => {\n void applyNow('')\n },\n }\n },\n rowModel: (indices, state, ctx) => {\n const output = step(indices, state, ctx)\n shown = { input: indices, output }\n return output\n },\n })\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC,SAAS,gBAAgB;AACzB,SAAS,yBAAyB;AAClC,SAAS,qBAAqB;AAC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SAAS,EAAE;AAAA,QAClB;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU,CAAC,SAAS,OAAO,QAAQ;AACjC,YAAM,SAAS,KAAK,SAAS,OAAO,GAAG;AACvC,cAAQ,EAAE,OAAO,SAAS,OAAO;AACjC,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":["matching","input"]}
package/dist/version.cjs CHANGED
@@ -25,7 +25,7 @@ __export(version_exports, {
25
25
  module.exports = __toCommonJS(version_exports);
26
26
 
27
27
  // package.json
28
- var version = "2.1.0";
28
+ var version = "2.1.1";
29
29
 
30
30
  // src/version.ts
31
31
  var VERSION = version;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../package.json"],"sourcesContent":["// Read from package.json at build time (the bundler inlines the one field), so a release never\n// ships a stale hard-coded version.\nimport { version } from '../package.json'\n\n/** The `@datakable/core` version (`context.package`, docs URLs, the global version registry). */\nexport const VERSION: string = version\n","{\n \"name\": \"@datakable/core\",\n \"version\": \"2.1.0\",\n \"description\": \"Headless, framework-agnostic core of DataKable — table state, sorting, filtering and types.\",\n \"license\": \"MIT\",\n \"author\": \"Supakit Kitjanabumrungsak\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Ink01101011/datakable.git\",\n \"directory\": \"packages/core\"\n },\n \"homepage\": \"https://github.com/Ink01101011/datakable#readme\",\n \"bugs\": \"https://github.com/Ink01101011/datakable/issues\",\n \"keywords\": [\n \"react\",\n \"react-table\",\n \"datatable\",\n \"data-table\",\n \"data-grid\",\n \"datagrid\",\n \"table\",\n \"typescript\",\n \"type-safe\",\n \"headless\",\n \"headless-ui\",\n \"zero-config\",\n \"sorting\",\n \"filtering\",\n \"search\",\n \"pagination\",\n \"framework-agnostic\",\n \"vanilla-js\",\n \"table-state\"\n ],\n \"type\": \"module\",\n \"sideEffects\": [\n \"./dist/messages/index.js\",\n \"./dist/messages/index.cjs\",\n \"./dist/diagnostics/process-guard.js\",\n \"./dist/diagnostics/process-guard.cjs\"\n ],\n \"engines\": {\n \"node\": \">=18.18.0\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"column-filters\": [\n \"./dist/column-filters.d.ts\"\n ],\n \"validity\": [\n \"./dist/validity.d.ts\"\n ],\n \"search\": [\n \"./dist/search.d.ts\"\n ],\n \"sorting\": [\n \"./dist/sorting.d.ts\"\n ],\n \"pagination\": [\n \"./dist/pagination.d.ts\"\n ],\n \"messages\": [\n \"./dist/messages.d.ts\"\n ],\n \"schema\": [\n \"./dist/schema.d.ts\"\n ],\n \"search-async\": [\n \"./dist/search-async.d.ts\"\n ],\n \"server\": [\n \"./dist/server.d.ts\"\n ]\n }\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./column-filters\": {\n \"import\": {\n \"types\": \"./dist/column-filters.d.ts\",\n \"default\": \"./dist/features/column-filters/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/column-filters.d.cts\",\n \"default\": \"./dist/features/column-filters/index.cjs\"\n }\n },\n \"./validity\": {\n \"import\": {\n \"types\": \"./dist/validity.d.ts\",\n \"default\": \"./dist/features/validity/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/validity.d.cts\",\n \"default\": \"./dist/features/validity/index.cjs\"\n }\n },\n \"./search\": {\n \"import\": {\n \"types\": \"./dist/search.d.ts\",\n \"default\": \"./dist/features/search/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/search.d.cts\",\n \"default\": \"./dist/features/search/index.cjs\"\n }\n },\n \"./sorting\": {\n \"import\": {\n \"types\": \"./dist/sorting.d.ts\",\n \"default\": \"./dist/features/sorting/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/sorting.d.cts\",\n \"default\": \"./dist/features/sorting/index.cjs\"\n }\n },\n \"./pagination\": {\n \"import\": {\n \"types\": \"./dist/pagination.d.ts\",\n \"default\": \"./dist/features/pagination/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/pagination.d.cts\",\n \"default\": \"./dist/features/pagination/index.cjs\"\n }\n },\n \"./messages\": {\n \"import\": {\n \"types\": \"./dist/messages.d.ts\",\n \"default\": \"./dist/messages/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/messages.d.cts\",\n \"default\": \"./dist/messages/index.cjs\"\n }\n },\n \"./schema\": {\n \"import\": {\n \"types\": \"./dist/schema.d.ts\",\n \"default\": \"./dist/ingest/schema-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/schema.d.cts\",\n \"default\": \"./dist/ingest/schema-entry.cjs\"\n }\n },\n \"./search-async\": {\n \"import\": {\n \"types\": \"./dist/search-async.d.ts\",\n \"default\": \"./dist/features/search/search-async-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/search-async.d.cts\",\n \"default\": \"./dist/features/search/search-async-entry.cjs\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/source/server-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.cts\",\n \"default\": \"./dist/source/server-entry.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node scripts/postbuild.mjs\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"check:pkg\": \"publint --strict && attw --pack . && node scripts/check-catalog.mjs\",\n \"check:catalog\": \"node scripts/check-catalog.mjs\"\n },\n \"dependencies\": {\n \"ex-search\": \"1.2.0\",\n \"exsorted\": \"1.2.3\",\n \"kk-debounce\": \"1.1.0\"\n },\n \"devDependencies\": {\n \"esbuild\": \"0.28.2\"\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEE,cAAW;;;ADGN,IAAM,UAAkB;","names":[]}
1
+ {"version":3,"sources":["../src/version.ts","../package.json"],"sourcesContent":["// Read from package.json at build time (the bundler inlines the one field), so a release never\n// ships a stale hard-coded version.\nimport { version } from '../package.json'\n\n/** The `@datakable/core` version (`context.package`, docs URLs, the global version registry). */\nexport const VERSION: string = version\n","{\n \"name\": \"@datakable/core\",\n \"version\": \"2.1.1\",\n \"description\": \"Headless, framework-agnostic core of DataKable — table state, sorting, filtering and types.\",\n \"license\": \"MIT\",\n \"author\": \"Supakit Kitjanabumrungsak\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Ink01101011/datakable.git\",\n \"directory\": \"packages/core\"\n },\n \"homepage\": \"https://github.com/Ink01101011/datakable#readme\",\n \"bugs\": \"https://github.com/Ink01101011/datakable/issues\",\n \"keywords\": [\n \"react\",\n \"react-table\",\n \"datatable\",\n \"data-table\",\n \"data-grid\",\n \"datagrid\",\n \"table\",\n \"typescript\",\n \"type-safe\",\n \"headless\",\n \"headless-ui\",\n \"zero-config\",\n \"sorting\",\n \"filtering\",\n \"search\",\n \"pagination\",\n \"framework-agnostic\",\n \"vanilla-js\",\n \"table-state\"\n ],\n \"type\": \"module\",\n \"sideEffects\": [\n \"./dist/messages/index.js\",\n \"./dist/messages/index.cjs\",\n \"./dist/diagnostics/process-guard.js\",\n \"./dist/diagnostics/process-guard.cjs\"\n ],\n \"engines\": {\n \"node\": \">=18.18.0\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"column-filters\": [\n \"./dist/column-filters.d.ts\"\n ],\n \"validity\": [\n \"./dist/validity.d.ts\"\n ],\n \"search\": [\n \"./dist/search.d.ts\"\n ],\n \"sorting\": [\n \"./dist/sorting.d.ts\"\n ],\n \"pagination\": [\n \"./dist/pagination.d.ts\"\n ],\n \"messages\": [\n \"./dist/messages.d.ts\"\n ],\n \"schema\": [\n \"./dist/schema.d.ts\"\n ],\n \"search-async\": [\n \"./dist/search-async.d.ts\"\n ],\n \"server\": [\n \"./dist/server.d.ts\"\n ]\n }\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./column-filters\": {\n \"import\": {\n \"types\": \"./dist/column-filters.d.ts\",\n \"default\": \"./dist/features/column-filters/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/column-filters.d.cts\",\n \"default\": \"./dist/features/column-filters/index.cjs\"\n }\n },\n \"./validity\": {\n \"import\": {\n \"types\": \"./dist/validity.d.ts\",\n \"default\": \"./dist/features/validity/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/validity.d.cts\",\n \"default\": \"./dist/features/validity/index.cjs\"\n }\n },\n \"./search\": {\n \"import\": {\n \"types\": \"./dist/search.d.ts\",\n \"default\": \"./dist/features/search/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/search.d.cts\",\n \"default\": \"./dist/features/search/index.cjs\"\n }\n },\n \"./sorting\": {\n \"import\": {\n \"types\": \"./dist/sorting.d.ts\",\n \"default\": \"./dist/features/sorting/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/sorting.d.cts\",\n \"default\": \"./dist/features/sorting/index.cjs\"\n }\n },\n \"./pagination\": {\n \"import\": {\n \"types\": \"./dist/pagination.d.ts\",\n \"default\": \"./dist/features/pagination/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/pagination.d.cts\",\n \"default\": \"./dist/features/pagination/index.cjs\"\n }\n },\n \"./messages\": {\n \"import\": {\n \"types\": \"./dist/messages.d.ts\",\n \"default\": \"./dist/messages/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/messages.d.cts\",\n \"default\": \"./dist/messages/index.cjs\"\n }\n },\n \"./schema\": {\n \"import\": {\n \"types\": \"./dist/schema.d.ts\",\n \"default\": \"./dist/ingest/schema-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/schema.d.cts\",\n \"default\": \"./dist/ingest/schema-entry.cjs\"\n }\n },\n \"./search-async\": {\n \"import\": {\n \"types\": \"./dist/search-async.d.ts\",\n \"default\": \"./dist/features/search/search-async-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/search-async.d.cts\",\n \"default\": \"./dist/features/search/search-async-entry.cjs\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/source/server-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.cts\",\n \"default\": \"./dist/source/server-entry.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node scripts/postbuild.mjs\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"check:pkg\": \"publint --strict && attw --pack . && node scripts/check-catalog.mjs\",\n \"check:catalog\": \"node scripts/check-catalog.mjs\"\n },\n \"dependencies\": {\n \"ex-search\": \"1.2.1\",\n \"exsorted\": \"1.2.3\",\n \"kk-debounce\": \"1.1.0\"\n },\n \"devDependencies\": {\n \"esbuild\": \"0.28.2\"\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEE,cAAW;;;ADGN,IAAM,UAAkB;","names":[]}
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "2.1.0";
2
+ var version = "2.1.1";
3
3
 
4
4
  // src/version.ts
5
5
  var VERSION = version;
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/version.ts"],"sourcesContent":["{\n \"name\": \"@datakable/core\",\n \"version\": \"2.1.0\",\n \"description\": \"Headless, framework-agnostic core of DataKable — table state, sorting, filtering and types.\",\n \"license\": \"MIT\",\n \"author\": \"Supakit Kitjanabumrungsak\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Ink01101011/datakable.git\",\n \"directory\": \"packages/core\"\n },\n \"homepage\": \"https://github.com/Ink01101011/datakable#readme\",\n \"bugs\": \"https://github.com/Ink01101011/datakable/issues\",\n \"keywords\": [\n \"react\",\n \"react-table\",\n \"datatable\",\n \"data-table\",\n \"data-grid\",\n \"datagrid\",\n \"table\",\n \"typescript\",\n \"type-safe\",\n \"headless\",\n \"headless-ui\",\n \"zero-config\",\n \"sorting\",\n \"filtering\",\n \"search\",\n \"pagination\",\n \"framework-agnostic\",\n \"vanilla-js\",\n \"table-state\"\n ],\n \"type\": \"module\",\n \"sideEffects\": [\n \"./dist/messages/index.js\",\n \"./dist/messages/index.cjs\",\n \"./dist/diagnostics/process-guard.js\",\n \"./dist/diagnostics/process-guard.cjs\"\n ],\n \"engines\": {\n \"node\": \">=18.18.0\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"column-filters\": [\n \"./dist/column-filters.d.ts\"\n ],\n \"validity\": [\n \"./dist/validity.d.ts\"\n ],\n \"search\": [\n \"./dist/search.d.ts\"\n ],\n \"sorting\": [\n \"./dist/sorting.d.ts\"\n ],\n \"pagination\": [\n \"./dist/pagination.d.ts\"\n ],\n \"messages\": [\n \"./dist/messages.d.ts\"\n ],\n \"schema\": [\n \"./dist/schema.d.ts\"\n ],\n \"search-async\": [\n \"./dist/search-async.d.ts\"\n ],\n \"server\": [\n \"./dist/server.d.ts\"\n ]\n }\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./column-filters\": {\n \"import\": {\n \"types\": \"./dist/column-filters.d.ts\",\n \"default\": \"./dist/features/column-filters/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/column-filters.d.cts\",\n \"default\": \"./dist/features/column-filters/index.cjs\"\n }\n },\n \"./validity\": {\n \"import\": {\n \"types\": \"./dist/validity.d.ts\",\n \"default\": \"./dist/features/validity/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/validity.d.cts\",\n \"default\": \"./dist/features/validity/index.cjs\"\n }\n },\n \"./search\": {\n \"import\": {\n \"types\": \"./dist/search.d.ts\",\n \"default\": \"./dist/features/search/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/search.d.cts\",\n \"default\": \"./dist/features/search/index.cjs\"\n }\n },\n \"./sorting\": {\n \"import\": {\n \"types\": \"./dist/sorting.d.ts\",\n \"default\": \"./dist/features/sorting/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/sorting.d.cts\",\n \"default\": \"./dist/features/sorting/index.cjs\"\n }\n },\n \"./pagination\": {\n \"import\": {\n \"types\": \"./dist/pagination.d.ts\",\n \"default\": \"./dist/features/pagination/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/pagination.d.cts\",\n \"default\": \"./dist/features/pagination/index.cjs\"\n }\n },\n \"./messages\": {\n \"import\": {\n \"types\": \"./dist/messages.d.ts\",\n \"default\": \"./dist/messages/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/messages.d.cts\",\n \"default\": \"./dist/messages/index.cjs\"\n }\n },\n \"./schema\": {\n \"import\": {\n \"types\": \"./dist/schema.d.ts\",\n \"default\": \"./dist/ingest/schema-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/schema.d.cts\",\n \"default\": \"./dist/ingest/schema-entry.cjs\"\n }\n },\n \"./search-async\": {\n \"import\": {\n \"types\": \"./dist/search-async.d.ts\",\n \"default\": \"./dist/features/search/search-async-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/search-async.d.cts\",\n \"default\": \"./dist/features/search/search-async-entry.cjs\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/source/server-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.cts\",\n \"default\": \"./dist/source/server-entry.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node scripts/postbuild.mjs\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"check:pkg\": \"publint --strict && attw --pack . && node scripts/check-catalog.mjs\",\n \"check:catalog\": \"node scripts/check-catalog.mjs\"\n },\n \"dependencies\": {\n \"ex-search\": \"1.2.0\",\n \"exsorted\": \"1.2.3\",\n \"kk-debounce\": \"1.1.0\"\n },\n \"devDependencies\": {\n \"esbuild\": \"0.28.2\"\n }\n}\n","// Read from package.json at build time (the bundler inlines the one field), so a release never\n// ships a stale hard-coded version.\nimport { version } from '../package.json'\n\n/** The `@datakable/core` version (`context.package`, docs URLs, the global version registry). */\nexport const VERSION: string = version\n"],"mappings":";AAEE,cAAW;;;ACGN,IAAM,UAAkB;","names":[]}
1
+ {"version":3,"sources":["../package.json","../src/version.ts"],"sourcesContent":["{\n \"name\": \"@datakable/core\",\n \"version\": \"2.1.1\",\n \"description\": \"Headless, framework-agnostic core of DataKable — table state, sorting, filtering and types.\",\n \"license\": \"MIT\",\n \"author\": \"Supakit Kitjanabumrungsak\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Ink01101011/datakable.git\",\n \"directory\": \"packages/core\"\n },\n \"homepage\": \"https://github.com/Ink01101011/datakable#readme\",\n \"bugs\": \"https://github.com/Ink01101011/datakable/issues\",\n \"keywords\": [\n \"react\",\n \"react-table\",\n \"datatable\",\n \"data-table\",\n \"data-grid\",\n \"datagrid\",\n \"table\",\n \"typescript\",\n \"type-safe\",\n \"headless\",\n \"headless-ui\",\n \"zero-config\",\n \"sorting\",\n \"filtering\",\n \"search\",\n \"pagination\",\n \"framework-agnostic\",\n \"vanilla-js\",\n \"table-state\"\n ],\n \"type\": \"module\",\n \"sideEffects\": [\n \"./dist/messages/index.js\",\n \"./dist/messages/index.cjs\",\n \"./dist/diagnostics/process-guard.js\",\n \"./dist/diagnostics/process-guard.cjs\"\n ],\n \"engines\": {\n \"node\": \">=18.18.0\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"typesVersions\": {\n \"*\": {\n \"column-filters\": [\n \"./dist/column-filters.d.ts\"\n ],\n \"validity\": [\n \"./dist/validity.d.ts\"\n ],\n \"search\": [\n \"./dist/search.d.ts\"\n ],\n \"sorting\": [\n \"./dist/sorting.d.ts\"\n ],\n \"pagination\": [\n \"./dist/pagination.d.ts\"\n ],\n \"messages\": [\n \"./dist/messages.d.ts\"\n ],\n \"schema\": [\n \"./dist/schema.d.ts\"\n ],\n \"search-async\": [\n \"./dist/search-async.d.ts\"\n ],\n \"server\": [\n \"./dist/server.d.ts\"\n ]\n }\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./column-filters\": {\n \"import\": {\n \"types\": \"./dist/column-filters.d.ts\",\n \"default\": \"./dist/features/column-filters/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/column-filters.d.cts\",\n \"default\": \"./dist/features/column-filters/index.cjs\"\n }\n },\n \"./validity\": {\n \"import\": {\n \"types\": \"./dist/validity.d.ts\",\n \"default\": \"./dist/features/validity/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/validity.d.cts\",\n \"default\": \"./dist/features/validity/index.cjs\"\n }\n },\n \"./search\": {\n \"import\": {\n \"types\": \"./dist/search.d.ts\",\n \"default\": \"./dist/features/search/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/search.d.cts\",\n \"default\": \"./dist/features/search/index.cjs\"\n }\n },\n \"./sorting\": {\n \"import\": {\n \"types\": \"./dist/sorting.d.ts\",\n \"default\": \"./dist/features/sorting/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/sorting.d.cts\",\n \"default\": \"./dist/features/sorting/index.cjs\"\n }\n },\n \"./pagination\": {\n \"import\": {\n \"types\": \"./dist/pagination.d.ts\",\n \"default\": \"./dist/features/pagination/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/pagination.d.cts\",\n \"default\": \"./dist/features/pagination/index.cjs\"\n }\n },\n \"./messages\": {\n \"import\": {\n \"types\": \"./dist/messages.d.ts\",\n \"default\": \"./dist/messages/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/messages.d.cts\",\n \"default\": \"./dist/messages/index.cjs\"\n }\n },\n \"./schema\": {\n \"import\": {\n \"types\": \"./dist/schema.d.ts\",\n \"default\": \"./dist/ingest/schema-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/schema.d.cts\",\n \"default\": \"./dist/ingest/schema-entry.cjs\"\n }\n },\n \"./search-async\": {\n \"import\": {\n \"types\": \"./dist/search-async.d.ts\",\n \"default\": \"./dist/features/search/search-async-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/search-async.d.cts\",\n \"default\": \"./dist/features/search/search-async-entry.cjs\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/source/server-entry.js\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.cts\",\n \"default\": \"./dist/source/server-entry.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node scripts/postbuild.mjs\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"check:pkg\": \"publint --strict && attw --pack . && node scripts/check-catalog.mjs\",\n \"check:catalog\": \"node scripts/check-catalog.mjs\"\n },\n \"dependencies\": {\n \"ex-search\": \"1.2.1\",\n \"exsorted\": \"1.2.3\",\n \"kk-debounce\": \"1.1.0\"\n },\n \"devDependencies\": {\n \"esbuild\": \"0.28.2\"\n }\n}\n","// Read from package.json at build time (the bundler inlines the one field), so a release never\n// ships a stale hard-coded version.\nimport { version } from '../package.json'\n\n/** The `@datakable/core` version (`context.package`, docs URLs, the global version registry). */\nexport const VERSION: string = version\n"],"mappings":";AAEE,cAAW;;;ACGN,IAAM,UAAkB;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datakable/core",
3
- "version": "2.1.0",
3
+ "version": "2.1.1",
4
4
  "description": "Headless, framework-agnostic core of DataKable — table state, sorting, filtering and types.",
5
5
  "license": "MIT",
6
6
  "author": "Supakit Kitjanabumrungsak",
@@ -183,7 +183,7 @@
183
183
  "dist"
184
184
  ],
185
185
  "dependencies": {
186
- "ex-search": "1.2.0",
186
+ "ex-search": "1.2.1",
187
187
  "exsorted": "1.2.3",
188
188
  "kk-debounce": "1.1.0"
189
189
  },