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