| 49 | |
| 50 | return Object.assign({}, nextConfig, { |
| 51 | webpack(config, options) { |
| 52 | config.module.rules.push({ |
| 53 | test: __filename, |
| 54 | use: [ |
| 55 | createLoader(function () { |
| 56 | let contentDir = path.resolve('./content') |
| 57 | this.addContextDependency(contentDir) |
| 58 | |
| 59 | let files = glob.sync('**/*.mdx', { cwd: contentDir }) |
| 60 | let data = files.map((file) => { |
| 61 | let url = '/' + file.replace(/\.mdx$/, '') |
| 62 | let mdx = fs.readFileSync(path.join(contentDir, file), 'utf8') |
| 63 | |
| 64 | let sections = [] |
| 65 | |
| 66 | if (cache.get(file)?.[0] === mdx) { |
| 67 | sections = cache.get(file)[1] |
| 68 | } else { |
| 69 | let vfile = { value: mdx, sections } |
| 70 | processor.runSync(processor.parse(vfile), vfile) |
| 71 | cache.set(file, [mdx, sections]) |
| 72 | } |
| 73 | |
| 74 | return { url, sections } |
| 75 | }) |
| 76 | |
| 77 | return ` |
| 78 | import FlexSearch from 'flexsearch' |
| 79 | |
| 80 | let sectionIndex = new FlexSearch.Document({ |
| 81 | tokenize: 'full', |
| 82 | document: { |
| 83 | id: 'url', |
| 84 | index: 'content', |
| 85 | store: ['title', 'pageTitle'], |
| 86 | }, |
| 87 | context: { |
| 88 | resolution: 9, |
| 89 | depth: 2, |
| 90 | bidirectional: true |
| 91 | } |
| 92 | }) |
| 93 | |
| 94 | let data = ${JSON.stringify(data)} |
| 95 | |
| 96 | for (let { url, sections } of data) { |
| 97 | for (let [title, hash, content] of sections) { |
| 98 | sectionIndex.add({ |
| 99 | url: url + (hash ? ('#' + hash) : ''), |
| 100 | title, |
| 101 | content: [title, ...content].join('\\n'), |
| 102 | pageTitle: hash ? sections[0][0] : undefined, |
| 103 | }) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | export function search(query, options = {}) { |
| 108 | let result = sectionIndex.search(query, { |