docs/.vitepress/theme/workers/searchWorker.ts
424 lines · 10889 bytes
33 symbols in this file
ResultSearchModePlainRecordSearchConfigPageGroupCountLoadIndexRequestTextSearchRequestUrlSearchRequestPreloadMetadataRequestSearchWorkerRequestWorkerSearchResultdefaultBoostDocumentstableStringifysetPageOrdergetPageKeygetAnchorKeygetResultLocationgetPageOrdergetDocOrdercompareByPageAndDocstripMarkdowngetQueryTermsfindMatchingLinksForResultwithLinkPathTitlesgetTabsForResultwithTabMetadatarebuildDocOrderloadSearchIndextextSearchensureUrlLinksensureTabTargetsensureSearchMetadataurlSearch
1import MiniSearch, {
2 type Options,
3 type SearchOptions,
4 type SearchResult
5} from 'minisearch'
6
7import type { PageLink, TabTarget } from '../../plugins/urlSearchPlugin'
8
9interface Result {
10 tabs?: string[]
11 title: string
12 titles: string[]
13 text?: string
14}
15
16type SearchMode = 'exact' | 'fuzzy' | 'url'
17
18type PlainRecord = Record<string, unknown>
19
20interface SearchConfig {
21 options?: PlainRecord
22 searchOptions?: PlainRecord
23 useDefaultBoostDocument?: boolean
24}
25
26interface PageGroupCount {
27 key: string
28 count: number
29}
30
31interface LoadIndexRequest {
32 type: 'load-index'
33 id: number
34 localeIndex: string
35 indexJson: unknown
36 indexVersion: number
37 config: SearchConfig
38}
39
40interface TextSearchRequest {
41 type: 'text-search'
42 id: number
43 query: string
44 mode: SearchMode
45 pageOrderEntries: [string, number][]
46}
47
48interface UrlSearchRequest {
49 type: 'url-search'
50 id: number
51 query: string
52 pageOrderEntries: [string, number][]
53}
54
55interface PreloadMetadataRequest {
56 type: 'preload-metadata'
57 id: number
58 pageOrderEntries: [string, number][]
59}
60
61type SearchWorkerRequest =
62 | LoadIndexRequest
63 | TextSearchRequest
64 | UrlSearchRequest
65 | PreloadMetadataRequest
66
67type WorkerSearchResult = SearchResult & Result
68
69let searchIndex: MiniSearch<Result> | null = null
70let searchIndexKey = ''
71let urlLinks: PageLink[] = []
72let urlLinkHrefsLower: string[] = []
73let urlLinksPromise: Promise<void> | null = null
74let tabTargetMap = new Map<string, string[]>()
75let tabTargetsPromise: Promise<void> | null = null
76let pageOrder = new Map<string, number>()
77let docOrder = new Map<string, number>()
78
79function defaultBoostDocument(
80 _: string,
81 term: string,
82 storedFields: Record<string, string | string[]>
83) {
84 const titles = ((storedFields?.titles as string[] | undefined) ?? [])
85 .filter((t) => Boolean(t))
86 .map((t) => t.toLowerCase())
87 const titleIndex = titles
88 .map((t, i) => (t?.includes(term) ? i : -1))
89 .find((i) => i >= 0) ?? -1
90 if (titleIndex >= 0) return 10000 - titleIndex
91 return 1
92}
93
94function stableStringify(value: unknown): string {
95 if (value === null || typeof value !== 'object') return JSON.stringify(value)
96 if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
97 const object = value as Record<string, unknown>
98 return `{${
99 Object.keys(object).sort().map((key) =>
100 `${JSON.stringify(key)}:${stableStringify(object[key])}`
101 ).join(',')
102 }}`
103}
104
105function setPageOrder(entries: [string, number][]) {
106 pageOrder = new Map(entries)
107}
108
109function getPageKey(id: string) {
110 return id.split('#')[0].replace(/\/$/, '')
111}
112
113function getAnchorKey(pageId: string, anchor: string) {
114 return `${pageId.replace(/\/$/, '')}\x00${anchor}`
115}
116
117function getResultLocation(id: unknown) {
118 const value = String(id)
119 const hashIndex = value.indexOf('#')
120
121 return {
122 anchor: hashIndex >= 0 ? value.slice(hashIndex + 1) : '',
123 pageId: getPageKey(value)
124 }
125}
126
127function getPageOrder(key: string) {
128 return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
129}
130
131function getDocOrder(id: string) {
132 return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER
133}
134
135function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) {
136 const aId = String(a.id)
137 const bId = String(b.id)
138 const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId))
139 if (pageDiff !== 0) return pageDiff
140 return getDocOrder(aId) - getDocOrder(bId)
141}
142
143function stripMarkdown(value: string) {
144 return value
145 .replace(/`([^`]+)`/g, '$1')
146 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
147 .replace(/[*_~]/g, '')
148 .trim()
149}
150
151function getQueryTerms(query: string) {
152 return query
153 .toLowerCase()
154 .split(/\s+/)
155 .map((term) => term.trim())
156 .filter(Boolean)
157}
158
159function findMatchingLinksForResult(
160 result: WorkerSearchResult,
161 query: string
162) {
163 const pageId = getPageKey(String(result.id))
164 const anchor = String(result.id).split('#')[1] ?? ''
165 const terms = getQueryTerms(query)
166 if (!terms.length) return []
167
168 return urlLinks.filter((link) => {
169 if (link.pageId.replace(/\/$/, '') !== pageId || link.anchor !== anchor) {
170 return false
171 }
172
173 const linkText = stripMarkdown(link.linkText).toLowerCase()
174 return terms.every((term) => linkText.includes(term))
175 })
176}
177
178function withLinkPathTitles(
179 results: WorkerSearchResult[],
180 query: string
181) {
182 if (!urlLinks.length) return results
183
184 const expanded: WorkerSearchResult[] = []
185 for (const result of results) {
186 const links = findMatchingLinksForResult(result, query)
187 if (!links.length) {
188 expanded.push(result)
189 } else {
190 for (let i = 0; i < links.length; i++) {
191 const link = links[i]
192 expanded.push({
193 ...result,
194 title: stripMarkdown(link.linkText),
195 titles: link.titles,
196 _linkIndex: i,
197 ...(link.tabs?.length ? { tabs: link.tabs } : {})
198 })
199 }
200 }
201 }
202 return expanded
203}
204
205function getTabsForResult(result: WorkerSearchResult) {
206 if (result.tabs?.length) return result.tabs
207
208 const { pageId, anchor } = getResultLocation(result.id)
209 return tabTargetMap.get(getAnchorKey(pageId, anchor))
210}
211
212function withTabMetadata(results: WorkerSearchResult[]) {
213 if (!tabTargetMap.size) return results
214
215 return results.map((result) => {
216 const tabs = getTabsForResult(result)
217 return tabs?.length ? { ...result, tabs } : result
218 })
219}
220
221function rebuildDocOrder(index: MiniSearch<Result>) {
222 const map = new Map<string, number>()
223 const ids = (index as any)._documentIds
224 if (ids instanceof Map) {
225 let i = 0
226 for (const originalId of ids.values()) {
227 map.set(String(originalId), i++)
228 }
229 } else if (ids && typeof ids === 'object') {
230 const keys = Object.keys(ids)
231 .map(Number)
232 .sort((a, b) => a - b)
233 let i = 0
234 for (const key of keys) {
235 map.set(String(ids[key]), i++)
236 }
237 }
238 docOrder = map
239}
240
241async function loadSearchIndex(
242 localeIndex: string,
243 indexVersion: number,
244 indexJson: unknown,
245 config: SearchConfig
246) {
247 const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}`
248 if (searchIndex && searchIndexKey === key) return
249
250 const searchOptions = {
251 boost: { title: 10, titles: 4, text: 1 },
252 ...(config.searchOptions ?? {}),
253 ...(config.useDefaultBoostDocument
254 ? { boostDocument: defaultBoostDocument }
255 : {})
256 } as SearchOptions
257
258 searchIndex = MiniSearch.loadJSON<Result>(
259 indexJson as any,
260 {
261 fields: ['title', 'titles', 'text'],
262 storeFields: ['title', 'titles'],
263 searchOptions,
264 ...(config.options ?? {})
265 } as Options<Result>
266 )
267 searchIndexKey = key
268 rebuildDocOrder(searchIndex)
269}
270
271async function textSearch(message: TextSearchRequest) {
272 setPageOrder(message.pageOrderEntries)
273 if (!searchIndex) throw new Error('Search index has not been loaded')
274
275 const dynamicSearchOptions = {
276 fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false,
277 prefix: message.mode === 'fuzzy'
278 ? (term: string) => term.length > 3
279 : false,
280 maxFuzzy: message.mode === 'fuzzy' ? 1 : 0,
281 boost: { title: 10, titles: 4, text: 1 }
282 } as SearchOptions
283
284 const ranked = searchIndex.search(
285 message.query,
286 dynamicSearchOptions
287 ) as WorkerSearchResult[]
288
289 const top = ranked.slice(0, 50)
290 const seen = new Set(top.map((r) => r.id))
291 const titleHits = ranked.filter(
292 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
293 )
294 const results = [...top, ...titleHits].sort(compareByPageAndDoc)
295 await ensureSearchMetadata()
296 const displayResults = withTabMetadata(
297 withLinkPathTitles(results, message.query)
298 )
299 const terms = new Set<string>()
300 for (const result of displayResults) {
301 for (const term in result.match) terms.add(term)
302 }
303
304 return {
305 results: displayResults,
306 terms: [...terms]
307 }
308}
309
310async function ensureUrlLinks() {
311 if (urlLinks.length > 0) return
312 if (urlLinksPromise) {
313 await urlLinksPromise
314 return
315 }
316
317 urlLinksPromise = fetch('/url-search-index.json')
318 .then((r) => r.json())
319 .then((data: PageLink[]) => {
320 data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId))
321 urlLinks = data
322 urlLinkHrefsLower = data.map((link) => link.href.toLowerCase())
323 })
324 .catch(() => {
325 urlLinks = []
326 urlLinkHrefsLower = []
327 })
328 .finally(() => {
329 urlLinksPromise = null
330 })
331 await urlLinksPromise
332}
333
334async function ensureTabTargets() {
335 if (tabTargetMap.size > 0) return
336 if (tabTargetsPromise) {
337 await tabTargetsPromise
338 return
339 }
340
341 tabTargetsPromise = fetch('/tab-search-index.json')
342 .then((r) => r.json())
343 .then((data: TabTarget[]) => {
344 tabTargetMap = new Map(
345 data.map((target) => [
346 getAnchorKey(target.pageId, target.anchor),
347 target.tabs
348 ])
349 )
350 })
351 .catch(() => {
352 tabTargetMap = new Map()
353 })
354 .finally(() => {
355 tabTargetsPromise = null
356 })
357 await tabTargetsPromise
358}
359
360async function ensureSearchMetadata() {
361 await Promise.all([ensureUrlLinks(), ensureTabTargets()])
362}
363
364async function urlSearch(message: UrlSearchRequest) {
365 setPageOrder(message.pageOrderEntries)
366 await ensureSearchMetadata()
367
368 const query = message.query.trim().toLowerCase()
369 if (!query) return { matches: [], pageGroups: [] }
370
371 const matches: PageLink[] = []
372 const pageGroups = new Map<string, PageGroupCount>()
373 for (let i = 0; i < urlLinks.length; i++) {
374 if (!urlLinkHrefsLower[i].includes(query)) continue
375
376 const link = urlLinks[i]
377
378 if (link.tabs?.length) {
379 matches.push(link)
380 } else {
381 const tabs = tabTargetMap.get(getAnchorKey(link.pageId, link.anchor))
382 matches.push(tabs?.length ? { ...link, tabs } : link)
383 }
384 const existing = pageGroups.get(link.pageId)
385 if (existing) existing.count++
386 else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
387 }
388
389 return {
390 matches,
391 pageGroups: [...pageGroups.values()].sort(
392 (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
393 )
394 }
395}
396
397self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => {
398 const message = event.data
399 try {
400 const payload = message.type === 'load-index'
401 ? await loadSearchIndex(
402 message.localeIndex,
403 message.indexVersion,
404 message.indexJson,
405 message.config
406 )
407 : message.type === 'text-search'
408 ? await textSearch(message)
409 : message.type === 'preload-metadata'
410 ? (setPageOrder(message.pageOrderEntries), await ensureSearchMetadata())
411 : await urlSearch(message)
412 self.postMessage({
413 type: `${message.type}:success`,
414 id: message.id,
415 payload
416 })
417 } catch (error) {
418 self.postMessage({
419 type: `${message.type}:error`,
420 id: message.id,
421 error: error instanceof Error ? error.message : String(error)
422 })
423 }
424}