@wgtechlabs/mdd-engine 0.1.0-dev.b4f443b → 0.1.0-pr.04f8fe2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -85,6 +85,10 @@ import { search } from '@wgtechlabs/mdd-engine/search';
85
85
  const index = createSearchIndex(result.site);
86
86
  const restored = JSON.parse(JSON.stringify(index));
87
87
  console.log(search(restored, 'installation', { limit: 10 }));
88
+ // Multiple heading hits, breadcrumbs, and ranges for UI highlights.
89
+ console.log(search(restored, 'instalation', {
90
+ mode: 'sections', fuzzy: true, limit: 8,
91
+ }));
88
92
  // [{ title, url, section?, excerpt, score }]
89
93
  ```
90
94
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { CompileOptions, CompileResult } from "./types.js";
2
- export { type SearchIndex, type SearchOptions, type SearchPage, type SearchResult, type SearchSection, search, validateSearchIndex, } from "./search.js";
2
+ export { type SearchIndex, type SearchMatch, type SearchOptions, type SearchPage, type SearchResult, type SearchSection, search, validateSearchIndex, } from "./search.js";
3
3
  export { createSearchIndex } from "./search-index.js";
4
4
  export type { Asset, CompileOptions, CompileResult, Diagnostic, Footer, Heading, Metadata, NavigationItem, Page, Site, SocialLink, Theme, } from "./types.js";
5
5
  /** Compile a local checkout; never fetch repositories, execute author code, or emit files. */
@@ -7,8 +7,9 @@ import { transformAlerts } from "./alerts.js";
7
7
  import { validateSearchIndex, } from "./search.js";
8
8
  const parser = unified().use(remarkParse).use(remarkGfm);
9
9
  const blockTypes = new Set(["paragraph", "code", "tableCell", "listItem"]);
10
- function indexPage(page) {
10
+ function indexPage(page, breadcrumbs) {
11
11
  const sections = [{ title: "", url: page.url, text: "" }];
12
+ const ancestors = [];
12
13
  let headingIndex = 0;
13
14
  const chunks = [[]];
14
15
  const tree = parser.parse(page.markdown);
@@ -23,11 +24,20 @@ function indexPage(page) {
23
24
  heading.depth !== node.depth) {
24
25
  throw new TypeError("Search indexing requires matching compiled Markdown and headings.");
25
26
  }
27
+ while (ancestors.length &&
28
+ (ancestors.at(-1)?.depth ?? 0) >= heading.depth)
29
+ ancestors.pop();
26
30
  sections.push({
27
31
  title: heading.text,
28
32
  url: `${page.url}#${encodeURIComponent(heading.id)}`,
29
33
  text: "",
34
+ breadcrumbs: ancestors
35
+ .filter((ancestor) => !(ancestor.depth === 1 &&
36
+ ancestor.text.normalize("NFKC").toLowerCase() ===
37
+ page.title.normalize("NFKC").toLowerCase()))
38
+ .map((ancestor) => ancestor.text),
30
39
  });
40
+ ancestors.push(heading);
31
41
  chunks.push([]);
32
42
  return SKIP;
33
43
  }
@@ -55,12 +65,33 @@ function indexPage(page) {
55
65
  url: page.url,
56
66
  title: page.title,
57
67
  description: page.description ?? "",
68
+ breadcrumbs,
58
69
  sections,
59
70
  };
60
71
  }
61
72
  /** Build only from successfully compiled pages; no source paths or HTML are indexed. */
