English
search-helper
Shared utilities for the local search plugins.
The package owns everything a local search plugin needs except the search engine itself: it collects the index items of the pages, keeps the mapping from the index ids back to the page paths, generates the worker that embeds the index, builds the results out of the engine hits, and ships the search box and the search modal of the client.
It is used by @vuepress/plugin-slimsearch, @vuepress/plugin-flexsearch and @vuepress/plugin-orama.
Usage
npm i @vuepress/search-helper@nextThe local search plugins of this repository depend on the package, so it is installed together with them. Add it explicitly only when you write your own search plugin.
The node side collects the index of the pages and hands it to the engine, then embeds the encoded index into the worker of the plugin. MyIndex and createIndex below stand for the types and the API of the engine you use:
import {
PathStore,
collectPageIndex,
generateSearchWorker,
prepareStore,
} from '@vuepress/search-helper'
import type { SearchIndexStore } from '@vuepress/search-helper'
import type { Plugin } from 'vuepress/core'
import { path } from 'vuepress/utils'
export const mySearchPlugin = (): Plugin => (app) => {
const store = new PathStore()
const searchIndexStore: SearchIndexStore<MyIndex> = {}
const indexesByPage = new Map<string, string[]>()
return {
name: 'my-search-plugin',
onInitialized: () => {
const { indexesByLocale } = collectPageIndex(
app,
{},
store,
indexesByPage,
)
for (const [localePath, items] of Object.entries(indexesByLocale))
searchIndexStore[localePath] = createIndex(items)
},
onPrepared: () => prepareStore(app, 'my-search', store),
onGenerated: () =>
generateSearchWorker(app, {
workerFile: path.resolve(import.meta.dirname, '../worker/build.js'),
outputFile: 'my-search.worker.js',
indexPlaceholder: '__MY_SEARCH_INDEX__',
sortPlaceholder: '__MY_SEARCH_SORT_STRATEGY__',
encode: (index) => JSON.stringify(index),
searchIndexStore,
}),
}
}The client side only needs the config of the search box, which is generated from the values that the plugin injects:
import { createSearchClientConfig } from '@vuepress/search-helper/client'
export default createSearchClientConfig({
options: __MY_SEARCH_OPTIONS__,
locales: __MY_SEARCH_LOCALES__,
store,
})Guide
Indexing the pages
collectPageIndex() turns the pages of the site into index items grouped by locale path. A page is skipped when it is filtered out by the filter option or when it sets search: false in its frontmatter. Every indexable page contributes:
- A page item, with the id of the page and its title.
- A section item for each heading of the page, whose id carries the anchor of the section.
- A custom field item for each indexable custom field of the page.
The ids are built from the numeric page id of the path store, INDEX_ID_SEPARATOR (the NUL character, which can never appear in an anchor) and a kind marker, e.g. 0, 0\u0000#anchor and 0\u0000@1. parseIndexId() splits them back, so an engine only has to store the id string.
PathStore maps the numeric ids to the page paths and back, and reuses the ids of the deleted paths, so that a page keeps a stable id while it exists:
const store = new PathStore()
store.addPath('/guide/') // 0
store.addPaths(['/guide/a.html', '/guide/b.html']) // [1, 2]
store.deletePath('/guide/a.html')
store.toJSON() // { '0': '/guide/', '2': '/guide/b.html' }generatePageIndex() generates the items of a single page, which is what a dev server needs to update the index of a page without rebuilding everything.
Preparing the index for the client
The index of every locale is written into the temp directory of the plugin, where the client and the dev worker can import it:
prepareStore()writes the path store into<tempDir>/store.js.writeLocaleIndex()writes the encoded index of a locale into its own chunk.writeLocaleRegistry()writes<tempDir>/index.js, which lazily imports the chunks of every locale.prepareSearchIndex()writes the chunks and the registry of every locale of an index store.prepareWorkerOptions()writes the sort strategy into<tempDir>/worker-options.js.
In dev, the client loads these files; in build, the index is embedded into the worker by generateSearchWorker(), which is why the worker must be generated on the onGenerated hook, once every page is known.
Generating the search worker
generateSearchWorker() reads a worker template, replaces the placeholders of the index and of the sort strategy, and writes the result into the output directory. The template is a normal worker module, so it imports the engine, decodes the embedded index and answers every message with the shared protocol:
import { entries, fromEntries } from '@vuepress/helper/shared'
import {
createWorkerResponse,
getOwnEntry,
} from '@vuepress/search-helper/shared'
declare const __MY_SEARCH_INDEX__: string
declare const __MY_SEARCH_SORT_STRATEGY__: 'max' | 'total'
const searchIndex = fromEntries(
entries(JSON.parse(__MY_SEARCH_INDEX__) as Record<string, string>).map(
([localePath, encoded]) => [localePath, loadIndex(decodeIndex(encoded))],
),
)
self.addEventListener('message', ({ data }) => {
self.postMessage(
createWorkerResponse(
data,
getOwnEntry(searchIndex, data.locale),
{ getSearchResults, getSuggestions },
__MY_SEARCH_SORT_STRATEGY__,
),
)
})createWorkerResponse() resolves the type of the request (all, search or suggest), calls the matching handler and returns the payload of the response, so the client code does not have to know the engine.
Building the results
An engine returns its own hits: an index id, a score and the stored document. buildSearchResults() groups them by page, uses the page item as the title of the result and sorts the pages by the sortStrategy:
import { buildSearchResults } from '@vuepress/search-helper/shared'
const results = buildSearchResults({
hits,
displayTerms: terms,
getPageTitle: (pageId) => store[pageId],
})Every matched item keeps the ranges that getMatchedContent() computed, so the client can highlight the query without parsing the content again.
Tokenizing
A search engine tokenizes the indexed documents, and the query must be tokenized the same way, otherwise the terms do not match. createWordTokenizer() returns a tokenizer for a language, which lowercases the terms and folds their diacritics, and keeps the repetitions so that the phrase matching still works. isSegmenterAvailable() tells whether Intl.Segmenter can split languages without whitespace, and foldDiacritics() and segmentWords() expose the two steps on their own.
The client side
createSearchClientConfig() returns the client config of the plugin: it stores the config, injects the search options into the app, registers the SearchBox component and mounts the SearchModal root component. The config is read back by getSearchClientConfig() in these components and in the worker composables.
The options of the search box can also be read from a page with useSearchOptions(), which merges the engine defaults, the root options and the options of the current locale.
Node API
collectPageIndex
appRequired
AppThe VuePress app of the site.
options
CollectPageIndexOptionsThe options shared by the search plugins, i.e. indexContent, customFields, preserveTags and filter.
storeRequired
PathStoreThe path store of the plugin.
indexesByPage
Map<string, string[]>The map to fill with the index ids of every page, which is used to remove the stale items of a page on update.
It returns CollectedPageIndex, i.e. { indexesByLocale, indexesByPage }, where the items are grouped by locale path.
generatePageIndex
pageRequired
PageThe page to index.
storeRequired
PathStoreThe path store of the plugin.
options
GeneratePageIndexOptionsThe indexContent, customFields and preserveTags options.
It returns the IndexItem[] of a single page: the page item, a section item per heading and a custom field item per indexable field.
PathStore
The class that maps the numeric ids of the index to the page paths.
addPath(path): returns the id of the path, and creates it when it is new.addPaths(paths): returns the ids of the paths.deletePath(path): frees the id of the path, which is reused by a later path.clear(): removes every path.toJSON(): returns theRecord<number, string>of the stored paths.
prepareStore
appRequired
AppThe VuePress app of the site.
tempDirRequired
stringThe name of the temp directory of the plugin.
storeRequired
PathStoreThe path store of the plugin.
It writes the store into <tempDir>/store.js.
writeLocaleIndex
appRequired
AppThe VuePress app of the site.
optionsRequired
PrepareIndexOptions<TIndex>The tempDir of the plugin and the encode function that serializes an index.
localeRequired
stringThe path of the locale.
indexRequired
TIndexThe index of the locale.
It writes the encoded index of a locale into its own chunk of the temp directory.
writeLocaleRegistry
appRequired
AppThe VuePress app of the site.
tempDirRequired
stringThe name of the temp directory of the plugin.
localesRequired
string[]The paths of the locales.
It writes <tempDir>/index.js, whose entries lazily import the chunk of every locale.
prepareSearchIndex
appRequired
AppThe VuePress app of the site.
optionsRequired
PrepareIndexOptions<TIndex>The tempDir of the plugin and the encode function that serializes an index.
searchIndexStoreRequired
SearchIndexStore<TIndex>The index of every locale.
It writes the chunks of every locale, then the registry.
prepareWorkerOptions
appRequired
AppThe VuePress app of the site.
tempDirRequired
stringThe name of the temp directory of the plugin.
sortStrategyRequired
SearchSortStrategyThe sort strategy of the results, i.e. 'max' or 'total'.
It writes the sort strategy into <tempDir>/worker-options.js.
generateSearchWorker
workerFileRequired
stringThe path of the worker template.
outputFileRequired
stringThe name of the generated worker, relative to the output directory.
indexPlaceholderRequired
stringThe placeholder of the encoded index in the template.
sortPlaceholderRequired
stringThe placeholder of the sort strategy in the template.
encodeRequired
(index: TIndex) => stringThe function that serializes an index, which is the same one as the encode of writeLocaleIndex().
sortStrategy
SearchSortStrategyDefault
'max'The sort strategy of the results.
searchIndexStoreRequired
SearchIndexStore<TIndex>The index of every locale.
It embeds the encoded index of every locale into the worker template and writes the result to the output directory. It must be called on the onGenerated hook.
createSearchLogger
It returns the VuePress logger of a plugin, so that every search plugin logs its messages with the same prefix.
getLocaleLanguage
It returns the language of a locale path, falling back to the lang of the site when the locale does not declare one.
getLocaleChunkName
It returns the name of the temp chunk of a locale, which is what writeLocaleRegistry() imports.
searchLocaleInfo
The default text of the search box for every built-in language, typed as DefaultLocaleInfo<SearchLocaleData>. The plugins pass it as the default of their locales option, so a site only has to translate the text it wants to change. See Locales.
Shared API
The shared entry, i.e. @vuepress/search-helper/shared, holds the code that runs in the worker and in the browser, so its values are also re-exported by the node entry.
buildSearchResults
hitsRequired
SearchHit[]The hits of the engine, i.e. an index id, a score, the stored document and the matched terms.
displayTermsRequired
string[]The terms of the query, used to highlight the matches. They must be tokenized the same way as the index.
getPageTitleRequired
(pageId: number) => string | undefinedIt returns the title of a page by its index id.
sortStrategy
SearchSortStrategyDefault
'max'Whether a page is sorted by its best match ('max') or by the sum of its matches ('total').
It returns the SearchResult[] of the query, i.e. a title and the matched items of the page.
parseIndexId
It splits an index id into its pageId, its kind ('page', 'section' or 'customField') and its info, i.e. the anchor of a section or the index of a custom field.
isSectionIndexItem and isCustomFieldIndexItem
The type guards of the section items and of the custom field items of an IndexItem[].
getMatchedContent
It returns the snippet of a content around its matches, i.e. { text, highlights }, where highlights is the flat list of the ranges to highlight, or null when the content does not match.
Tokenizers
createWordTokenizer(language): returns the tokenizer of a language, which lowercases the terms and folds their diacritics.foldDiacritics(text): replaces the accented characters by their base character, keeping the length of the text.segmentWords(text, segmenter): splits a text with anIntl.Segmenter.createSegmenter(language): returns the segmenter of a language.isSegmenterAvailable(): tells whether the runtime providesIntl.Segmenter.foldToken(token): folds a single token.
Worker protocol
The worker and the client share a message protocol, so an engine only has to implement the search itself:
WorkerMessageData<TOptions>: the request, i.e. atype('all','search'or'suggest'), aquery, alocale, optional engineoptionsand theidof the request.WorkerResponse: the response, i.e. the type, the id and the payload of the request.createWorkerResponse(data, localeIndex, handlers, sortStrategy): resolves the request and returns the response, withgetSearchResultsandgetSuggestionsas handlers.getOwnEntry(record, key): reads an entry of a record, ignoring the inherited properties.
Client API
createSearchClientConfig
optionsRequired
SearchClientOptionsThe options of the search box, i.e. suggestion, searchDelay, suggestDelay, queryHistoryCount, resultHistoryCount, hotKeys and worker.
localesRequired
ExactLocaleConfig<SearchLocaleData>The text of the search box of every locale.
customFieldConfig
Record<string, SearchCustomFieldFormatter>The formatters of the custom fields, indexed by the index of the field.
storeRequired
Record<number, string>The path store, which maps the id of a page to its path.
createDevWorker
() => WorkerThe factory of the worker in the dev server. It must use the new Worker(new URL(...)) syntax, so that the bundler can resolve the imports of the worker.
getLocaleSearchOptions
(lang: string) => WorkerSearchOptionsThe engine specific defaults of the search options of a locale, merged before the user options.
It returns the client config of the plugin, which injects the options, registers the SearchBox component and mounts the SearchModal root component.
setSearchClientConfig and getSearchClientConfig
They set and read the config of the search client. getSearchClientConfig() throws when the config has not been set, i.e. when the client config of the plugin is not registered.
createSearchWorker
It creates the worker of the search and wraps the message protocol into a SearchWorker:
all(query, localePath?, options?): returns theQueryResultof the query, i.e. its suggestions and its results.suggest(query, localePath?, options?): returns the suggestions of the query.search(query, localePath?, options?): returns the results of the query.terminate(): stops the worker.
In dev it creates the worker with createDevWorker, otherwise it loads options.worker from the site base.
defineSearchConfig, injectSearchConfig and useSearchOptions
defineSearchConfig() marks the options of the plugin, injectSearchConfig() provides them to the app, and useSearchOptions() returns the options of the current locale, merged from the engine defaults, the root options and the options of the locale. The options extend WorkerSearchOptions with querySplitter, suggestionsFilter and resultsFilter.
