docs/.vitepress/theme/workers/searchWorker.ts

5cfd00170df32fd4acbac60b0ed25c4b7910c205
wotaku/docs/.vitepress/theme/workers/searchWorker.ts

276 lines · 7005 bytes

  1import MiniSearch, {
  2  type Options,
  3  type SearchOptions,
  4  type SearchResult
  5} from 'minisearch'
  6
  7import type { PageLink } from '../../plugins/urlSearchPlugin'
  8
  9interface Result {
 10  title: string
 11  titles: string[]
 12  text?: string
 13}
 14
 15type SearchMode = 'exact' | 'fuzzy' | 'url'
 16
 17type PlainRecord = Record<string, unknown>
 18
 19interface SearchConfig {
 20  options?: PlainRecord
 21  searchOptions?: PlainRecord
 22  useDefaultBoostDocument?: boolean
 23}
 24
 25interface PageGroupCount {
 26  key: string
 27  count: number
 28}
 29
 30interface LoadIndexRequest {
 31  type: 'load-index'
 32  id: number
 33  localeIndex: string
 34  indexJson: unknown
 35  indexVersion: number
 36  config: SearchConfig
 37}
 38
 39interface TextSearchRequest {
 40  type: 'text-search'
 41  id: number
 42  query: string
 43  mode: SearchMode
 44  pageOrderEntries: [string, number][]
 45}
 46
 47interface UrlSearchRequest {
 48  type: 'url-search'
 49  id: number
 50  query: string
 51  pageOrderEntries: [string, number][]
 52}
 53
 54type SearchWorkerRequest =
 55  | LoadIndexRequest
 56  | TextSearchRequest
 57  | UrlSearchRequest
 58
 59type WorkerSearchResult = SearchResult & Result
 60
 61let searchIndex: MiniSearch<Result> | null = null
 62let searchIndexKey = ''
 63let urlLinks: PageLink[] = []
 64let urlLinksPromise: Promise<void> | null = null
 65let pageOrder = new Map<string, number>()
 66let docOrder = new Map<string, number>()
 67
 68function defaultBoostDocument(
 69  _: string,
 70  term: string,
 71  storedFields: Record<string, string | string[]>
 72) {
 73  const titles = ((storedFields?.titles as string[] | undefined) ?? [])
 74    .filter((t) => Boolean(t))
 75    .map((t) => t.toLowerCase())
 76  const titleIndex = titles
 77    .map((t, i) => (t?.includes(term) ? i : -1))
 78    .find((i) => i >= 0) ?? -1
 79  if (titleIndex >= 0) return 10000 - titleIndex
 80  return 1
 81}
 82
 83function stableStringify(value: unknown): string {
 84  if (value === null || typeof value !== 'object') return JSON.stringify(value)
 85  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
 86  const object = value as Record<string, unknown>
 87  return `{${
 88    Object.keys(object).sort().map((key) =>
 89      `${JSON.stringify(key)}:${stableStringify(object[key])}`
 90    ).join(',')
 91  }}`
 92}
 93
 94function setPageOrder(entries: [string, number][]) {
 95  pageOrder = new Map(entries)
 96}
 97
 98function getPageKey(id: string) {
 99  return id.split('#')[0].replace(/\/$/, '')
100}
101
102function getPageOrder(key: string) {
103  return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
104}
105
106function getDocOrder(id: string) {
107  return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER
108}
109
110function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) {
111  const aId = String(a.id)
112  const bId = String(b.id)
113  const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId))
114  if (pageDiff !== 0) return pageDiff
115  return getDocOrder(aId) - getDocOrder(bId)
116}
117
118function rebuildDocOrder(index: MiniSearch<Result>) {
119  const map = new Map<string, number>()
120  const ids = (index as any)._documentIds
121  if (ids instanceof Map) {
122    let i = 0
123    for (const originalId of ids.values()) {
124      map.set(String(originalId), i++)
125    }
126  } else if (ids && typeof ids === 'object') {
127    const keys = Object.keys(ids)
128      .map(Number)
129      .sort((a, b) => a - b)
130    let i = 0
131    for (const key of keys) {
132      map.set(String(ids[key]), i++)
133    }
134  }
135  docOrder = map
136}
137
138async function loadSearchIndex(
139  localeIndex: string,
140  indexVersion: number,
141  indexJson: unknown,
142  config: SearchConfig
143) {
144  const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}`
145  if (searchIndex && searchIndexKey === key) return
146
147  const searchOptions = {
148    boost: { title: 10, titles: 4, text: 1 },
149    ...(config.searchOptions ?? {}),
150    ...(config.useDefaultBoostDocument
151      ? { boostDocument: defaultBoostDocument }
152      : {})
153  } as SearchOptions
154
155  searchIndex = MiniSearch.loadJSON<Result>(
156    indexJson as any,
157    {
158      fields: ['title', 'titles', 'text'],
159      storeFields: ['title', 'titles'],
160      searchOptions,
161      ...(config.options ?? {})
162    } as Options<Result>
163  )
164  searchIndexKey = key
165  rebuildDocOrder(searchIndex)
166}
167
168async function textSearch(message: TextSearchRequest) {
169  setPageOrder(message.pageOrderEntries)
170  if (!searchIndex) throw new Error('Search index has not been loaded')
171
172  const dynamicSearchOptions = {
173    fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false,
174    prefix: message.mode === 'fuzzy'
175      ? (term: string) => term.length > 3
176      : false,
177    maxFuzzy: message.mode === 'fuzzy' ? 1 : 0,
178    boost: { title: 10, titles: 4, text: 1 }
179  } as SearchOptions
180
181  const ranked = searchIndex.search(
182    message.query,
183    dynamicSearchOptions
184  ) as WorkerSearchResult[]
185
186  const top = ranked.slice(0, 50)
187  const seen = new Set(top.map((r) => r.id))
188  const titleHits = ranked.filter(
189    (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
190  )
191  const results = [...top, ...titleHits].sort(compareByPageAndDoc)
192  const terms = new Set<string>()
193  for (const result of results) {
194    for (const term in result.match) terms.add(term)
195  }
196
197  return {
198    results,
199    terms: [...terms]
200  }
201}
202
203async function ensureUrlLinks() {
204  if (urlLinks.length > 0) return
205  if (urlLinksPromise) {
206    await urlLinksPromise
207    return
208  }
209
210  urlLinksPromise = fetch('/url-search-index.json')
211    .then((r) => r.json())
212    .then((data: PageLink[]) => {
213      data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId))
214      urlLinks = data
215    })
216    .catch(() => {
217      urlLinks = []
218    })
219    .finally(() => {
220      urlLinksPromise = null
221    })
222  await urlLinksPromise
223}
224
225async function urlSearch(message: UrlSearchRequest) {
226  setPageOrder(message.pageOrderEntries)
227  await ensureUrlLinks()
228
229  const query = message.query.trim().toLowerCase()
230  if (!query) return { matches: [], pageGroups: [] }
231
232  const matches: PageLink[] = []
233  const pageGroups = new Map<string, PageGroupCount>()
234  for (const link of urlLinks) {
235    if (!link.href.toLowerCase().includes(query)) continue
236
237    matches.push(link)
238    const existing = pageGroups.get(link.pageId)
239    if (existing) existing.count++
240    else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
241  }
242
243  return {
244    matches,
245    pageGroups: [...pageGroups.values()].sort(
246      (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
247    )
248  }
249}
250
251self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => {
252  const message = event.data
253  try {
254    const payload = message.type === 'load-index'
255      ? await loadSearchIndex(
256        message.localeIndex,
257        message.indexVersion,
258        message.indexJson,
259        message.config
260      )
261      : message.type === 'text-search'
262      ? await textSearch(message)
263      : await urlSearch(message)
264    self.postMessage({
265      type: `${message.type}:success`,
266      id: message.id,
267      payload
268    })
269  } catch (error) {
270    self.postMessage({
271      type: `${message.type}:error`,
272      id: message.id,
273      error: error instanceof Error ? error.message : String(error)
274    })
275  }
276}