62
73
  export function createSearchIndex(site) {
63
- const index = { version: 1, pages: site.pages.map(indexPage) };
74
+ const navigation = new Map();
75
+ const pending = site.navigation.map((item) => ({
76
+ item,
77
+ ancestors: [],
78
+ }));
79
+ while (pending.length) {
80
+ const entry = pending.pop();
81
+ if (!entry)
82
+ break;
83
+ const { item, ancestors } = entry;
84
+ if (ancestors.length > 64)
85
+ throw new TypeError("Search navigation exceeds 64 ancestor labels.");
86
+ if (item.url)
87
+ navigation.set(item.url, ancestors);
88
+ for (const child of item.children ?? [])
89
+ pending.push({ item: child, ancestors: [...ancestors, item.title] });
90
+ }
91
+ const index = {
92
+ version: 1,
93
+ pages: site.pages.map((page) => indexPage(page, navigation.get(page.url) ?? [])),
94
+ };
64
95
  index.pages.sort((a, b) => (a.url < b.url ? -1 : a.url > b.url ? 1 : 0));
65
96
  validateSearchIndex(index);
66
97
  return index;
package/dist/search.d.ts CHANGED
@@ -7,6 +7,8 @@ export interface SearchPage {
7
7
  url: string;
8
8
  title: string;
9
9
  description: string;
10
+ /** Navigation ancestor labels, excluding this page's own label. */
11
+ breadcrumbs?: string[];
10
12
  sections: SearchSection[];
11
13
  }
12
14
  export interface SearchSection {
@@ -14,20 +16,37 @@ export interface SearchSection {
14
16
  title: string;
15
17
  url: string;
16
18
  text: string;
19
+ /** Ancestor headings, excluding this heading and a duplicate page-title H1. */
20
+ breadcrumbs?: string[];
17
21
  }
18
22
  export interface SearchOptions {
19
23
  /** Maximum results, from 0 to 100. Defaults to 10. */
20
24
  limit?: number;
25
+ /** Defaults to one result per page; sections returns independent heading hits. */
26
+ mode?: "pages" | "sections";
27
+ /** Allow one single-edit query correction per result. Requires sections mode. */
28
+ fuzzy?: boolean;
21
29
  }
30
+ /** UTF-16 offsets into the original displayed field; end is exclusive. */
31
+ export type SearchMatch = [start: number, end: number];
22
32
  export interface SearchResult {
33
+ kind: "page" | "section";
23
34
  title: string;
24
35
  url: string;
36
+ pageUrl: string;
37
+ breadcrumbs: string[];
25
38
  /** Present when the destination is a compiled heading. */
26
39
  section?: string;
27
40
  excerpt: string;
28
41
  score: number;
42
+ matches: {
43
+ title: SearchMatch[];
44
+ section: SearchMatch[];
45
+ excerpt: SearchMatch[];
46
+ breadcrumbs: SearchMatch[][];
47
+ };
29
48
  }
30
49
  /** Validate deserialized data before any result can become a link. */
31
50
  export declare function validateSearchIndex(value: unknown): asserts value is SearchIndex;
32
- /** Return at most one hit per page, without filesystem, network, or DOM access. */
51
+ /** Query without filesystem, network, or DOM access; page mode preserves legacy ranking. */
33
52
  export declare function search(index: SearchIndex, query: string, options?: SearchOptions): SearchResult[];
package/dist/search.js CHANGED
@@ -1,6 +1,12 @@
1
1
  function record(value) {
2
2
  return value !== null && typeof value === "object" && !Array.isArray(value);
3
3
  }
4
+ function breadcrumbs(value, maximum) {
5
+ return (value === undefined ||
6
+ (Array.isArray(value) &&
7
+ value.length <= maximum &&
8
+ value.every((label) => typeof label === "string")));
9
+ }
4
10
  function pageUrl(value) {
5
11
  if (typeof value !== "string" ||
6
12
  !value.startsWith("/") ||
@@ -48,6 +54,7 @@ export function validateSearchIndex(value) {
48
54
  urls.has(page.url) ||
49
55
  typeof page.title !== "string" ||
50
56
  typeof page.description !== "string" ||
57
+ !breadcrumbs(page.breadcrumbs, 64) ||
51
58
  !Array.isArray(page.sections))
52
59
  throw new TypeError("Invalid search index page.");
53
60
  urls.add(page.url);
@@ -57,7 +64,8 @@ export function validateSearchIndex(value) {
57
64
  !sectionUrl(section.url, page.url) ||
58
65
  sections.has(section.url) ||
59
66
  typeof section.title !== "string" ||
60
- typeof section.text !== "string")
67
+ typeof section.text !== "string" ||
68
+ !breadcrumbs(section.breadcrumbs, 6))
61
69
  throw new TypeError("Invalid search index section.");
62
70
  sections.add(section.url);
63
71
  }
@@ -70,29 +78,151 @@ function normalize(value) {
70
78
  .replace(/[^\p{L}\p{N}\p{M}_]+/gu, " ")
71
79
  .trim();
72
80
  }
73
- function excerpt(value) {
74
- const characters = Array.from(value.replace(/\s+/gu, " ").trim());
75
- return characters.length > 160
76
- ? `${characters.slice(0, 159).join("")}…`
77
- : characters.join("");
81
+ function contains(value, pattern) {
82
+ return pattern.whole
83
+ ? ` ${value} `.includes(` ${pattern.text} `)
84
+ : value.includes(pattern.text);
78
85
  }
79
- /** Return at most one hit per page, without filesystem, network, or DOM access. */
80
- export function search(index, query, options = {}) {
81
- validateSearchIndex(index);
82
- const limit = options.limit ?? 10;
83
- if (!Number.isInteger(limit) || limit < 0 || limit > 100) {
84
- throw new RangeError("Search limit must be an integer from 0 to 100.");
86
+ function mergeRanges(ranges) {
87
+ ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
88
+ const merged = [];
89
+ for (const range of ranges) {
90
+ const previous = merged.at(-1);
91
+ if (previous && range[0] <= previous[1])
92
+ previous[1] = Math.max(previous[1], range[1]);
93
+ else
94
+ merged.push([...range]);
85
95
  }
86
- if (typeof query !== "string")
87
- throw new TypeError("Search query must be a string.");
88
- if (query.length > 512)
89
- throw new RangeError("Search query must not exceed 512 characters.");
90
- const terms = [...new Set(normalize(query).split(" ").filter(Boolean))];
91
- const phrase = terms.join(" ");
92
- if (terms.length > 32)
93
- throw new RangeError("Search query must not exceed 32 unique terms.");
94
- if (!terms.length || !limit)
96
+ return merged;
97
+ }
98
+ /** Map normalized matches to complete original graphemes, including NFKC expansions. */
99
+ function matchRanges(value, patterns, firstOnly = false) {
100
+ const normalized = value.normalize("NFKC").toLowerCase();
101
+ const found = [];
102
+ for (const pattern of patterns) {
103
+ let offset = 0;
104
+ while (offset < normalized.length) {
105
+ const start = normalized.indexOf(pattern.text, offset);
106
+ if (start < 0)
107
+ break;
108
+ const end = start + pattern.text.length;
109
+ // Unicode-aware boundaries avoid splitting an astral letter at a token edge.
110
+ const before = normalized.slice(0, start).match(/[\p{L}\p{N}\p{M}_]$/u);
111
+ const after = /^[\p{L}\p{N}\p{M}_]/u.test(normalized.slice(end));
112
+ if (!pattern.whole || (!before && !after)) {
113
+ found.push([start, end]);
114
+ if (firstOnly)
115
+ break;
116
+ }
117
+ offset = start + 1;
118
+ }
119
+ }
120
+ let ranges = mergeRanges(found);
121
+ if (!ranges.length)
95
122
  return [];
123
+ if (firstOnly)
124
+ ranges = ranges.slice(0, 1);
125
+ const groups = [];
126
+ for (const { segment, index } of new Intl.Segmenter(undefined, {
127
+ granularity: "grapheme",
128
+ }).segment(value)) {
129
+ let group = {
130
+ text: segment.normalize("NFKC"),
131
+ start: index,
132
+ end: index + segment.length,
133
+ };
134
+ // NFKC can combine adjacent graphemes, e.g. compatibility Hangul ㄱㅏ → 가.
135
+ while (groups.length) {
136
+ const previous = groups.at(-1);
137
+ if (!previous)
138
+ break;
139
+ const joined = previous.text + group.text;
140
+ const combined = joined.normalize("NFKC");
141
+ if (combined === joined)
142
+ break;
143
+ groups.pop();
144
+ group = { text: combined, start: previous.start, end: group.end };
145
+ }
146
+ groups.push(group);
147
+ }
148
+ // Whole-field lowercase retains contextual letters such as final sigma.
149
+ // Per-group lowercase supplies only lengths, including expansions like İ.
150
+ const mapped = [];
151
+ let offset = 0;
152
+ let rangeIndex = 0;
153
+ let originalStart = 0;
154
+ for (const group of groups) {
155
+ const next = offset + group.text.toLowerCase().length;
156
+ let range = ranges[rangeIndex];
157
+ while (range && range[0] < next) {
158
+ if (range[0] >= offset)
159
+ originalStart = group.start;
160
+ if (range[1] > next)
161
+ break;
162
+ mapped.push([originalStart, group.end]);
163
+ range = ranges[++rangeIndex];
164
+ }
165
+ if (!range)
166
+ break;
167
+ offset = next;
168
+ }
169
+ return mergeRanges(mapped);
170
+ }
171
+ function excerpt(value, patterns) {
172
+ const text = value.replace(/\s+/gu, " ").trim();
173
+ const characters = Array.from(text);
174
+ if (characters.length <= 160)
175
+ return text;
176
+ const match = matchRanges(text, patterns, true)[0];
177
+ const matchStart = match ? Array.from(text.slice(0, match[0])).length : 0;
178
+ const matchLength = match
179
+ ? Array.from(text.slice(match[0], match[1])).length
180
+ : 0;
181
+ // Reserve room for both ellipses and the matched term before adding context.
182
+ const context = Math.min(40, Math.max(0, 158 - matchLength));
183
+ const start = Math.min(Math.max(0, matchStart - context), characters.length - 159);
184
+ let end = Math.min(characters.length, start + 160 - (start > 0 ? 1 : 0));
185
+ if (end < characters.length)
186
+ end--;
187
+ const startOffset = characters.slice(0, start).join("").length;
188
+ const endOffset = characters.slice(0, end).join("").length;
189
+ // Move clipped edges inward to complete graphemes without exceeding the cap.
190
+ let safeStart = text.length;
191
+ let safeEnd = 0;
192
+ for (const { segment, index } of new Intl.Segmenter(undefined, {
193
+ granularity: "grapheme",
194
+ }).segment(text)) {
195
+ if (index >= startOffset && safeStart === text.length)
196
+ safeStart = index;
197
+ if (index + segment.length <= endOffset)
198
+ safeEnd = index + segment.length;
199
+ if (index >= endOffset)
200
+ break;
201
+ }
202
+ return `${safeStart > 0 ? "…" : ""}${text.slice(safeStart, safeEnd)}${safeEnd < text.length ? "…" : ""}`;
203
+ }
204
+ function candidateUrl(candidate) {
205
+ return candidate.destination?.url ?? candidate.page.url;
206
+ }
207
+ function compareCandidates(a, b) {
208
+ const aUrl = candidateUrl(a);
209
+ const bUrl = candidateUrl(b);
210
+ return (b.rank - a.rank ||
211
+ b.score - a.score ||
212
+ (aUrl < bUrl ? -1 : aUrl > bUrl ? 1 : 0));
213
+ }
214
+ function sourceText(sources, patterns, fallback) {
215
+ return (sources.find((text) => {
216
+ const normalized = normalize(text);
217
+ return patterns.some((pattern) => contains(normalized, pattern));
218
+ }) ??
219
+ sources.find((text) => text) ??
220
+ fallback);
221
+ }
222
+ /** Preserve page-mode weighting, cross-section coverage, and destination selection. */
223
+ function pageCandidates(index, terms) {
224
+ const phrase = terms.join(" ");
225
+ const patterns = terms.map((text) => ({ text }));
96
226
  const results = [];
97
227
  for (const page of index.pages) {
98
228
  const title = normalize(page.title);
@@ -131,23 +261,217 @@ export function search(index, query, options = {}) {
131
261
  // A stable sort preserves document order when multiple sections tie.
132
262
  matches.sort((a, b) => b.score - a.score);
133
263
  const best = matches[0]?.section;
134
- const destination = metadataMatch ? undefined : best;
135
264
  results.push({
136
- title: page.title,
137
- url: destination?.url ?? page.url,
138
- ...(destination?.title ? { section: destination.title } : {}),
139
- excerpt: excerpt(best?.text ||
140
- page.description ||
141
- page.sections.find((section) => section.text)?.text ||
142
- page.title),
265
+ page,
266
+ destination: metadataMatch ? undefined : best,
267
+ source: sourceText([
268
+ best?.text ?? "",
269
+ page.description,
270
+ ...page.sections.map((section) => section.text),
271
+ ], patterns, page.title),
143
272
  score: weights.reduce((sum, weight) => sum + weight, 0) +
144
273
  (title === phrase
145
274
  ? 24
146
275
  : sections.some((section) => section.title === phrase)
147
276
  ? 12
148
277
  : 0),
278
+ rank: 0,
279
+ patterns,
149
280
  });
150
281
  }
151
- results.sort((a, b) => b.score - a.score || (a.url < b.url ? -1 : a.url > b.url ? 1 : 0));
152
- return results.slice(0, limit);
282
+ return results;
283
+ }
284
+ /** Single insertion, deletion, substitution, or adjacent transposition, on code points. */
285
+ function singleEdit(query, token) {
286
+ if (token.length > 66)
287
+ return false;
288
+ const text = Array.from(token);
289
+ if (Math.abs(query.length - text.length) > 1)
290
+ return false;
291
+ let start = 0;
292
+ while (start < query.length && query[start] === text[start])
293
+ start++;
294
+ if (start === Math.min(query.length, text.length))
295
+ return true;
296
+ if (query.length === text.length) {
297
+ if (query.slice(start + 1).join("") === text.slice(start + 1).join(""))
298
+ return true;
299
+ return (query[start] === text[start + 1] &&
300
+ query[start + 1] === text[start] &&
301
+ query.slice(start + 2).join("") === text.slice(start + 2).join(""));
302
+ }
303
+ return query.length > text.length
304
+ ? query.slice(start + 1).join("") === text.slice(start).join("")
305
+ : query.slice(start).join("") === text.slice(start + 1).join("");
306
+ }
307
+ function fieldScore(fields, pattern) {
308
+ return Math.max(0, ...fields
309
+ .filter((field) => contains(field.text, pattern))
310
+ .map((field) => field.weight));
311
+ }
312
+ function matchFields(fields, terms, fuzzy, required = []) {
313
+ const patterns = terms.map((text) => ({ text }));
314
+ const weights = patterns.map((pattern) => fieldScore(fields, pattern));
315
+ const missing = weights.flatMap((weight, index) => (weight ? [] : [index]));
316
+ if (!missing.length)
317
+ return {
318
+ patterns,
319
+ score: weights.reduce((a, b) => a + b, 0),
320
+ corrected: false,
321
+ };
322
+ const missingIndex = missing[0];
323
+ if (!fuzzy || missing.length !== 1 || missingIndex === undefined)
324
+ return;
325
+ const query = Array.from(terms[missingIndex] ?? "");
326
+ if (query.length < 4 || query.length > 32)
327
+ return;
328
+ const needsOwnCorrection = required.length > 0 &&
329
+ !patterns.some((pattern) => fieldScore(required, pattern));
330
+ let correction;
331
+ let correctionWeight = 0;
332
+ for (const field of fields) {
333
+ if (field.weight < correctionWeight)
334
+ continue;
335
+ for (const token of field.text.split(" ")) {
336
+ if (singleEdit(query, token) &&
337
+ (!needsOwnCorrection ||
338
+ fieldScore(required, { text: token, whole: true }) > 0) &&
339
+ (field.weight > correctionWeight ||
340
+ correction === undefined ||
341
+ token < correction)) {
342
+ correction = token;
343
+ correctionWeight = field.weight;
344
+ }
345
+ }
346
+ }
347
+ if (!correction)
348
+ return;
349
+ patterns[missingIndex] = { text: correction, whole: true };
350
+ weights[missingIndex] = correctionWeight;
351
+ return {
352
+ patterns,
353
+ score: weights.reduce((a, b) => a + b, 0),
354
+ corrected: true,
355
+ };
356
+ }
357
+ /** Score only page metadata plus a single coherent section, never sibling bodies. */
358
+ function sectionCandidates(index, terms, fuzzy) {
359
+ const phrase = terms.join(" ");
360
+ const results = [];
361
+ for (const page of index.pages) {
362
+ const title = normalize(page.title);
363
+ const metadata = [
364
+ { text: title, weight: 8 },
365
+ { text: normalize(page.description), weight: 2 },
366
+ ];
367
+ const pageMatch = matchFields(metadata, terms, fuzzy);
368
+ let pageCandidate;
369
+ if (pageMatch) {
370
+ const exact = title === phrase;
371
+ pageCandidate = {
372
+ page,
373
+ source: sourceText([page.description, ...page.sections.map((section) => section.text)], pageMatch.patterns, page.title),
374
+ score: pageMatch.score + (exact ? 24 : 0),
375
+ rank: pageMatch.corrected ? 0 : exact ? 2 : 1,
376
+ patterns: pageMatch.patterns,
377
+ };
378
+ }
379
+ for (const section of page.sections) {
380
+ const heading = normalize(section.title);
381
+ const body = normalize(section.text);
382
+ const ownFields = [
383
+ { text: heading, weight: 4 },
384
+ { text: body, weight: 1 },
385
+ ];
386
+ const match = matchFields([...metadata, ...ownFields], terms, fuzzy, ownFields);
387
+ if (!match?.patterns.some((pattern) => fieldScore(ownFields, pattern)))
388
+ continue;
389
+ // Repeated page headings without their own matching body add no useful destination.
390
+ if (pageMatch &&
391
+ heading === title &&
392
+ !match.patterns.some((pattern) => contains(body, pattern)))
393
+ continue;
394
+ const exact = heading === phrase;
395
+ const candidate = {
396
+ page,
397
+ destination: section.url === page.url ? undefined : section,
398
+ source: sourceText([section.text, page.description], match.patterns, section.title || page.title),
399
+ score: match.score + (exact ? 12 : 0),
400
+ rank: match.corrected ? 0 : exact ? 2 : 1,
401
+ patterns: match.patterns,
402
+ };
403
+ if (candidate.destination)
404
+ results.push(candidate);
405
+ else if (!pageCandidate ||
406
+ compareCandidates(candidate, pageCandidate) < 0)
407
+ pageCandidate = candidate;
408
+ }
409
+ if (pageCandidate)
410
+ results.push(pageCandidate);
411
+ }
412
+ return results;
413
+ }
414
+ function displayResult(candidate) {
415
+ const { page, destination, patterns } = candidate;
416
+ const isSection = destination !== undefined && destination.url !== page.url;
417
+ const trail = isSection
418
+ ? [
419
+ ...(page.breadcrumbs ?? []),
420
+ page.title,
421
+ ...(destination.breadcrumbs ?? []),
422
+ ]
423
+ : [...(page.breadcrumbs ?? [])];
424
+ const snippet = excerpt(candidate.source, patterns);
425
+ return {
426
+ kind: isSection ? "section" : "page",
427
+ title: page.title,
428
+ pageUrl: page.url,
429
+ url: candidateUrl(candidate),
430
+ ...(destination?.title ? { section: destination.title } : {}),
431
+ breadcrumbs: trail,
432
+ excerpt: snippet,
433
+ score: candidate.score,
434
+ matches: {
435
+ title: matchRanges(page.title, patterns),
436
+ section: matchRanges(destination?.title ?? "", patterns),
437
+ excerpt: matchRanges(snippet, patterns),
438
+ breadcrumbs: trail.map((label) => matchRanges(label, patterns)),
439
+ },
440
+ };
441
+ }
442
+ /** Query without filesystem, network, or DOM access; page mode preserves legacy ranking. */
443
+ export function search(index, query, options = {}) {
444
+ validateSearchIndex(index);
445
+ if (options === null || typeof options !== "object" || Array.isArray(options))
446
+ throw new TypeError("Search options must be an object.");
447
+ const limit = options.limit ?? 10;
448
+ const mode = options.mode === undefined ? "pages" : options.mode;
449
+ const fuzzy = options.fuzzy === undefined ? false : options.fuzzy;
450
+ if (!Number.isInteger(limit) || limit < 0 || limit > 100)
451
+ throw new RangeError("Search limit must be an integer from 0 to 100.");
452
+ if (mode !== "pages" && mode !== "sections")
453
+ throw new RangeError("Search mode must be pages or sections.");
454
+ if (typeof fuzzy !== "boolean")
455
+ throw new TypeError("Search fuzzy option must be a boolean.");
456
+ if (fuzzy && mode !== "sections")
457
+ throw new RangeError("Fuzzy search requires sections mode.");
458
+ if (typeof query !== "string")
459
+ throw new TypeError("Search query must be a string.");
460
+ if (query.length > 512)
461
+ throw new RangeError("Search query must not exceed 512 characters.");
462
+ const terms = [...new Set(normalize(query).split(" ").filter(Boolean))];
463
+ if (terms.length > 32)
464
+ throw new RangeError("Search query must not exceed 32 unique terms.");
465
+ if (!terms.length || !limit)
466
+ return [];
467
+ const results = mode === "sections"
468
+ ? sectionCandidates(index, terms, false)
469
+ : pageCandidates(index, terms);
470
+ if (fuzzy && results.length < limit) {
471
+ const literalUrls = new Set(results.map(candidateUrl));
472
+ results.push(...sectionCandidates(index, terms, true).filter((candidate) => candidate.rank === 0 && !literalUrls.has(candidateUrl(candidate))));
473
+ }
474
+ results.sort(compareCandidates);
475
+ // Original-text mapping and excerpt windows are computed only for final hits.
476
+ return results.slice(0, limit).map(displayResult);
153
477
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wgtechlabs/mdd-engine",
3
- "version": "0.1.0-dev.b4f443b",
3
+ "version": "0.1.0-pr.04f8fe2",
4
4
  "description": "Headless Markdown documentation compiler for mdd",
5
5
  "type": "module",
6
6
  "license": "MIT",