forked from 17thshard/roshar-map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch-index-loader.js
148 lines (126 loc) · 4.02 KB
/
search-index-loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
const fs = require('fs')
const lunr = require('lunr')
require('lunr-languages/lunr.stemmer.support')(lunr)
lunr.tokenizer.separator = /[\s-[\](){}]+/
function removeDuplicates (token, index, tokens) {
const [position] = token.metadata.position
for (let i = index - 1; i >= 0 && tokens[i].metadata.position[0] === position; i--) {
if (tokens[i].toString() === token.toString()) {
return null
}
}
return token
}
lunr.Pipeline.registerFunction(removeDuplicates, 'remove-duplicates')
function nGramTokenizer (obj, metadata) {
if (obj === null || obj === undefined) {
return []
}
if (Array.isArray(obj)) {
return obj.map(function (t) {
return new lunr.Token(
lunr.utils.asString(t).toLowerCase(),
lunr.utils.clone(metadata)
)
})
}
const str = obj.toString().toLowerCase()
const len = str.length
const tokens = []
for (let sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) {
const char = str.charAt(sliceEnd)
const sliceLength = sliceEnd - sliceStart
if ((char.match(lunr.tokenizer.separator) || sliceEnd === len)) {
if (sliceLength > 0) {
const tokenMetadata = lunr.utils.clone(metadata) || {}
tokenMetadata.position = [sliceStart, sliceLength]
tokenMetadata.index = tokens.length
const baseToken = str.slice(sliceStart, sliceEnd)
if (baseToken.length <= 3) {
tokens.push(new lunr.Token(baseToken, tokenMetadata))
} else {
for (let i = 3; i <= baseToken.length; i++) {
const meta = lunr.utils.clone(tokenMetadata)
meta.position = [sliceStart, i]
meta.index = tokens.length
tokens.push(new lunr.Token(baseToken.slice(0, i), meta))
}
}
}
sliceStart = sliceEnd + 1
}
}
return tokens
}
module.exports = function (source) {
if (this.cacheable) {
this.cacheable()
}
this.async()
const messages = typeof source === 'string' ? JSON.parse(source) : source
const load = async (key) => {
const path = await new Promise((resolve, reject) => this.resolve(
this.rootContext,
`@/store/${key}.json`,
(error, result) => error !== null ? reject(error) : resolve(result)
))
this.addDependency(path)
return JSON.parse(fs.readFileSync(path)).reduce(
(acc, entry) => {
acc[entry.id] = entry
return acc
},
{}
)
}
async function buildIndex () {
const searchable = (await Promise.all(['events', 'locations', 'characters', 'misc'].map(async key => ({
key,
value: await load(key)
})))).reduce(
(acc, entry) => {
acc[entry.key] = entry.value
return acc
},
{}
)
return lunr(function () {
const lunrLanguage = messages['search-language']
this.tokenizer = nGramTokenizer
if (lunrLanguage !== 'en') {
require(`lunr-languages/lunr.${lunrLanguage}`)(lunr)
this.use(lunr[lunrLanguage])
}
this.pipeline.add(removeDuplicates)
this.ref('id')
this.field('name', { boost: 10 })
this.field('details')
this.field('artist')
Object.entries(searchable).forEach(([entryType, entryData]) => {
const entries = messages[entryType] ?? []
Object.keys(entries).forEach((id) => {
const entry = entryData[id]
let artist
if (entry !== undefined && entry.image !== undefined && entry.image.credits !== undefined) {
const markdownResult = /^\[([^\]]+)]\(.*\)$/.exec(entry.image.credits)
artist = markdownResult !== null ? markdownResult[1] : entry.image.credits
}
this.add(
{ ...entries[id], id: `${entryType}/${id}`, artist },
{ boost: entryType !== 'events' ? 2 : 1 }
)
})
})
})
}
buildIndex()
.then(index =>
this.callback(
null,
JSON.stringify(index)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
)
)
.catch(error => this.callback(error))
}