-
Notifications
You must be signed in to change notification settings - Fork 0
/
dictionaries.js
90 lines (83 loc) · 2.52 KB
/
dictionaries.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
const nspell = require('nspell');
const axios = require('axios').default;
const hunspellDictionaries = {};
const httpDictionaries = {};
function parseDictionaryUrl(dictionaryUrl) {
return Object.defineProperties({}, {
'isHttp': {
value: (dictionaryUrl.startsWith('https://') || dictionaryUrl.startsWith('http://')) && dictionaryUrl.includes('%s'),
},
'isHunspell': {
value: dictionaryUrl.startsWith('hunspell://'),
},
'language': {
value: (dictionaryUrl.match(/^hunspell:\/\/([a-z-]+)$/) || [])[1],
},
'url': {
value: dictionaryUrl,
},
});
}
async function isValidHunspell(word) {
return this.correct(word) || this.suggest(word).findIndex(suggestion => suggestion.toLowerCase() == word) >= 0;
}
async function isValidHttp(word) {
return true && await axios.get(`${this.info.url}`.replace('%s', word)).catch(console.error);
}
async function loadHttp(dictionaryInfo) {
let dictionary = httpDictionaries[dictionaryInfo.url];
if (dictionary === undefined) {
dictionary = {};
dictionary = Object.defineProperties(dictionary, {
info: {
value: dictionaryInfo,
},
isValid: {
value: isValidHttp.bind(dictionary),
},
});
httpDictionaries[dictionaryInfo.url] = dictionary;
}
return dictionary;
}
async function loadHunspell(dictionaryInfo) {
let dictionary = hunspellDictionaries[dictionaryInfo.language];
if (dictionary === undefined) {
try {
const dictionaryData = require(`dictionary-${dictionaryInfo.language}`);
dictionary = await (new Promise(resolve => {
dictionaryData((error, data) => {
if (error) {
throw error;
}
resolve(nspell(data));
});
}));
Object.defineProperty(dictionary, 'info', {
value: dictionaryInfo,
});
dictionary.isValid = isValidHunspell.bind(dictionary);
hunspellDictionaries[dictionaryInfo.language] = dictionary;
} catch (error) {
console.error('Failed to load dictionary for language ', dictionaryInfo.language, ': ', error);
}
}
return dictionary;
}
module.exports = {
load: async function (dictionaryUrl) {
const dictionaryInfo = parseDictionaryUrl(dictionaryUrl);
if (dictionaryInfo.isHttp) {
return loadHttp(dictionaryInfo);
} else if (dictionaryInfo.isHunspell && dictionaryInfo.language !== undefined) {
return loadHunspell(dictionaryInfo);
} else {
console.error('Invalid dictionary:', dictionaryInfo);
return undefined;
}
},
isValid: async function (dictionaryUrl, word) {
const dictionary = await this.load(dictionaryUrl);
return dictionary && await dictionary.isValid(word);
},
};