@keymanapp/kmc-model 17.0.154-alpha → 17.0.156-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/build/src/build-trie.d.ts +42 -40
  2. package/build/src/build-trie.d.ts.map +1 -1
  3. package/build/src/build-trie.js +370 -366
  4. package/build/src/build-trie.js.map +1 -1
  5. package/build/src/compiler-callbacks.d.ts +6 -4
  6. package/build/src/compiler-callbacks.d.ts.map +1 -1
  7. package/build/src/compiler-callbacks.js +7 -5
  8. package/build/src/compiler-callbacks.js.map +1 -1
  9. package/build/src/join-word-breaker-decorator.d.ts +12 -10
  10. package/build/src/join-word-breaker-decorator.d.ts.map +1 -1
  11. package/build/src/join-word-breaker-decorator.js +123 -121
  12. package/build/src/join-word-breaker-decorator.js.map +1 -1
  13. package/build/src/lexical-model-compiler.d.ts +19 -16
  14. package/build/src/lexical-model-compiler.d.ts.map +1 -1
  15. package/build/src/lexical-model-compiler.js +153 -150
  16. package/build/src/lexical-model-compiler.js.map +1 -1
  17. package/build/src/lexical-model.d.ts +137 -135
  18. package/build/src/lexical-model.d.ts.map +1 -1
  19. package/build/src/lexical-model.js +8 -6
  20. package/build/src/lexical-model.js.map +1 -1
  21. package/build/src/main.d.ts +19 -17
  22. package/build/src/main.d.ts.map +1 -1
  23. package/build/src/main.js +60 -60
  24. package/build/src/main.js.map +1 -1
  25. package/build/src/model-compiler-errors.d.ts +53 -51
  26. package/build/src/model-compiler-errors.d.ts.map +1 -1
  27. package/build/src/model-compiler-errors.js +58 -56
  28. package/build/src/model-compiler-errors.js.map +1 -1
  29. package/build/src/model-defaults.d.ts +58 -56
  30. package/build/src/model-defaults.d.ts.map +1 -1
  31. package/build/src/model-defaults.js +108 -106
  32. package/build/src/model-defaults.js.map +1 -1
  33. package/build/src/model-definitions.d.ts +73 -71
  34. package/build/src/model-definitions.d.ts.map +1 -1
  35. package/build/src/model-definitions.js +191 -189
  36. package/build/src/model-definitions.js.map +1 -1
  37. package/build/src/script-overrides-decorator.d.ts +6 -4
  38. package/build/src/script-overrides-decorator.d.ts.map +1 -1
  39. package/build/src/script-overrides-decorator.js +66 -64
  40. package/build/src/script-overrides-decorator.js.map +1 -1
  41. package/package.json +7 -7
@@ -1,366 +1,370 @@
1
- import { readFileSync } from "fs";
2
- import { ModelCompilerError, ModelCompilerMessageContext, ModelCompilerMessages } from "./model-compiler-errors.js";
3
- import { callbacks } from "./compiler-callbacks.js";
4
- // Supports LF or CRLF line terminators.
5
- const NEWLINE_SEPARATOR = /\u000d?\u000a/;
6
- /**
7
- * Returns a data structure that can be loaded by the TrieModel.
8
- *
9
- * It implements a **weighted** trie, whose indices (paths down the trie) are
10
- * generated by a search key, and not concrete wordforms themselves.
11
- *
12
- * @param sourceFiles an array of source files that will be read to generate the trie.
13
- */
14
- export function createTrieDataStructure(filenames, searchTermToKey) {
15
- if (typeof searchTermToKey !== "function") {
16
- throw new ModelCompilerError(ModelCompilerMessages.Error_SearchTermToKeyMustBeExplicitlySpecified());
17
- }
18
- // Make one big word list out of all of the filenames provided.
19
- let wordlist = {};
20
- filenames.forEach(filename => parseWordListFromFilename(wordlist, filename));
21
- let trie = Trie.buildTrie(wordlist, searchTermToKey);
22
- return JSON.stringify(trie);
23
- }
24
- /**
25
- * Parses a word list from a file, merging duplicate entries.
26
- *
27
- * The word list may be encoded in:
28
- *
29
- * - UTF-8, with or without BOM [exported by most software]
30
- * - UTF-16, little endian, with BOM [exported by Microsoft Excel]
31
- *
32
- * @param wordlist word list to merge entries into (may have existing entries)
33
- * @param filename filename of the word list
34
- */
35
- export function parseWordListFromFilename(wordlist, filename) {
36
- ModelCompilerMessageContext.filename = filename;
37
- _parseWordList(wordlist, new WordListFromFilename(filename));
38
- }
39
- /**
40
- * Parses a word list from a string. The string should have multiple lines
41
- * with LF or CRLF line terminators.
42
- *
43
- * @param wordlist word list to merge entries into (may have existing entries)
44
- * @param filename filename of the word list
45
- */
46
- export function parseWordListFromContents(wordlist, contents) {
47
- ModelCompilerMessageContext.filename = undefined;
48
- _parseWordList(wordlist, new WordListFromMemory(contents));
49
- }
50
- /**
51
- * Reads a tab-separated values file into a word list. This function converts all
52
- * entries into NFC and merges duplicate entries across wordlists. Duplication is
53
- * on the basis of character-for-character equality after normalisation to NFC.
54
- *
55
- * Format specification:
56
- *
57
- * - the file is a UTF-8 encoded text file.
58
- * - new lines are either LF or CRLF.
59
- * - the file MAY start with the UTF-8 byte-order mark (BOM); that is, if the
60
- * first three bytes of the file are EF BB BF, these will be interepreted as
61
- * the BOM and will be ignored.
62
- * - the file either consists of a comment or an entry.
63
- * - comment lines MUST start with the '#' character on the very first column.
64
- * - entries are one to three columns, separated by the (horizontal) tab
65
- * character.
66
- * - column 1 (REQUIRED): the wordform: can have any character except tab, CR,
67
- * LF. Surrounding whitespace characters are trimmed.
68
- * - column 2 (optional): the count: a non-negative integer specifying how many
69
- * times this entry has appeared in the corpus. Blank means 'indeterminate';
70
- * commas are permissible in the digits.
71
- * - column 3 (optional): comment: an informative comment, ignored by the tool.
72
- *
73
- * @param wordlist word list to merge entries into (may have existing entries)
74
- * @param contents contents of the file to import
75
- */
76
- function _parseWordList(wordlist, source) {
77
- const TAB = "\t";
78
- let wordsSeenInThisFile = new Set();
79
- for (let [lineno, line] of source.lines()) {
80
- ModelCompilerMessageContext.line = lineno;
81
- // Remove the byte-order mark (BOM) from the beginning of the string.
82
- // Because `contents` can be the concatenation of several files, we have to remove
83
- // the BOM from every possible start of file -- i.e., beginning of every line.
84
- line = line.replace(/^\uFEFF/, '').trim();
85
- if (line.startsWith('#') || line === "") {
86
- continue; // skip comments and empty lines
87
- }
88
- // The third column is the comment. Always ignored!
89
- let [wordform, countText] = line.split(TAB);
90
- // Clean the word form.
91
- let original = wordform;
92
- wordform = wordform.normalize('NFC');
93
- if (original !== wordform) {
94
- // Mixed normalization forms are yucky! Warn about it.
95
- callbacks.reportMessage(ModelCompilerMessages.Warn_MixedNormalizationForms({ wordform: wordform }));
96
- }
97
- wordform = wordform.trim();
98
- countText = (countText || '').trim().replace(/,/g, '');
99
- let count = parseInt(countText, 10);
100
- // When parsing a decimal integer fails (e.g., blank or something else):
101
- if (!isFinite(count) || count < 0) {
102
- // TODO: is this the right thing to do?
103
- // Treat it like a hapax legonmenom -- it exist, but only once.
104
- count = 1;
105
- }
106
- if (wordsSeenInThisFile.has(wordform)) {
107
- // The same word seen across multiple files is fine,
108
- // but a word seen multiple times in one file is a problem!
109
- callbacks.reportMessage(ModelCompilerMessages.Warn_DuplicateWordInSameFile({ wordform: wordform }));
110
- }
111
- wordsSeenInThisFile.add(wordform);
112
- wordlist[wordform] = (isNaN(wordlist[wordform]) ? 0 : wordlist[wordform] || 0) + count;
113
- }
114
- }
115
- class WordListFromMemory {
116
- name = '<memory>';
117
- _contents;
118
- constructor(contents) {
119
- this._contents = contents;
120
- }
121
- *lines() {
122
- yield* enumerateLines(this._contents.split(NEWLINE_SEPARATOR));
123
- }
124
- }
125
- class WordListFromFilename {
126
- name;
127
- constructor(filename) {
128
- this.name = filename;
129
- }
130
- *lines() {
131
- let contents = readFileSync(this.name, detectEncoding(this.name));
132
- yield* enumerateLines(contents.split(NEWLINE_SEPARATOR));
133
- }
134
- }
135
- /**
136
- * Yields pairs of [lineno, line], given an Array of lines.
137
- */
138
- function* enumerateLines(lines) {
139
- let i = 1;
140
- for (let line of lines) {
141
- yield [i, line];
142
- i++;
143
- }
144
- }
145
- var Trie;
146
- (function (Trie_1) {
147
- /**
148
- * A sentinel value for when an internal node has contents and requires an
149
- * "internal" leaf. That is, this internal node has content. Instead of placing
150
- * entries as children in an internal node, a "fake" leaf is created, and its
151
- * key is this special internal value.
152
- *
153
- * The value is a valid Unicode BMP code point, but it is a "non-character".
154
- * Unicode will never assign semantics to these characters, as they are
155
- * intended to be used internally as sentinel values.
156
- */
157
- const INTERNAL_VALUE = '\uFDD0';
158
- /**
159
- * Builds a trie from a word list.
160
- *
161
- * @param wordlist The wordlist with non-negative weights.
162
- * @param keyFunction Function that converts word forms into indexed search keys
163
- * @returns A JSON-serialiable object that can be given to the TrieModel constructor.
164
- */
165
- function buildTrie(wordlist, keyFunction) {
166
- let root = new Trie(keyFunction).buildFromWordList(wordlist).root;
167
- return {
168
- totalWeight: sumWeights(root),
169
- root: root
170
- };
171
- }
172
- Trie_1.buildTrie = buildTrie;
173
- /**
174
- * Wrapper class for the trie and its nodes and wordform to search
175
- */
176
- class Trie {
177
- root = createRootNode();
178
- toKey;
179
- constructor(wordform2key) {
180
- this.toKey = wordform2key;
181
- }
182
- /**
183
- * Populates the trie with the contents of an entire wordlist.
184
- * @param words a list of word and count pairs.
185
- */
186
- buildFromWordList(words) {
187
- for (let [wordform, weight] of Object.entries(words)) {
188
- let key = this.toKey(wordform);
189
- addUnsorted(this.root, { key, weight, content: wordform }, 0);
190
- }
191
- sortTrie(this.root);
192
- return this;
193
- }
194
- }
195
- // "Constructors"
196
- function createRootNode() {
197
- return {
198
- type: 'leaf',
199
- weight: 0,
200
- entries: []
201
- };
202
- }
203
- // Implement Trie creation.
204
- /**
205
- * Adds an entry to the trie.
206
- *
207
- * Note that the trie will likely be unsorted after the add occurs. Before
208
- * performing a lookup on the trie, use call sortTrie() on the root note!
209
- *
210
- * @param node Which node should the entry be added to?
211
- * @param entry the wordform/weight/key to add to the trie
212
- * @param index the index in the key and also the trie depth. Should be set to
213
- * zero when adding onto the root node of the trie.
214
- */
215
- function addUnsorted(node, entry, index = 0) {
216
- // Each node stores the MAXIMUM weight out of all of its decesdents, to
217
- // enable a greedy search through the trie.
218
- node.weight = Math.max(node.weight, entry.weight);
219
- // When should a leaf become an interior node?
220
- // When it already has a value, but the key of the current value is longer
221
- // than the prefix.
222
- if (node.type === 'leaf' && index < entry.key.length && node.entries.length >= 1) {
223
- convertLeafToInternalNode(node, index);
224
- }
225
- if (node.type === 'leaf') {
226
- // The key matches this leaf node, so add yet another entry.
227
- addItemToLeaf(node, entry);
228
- }
229
- else {
230
- // Push the node down to a lower node.
231
- addItemToInternalNode(node, entry, index);
232
- }
233
- node.unsorted = true;
234
- }
235
- /**
236
- * Adds an item to the internal node at a given depth.
237
- * @param item
238
- * @param index
239
- */
240
- function addItemToInternalNode(node, item, index) {
241
- let char = item.key[index];
242
- if (!node.children[char]) {
243
- node.children[char] = createRootNode();
244
- node.values.push(char);
245
- }
246
- addUnsorted(node.children[char], item, index + 1);
247
- }
248
- function addItemToLeaf(leaf, item) {
249
- leaf.entries.push(item);
250
- }
251
- /**
252
- * Mutates the given Leaf to turn it into an InternalNode.
253
- *
254
- * NOTE: the node passed in will be DESTRUCTIVELY CHANGED into a different
255
- * type when passed into this function!
256
- *
257
- * @param depth depth of the trie at this level.
258
- */
259
- function convertLeafToInternalNode(leaf, depth) {
260
- let entries = leaf.entries;
261
- // Alias the current node, as the desired type.
262
- let internal = leaf;
263
- internal.type = 'internal';
264
- delete leaf.entries;
265
- internal.values = [];
266
- internal.children = {};
267
- // Convert the old values array into the format for interior nodes.
268
- for (let item of entries) {
269
- let char;
270
- if (depth < item.key.length) {
271
- char = item.key[depth];
272
- }
273
- else {
274
- char = INTERNAL_VALUE;
275
- }
276
- if (!internal.children[char]) {
277
- internal.children[char] = createRootNode();
278
- internal.values.push(char);
279
- }
280
- addUnsorted(internal.children[char], item, depth + 1);
281
- }
282
- internal.unsorted = true;
283
- }
284
- /**
285
- * Recursively sort the trie, in descending order of weight.
286
- * @param node any node in the trie
287
- */
288
- function sortTrie(node) {
289
- if (node.type === 'leaf') {
290
- if (!node.unsorted) {
291
- return;
292
- }
293
- node.entries.sort(function (a, b) { return b.weight - a.weight; });
294
- }
295
- else {
296
- // We MUST recurse and sort children before returning.
297
- for (let char of node.values) {
298
- sortTrie(node.children[char]);
299
- }
300
- if (!node.unsorted) {
301
- return;
302
- }
303
- node.values.sort((a, b) => {
304
- return node.children[b].weight - node.children[a].weight;
305
- });
306
- }
307
- delete node.unsorted;
308
- }
309
- /**
310
- * O(n) recursive traversal to sum the total weight of all leaves in the
311
- * trie, starting at the provided node.
312
- *
313
- * @param node The node to start summing weights.
314
- */
315
- function sumWeights(node) {
316
- let val;
317
- if (node.type === 'leaf') {
318
- val = node.entries
319
- .map(entry => entry.weight)
320
- //.map(entry => isNaN(entry.weight) ? 1 : entry.weight)
321
- .reduce((acc, count) => acc + count, 0);
322
- }
323
- else {
324
- val = Object.keys(node.children)
325
- .map((key) => sumWeights(node.children[key]))
326
- .reduce((acc, count) => acc + count, 0);
327
- }
328
- if (isNaN(val)) {
329
- throw new Error("Unexpected NaN has appeared!");
330
- }
331
- return val;
332
- }
333
- })(Trie || (Trie = {}));
334
- /**
335
- * Detects the encoding of a text file.
336
- *
337
- * Supported encodings are:
338
- *
339
- * - UTF-8, with or without BOM
340
- * - UTF-16, little endian, with BOM
341
- *
342
- * UTF-16 in big endian is explicitly NOT supported! The reason is two-fold:
343
- * 1) Node does not support it without resorting to an external library (or
344
- * swapping every byte in the file!); and 2) I'm not sure anything actually
345
- * outputs in this format anyway!
346
- *
347
- * @param filename filename of the file to detect encoding
348
- */
349
- function detectEncoding(filename) {
350
- let buffer = readFileSync(filename);
351
- // Note: BOM is U+FEFF
352
- // In little endian, this is 0xFF 0xFE
353
- if (buffer[0] == 0xFF && buffer[1] == 0xFE) {
354
- return 'utf16le';
355
- }
356
- else if (buffer[0] == 0xFE && buffer[1] == 0xFF) {
357
- // Big Endian, is NOT supported because Node does not support it (???)
358
- // See: https://stackoverflow.com/a/14551669/6626414
359
- throw new ModelCompilerError(ModelCompilerMessages.Error_UTF16BEUnsupported());
360
- }
361
- else {
362
- // Assume its in UTF-8, with or without a BOM.
363
- return 'utf8';
364
- }
365
- }
366
- //# sourceMappingURL=build-trie.js.map
1
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d4f5a692-30cf-590f-ae4c-c023b52c77cc")}catch(e){}}();
2
+ import { ModelCompilerError, ModelCompilerMessageContext, ModelCompilerMessages } from "./model-compiler-errors.js";
3
+ import { callbacks } from "./compiler-callbacks.js";
4
+ // Supports LF or CRLF line terminators.
5
+ const NEWLINE_SEPARATOR = /\u000d?\u000a/;
6
+ /**
7
+ * Returns a data structure that can be loaded by the TrieModel.
8
+ *
9
+ * It implements a **weighted** trie, whose indices (paths down the trie) are
10
+ * generated by a search key, and not concrete wordforms themselves.
11
+ *
12
+ * @param sourceFiles an array of source files that will be read to generate the trie.
13
+ */
14
+ export function createTrieDataStructure(filenames, searchTermToKey) {
15
+ if (typeof searchTermToKey !== "function") {
16
+ throw new ModelCompilerError(ModelCompilerMessages.Error_SearchTermToKeyMustBeExplicitlySpecified());
17
+ }
18
+ // Make one big word list out of all of the filenames provided.
19
+ let wordlist = {};
20
+ filenames.forEach(filename => parseWordListFromFilename(wordlist, filename));
21
+ let trie = Trie.buildTrie(wordlist, searchTermToKey);
22
+ return JSON.stringify(trie);
23
+ }
24
+ /**
25
+ * Parses a word list from a file, merging duplicate entries.
26
+ *
27
+ * The word list may be encoded in:
28
+ *
29
+ * - UTF-8, with or without BOM [exported by most software]
30
+ * - UTF-16, little endian, with BOM [exported by Microsoft Excel]
31
+ *
32
+ * @param wordlist word list to merge entries into (may have existing entries)
33
+ * @param filename filename of the word list
34
+ */
35
+ export function parseWordListFromFilename(wordlist, filename) {
36
+ ModelCompilerMessageContext.filename = filename;
37
+ _parseWordList(wordlist, new WordListFromFilename(filename));
38
+ }
39
+ /**
40
+ * Parses a word list from a string. The string should have multiple lines
41
+ * with LF or CRLF line terminators.
42
+ *
43
+ * @param wordlist word list to merge entries into (may have existing entries)
44
+ * @param filename filename of the word list
45
+ */
46
+ export function parseWordListFromContents(wordlist, contents) {
47
+ ModelCompilerMessageContext.filename = undefined;
48
+ _parseWordList(wordlist, new WordListFromMemory(contents));
49
+ }
50
+ /**
51
+ * Reads a tab-separated values file into a word list. This function converts all
52
+ * entries into NFC and merges duplicate entries across wordlists. Duplication is
53
+ * on the basis of character-for-character equality after normalisation to NFC.
54
+ *
55
+ * Format specification:
56
+ *
57
+ * - the file is a UTF-8 encoded text file.
58
+ * - new lines are either LF or CRLF.
59
+ * - the file MAY start with the UTF-8 byte-order mark (BOM); that is, if the
60
+ * first three bytes of the file are EF BB BF, these will be interepreted as
61
+ * the BOM and will be ignored.
62
+ * - the file either consists of a comment or an entry.
63
+ * - comment lines MUST start with the '#' character on the very first column.
64
+ * - entries are one to three columns, separated by the (horizontal) tab
65
+ * character.
66
+ * - column 1 (REQUIRED): the wordform: can have any character except tab, CR,
67
+ * LF. Surrounding whitespace characters are trimmed.
68
+ * - column 2 (optional): the count: a non-negative integer specifying how many
69
+ * times this entry has appeared in the corpus. Blank means 'indeterminate';
70
+ * commas are permissible in the digits.
71
+ * - column 3 (optional): comment: an informative comment, ignored by the tool.
72
+ *
73
+ * @param wordlist word list to merge entries into (may have existing entries)
74
+ * @param contents contents of the file to import
75
+ */
76
+ function _parseWordList(wordlist, source) {
77
+ const TAB = "\t";
78
+ let wordsSeenInThisFile = new Set();
79
+ for (let [lineno, line] of source.lines()) {
80
+ ModelCompilerMessageContext.line = lineno;
81
+ // Remove the byte-order mark (BOM) from the beginning of the string.
82
+ // Because `contents` can be the concatenation of several files, we have to remove
83
+ // the BOM from every possible start of file -- i.e., beginning of every line.
84
+ line = line.replace(/^\uFEFF/, '').trim();
85
+ if (line.startsWith('#') || line === "") {
86
+ continue; // skip comments and empty lines
87
+ }
88
+ // The third column is the comment. Always ignored!
89
+ let [wordform, countText] = line.split(TAB);
90
+ // Clean the word form.
91
+ let original = wordform;
92
+ wordform = wordform.normalize('NFC');
93
+ if (original !== wordform) {
94
+ // Mixed normalization forms are yucky! Warn about it.
95
+ callbacks.reportMessage(ModelCompilerMessages.Warn_MixedNormalizationForms({ wordform: wordform }));
96
+ }
97
+ wordform = wordform.trim();
98
+ countText = (countText || '').trim().replace(/,/g, '');
99
+ let count = parseInt(countText, 10);
100
+ // When parsing a decimal integer fails (e.g., blank or something else):
101
+ if (!isFinite(count) || count < 0) {
102
+ // TODO: is this the right thing to do?
103
+ // Treat it like a hapax legonmenom -- it exist, but only once.
104
+ count = 1;
105
+ }
106
+ if (wordsSeenInThisFile.has(wordform)) {
107
+ // The same word seen across multiple files is fine,
108
+ // but a word seen multiple times in one file is a problem!
109
+ callbacks.reportMessage(ModelCompilerMessages.Warn_DuplicateWordInSameFile({ wordform: wordform }));
110
+ }
111
+ wordsSeenInThisFile.add(wordform);
112
+ wordlist[wordform] = (isNaN(wordlist[wordform]) ? 0 : wordlist[wordform] || 0) + count;
113
+ }
114
+ }
115
+ class WordListFromMemory {
116
+ name = '<memory>';
117
+ _contents;
118
+ constructor(contents) {
119
+ this._contents = contents;
120
+ }
121
+ *lines() {
122
+ yield* enumerateLines(this._contents.split(NEWLINE_SEPARATOR));
123
+ }
124
+ }
125
+ class WordListFromFilename {
126
+ name;
127
+ constructor(filename) {
128
+ this.name = filename;
129
+ }
130
+ *lines() {
131
+ const data = callbacks.loadFile(this.name);
132
+ const contents = new TextDecoder(detectEncoding(data)).decode(data);
133
+ yield* enumerateLines(contents.split(NEWLINE_SEPARATOR));
134
+ }
135
+ }
136
+ /**
137
+ * Yields pairs of [lineno, line], given an Array of lines.
138
+ */
139
+ function* enumerateLines(lines) {
140
+ let i = 1;
141
+ for (let line of lines) {
142
+ yield [i, line];
143
+ i++;
144
+ }
145
+ }
146
+ var Trie;
147
+ (function (Trie_1) {
148
+ /**
149
+ * A sentinel value for when an internal node has contents and requires an
150
+ * "internal" leaf. That is, this internal node has content. Instead of placing
151
+ * entries as children in an internal node, a "fake" leaf is created, and its
152
+ * key is this special internal value.
153
+ *
154
+ * The value is a valid Unicode BMP code point, but it is a "non-character".
155
+ * Unicode will never assign semantics to these characters, as they are
156
+ * intended to be used internally as sentinel values.
157
+ */
158
+ const INTERNAL_VALUE = '\uFDD0';
159
+ /**
160
+ * Builds a trie from a word list.
161
+ *
162
+ * @param wordlist The wordlist with non-negative weights.
163
+ * @param keyFunction Function that converts word forms into indexed search keys
164
+ * @returns A JSON-serialiable object that can be given to the TrieModel constructor.
165
+ */
166
+ function buildTrie(wordlist, keyFunction) {
167
+ let root = new Trie(keyFunction).buildFromWordList(wordlist).root;
168
+ return {
169
+ totalWeight: sumWeights(root),
170
+ root: root
171
+ };
172
+ }
173
+ Trie_1.buildTrie = buildTrie;
174
+ /**
175
+ * Wrapper class for the trie and its nodes and wordform to search
176
+ */
177
+ class Trie {
178
+ root = createRootNode();
179
+ toKey;
180
+ constructor(wordform2key) {
181
+ this.toKey = wordform2key;
182
+ }
183
+ /**
184
+ * Populates the trie with the contents of an entire wordlist.
185
+ * @param words a list of word and count pairs.
186
+ */
187
+ buildFromWordList(words) {
188
+ for (let [wordform, weight] of Object.entries(words)) {
189
+ let key = this.toKey(wordform);
190
+ addUnsorted(this.root, { key, weight, content: wordform }, 0);
191
+ }
192
+ sortTrie(this.root);
193
+ return this;
194
+ }
195
+ }
196
+ // "Constructors"
197
+ function createRootNode() {
198
+ return {
199
+ type: 'leaf',
200
+ weight: 0,
201
+ entries: []
202
+ };
203
+ }
204
+ // Implement Trie creation.
205
+ /**
206
+ * Adds an entry to the trie.
207
+ *
208
+ * Note that the trie will likely be unsorted after the add occurs. Before
209
+ * performing a lookup on the trie, use call sortTrie() on the root note!
210
+ *
211
+ * @param node Which node should the entry be added to?
212
+ * @param entry the wordform/weight/key to add to the trie
213
+ * @param index the index in the key and also the trie depth. Should be set to
214
+ * zero when adding onto the root node of the trie.
215
+ */
216
+ function addUnsorted(node, entry, index = 0) {
217
+ // Each node stores the MAXIMUM weight out of all of its decesdents, to
218
+ // enable a greedy search through the trie.
219
+ node.weight = Math.max(node.weight, entry.weight);
220
+ // When should a leaf become an interior node?
221
+ // When it already has a value, but the key of the current value is longer
222
+ // than the prefix.
223
+ if (node.type === 'leaf' && index < entry.key.length && node.entries.length >= 1) {
224
+ convertLeafToInternalNode(node, index);
225
+ }
226
+ if (node.type === 'leaf') {
227
+ // The key matches this leaf node, so add yet another entry.
228
+ addItemToLeaf(node, entry);
229
+ }
230
+ else {
231
+ // Push the node down to a lower node.
232
+ addItemToInternalNode(node, entry, index);
233
+ }
234
+ node.unsorted = true;
235
+ }
236
+ /**
237
+ * Adds an item to the internal node at a given depth.
238
+ * @param item
239
+ * @param index
240
+ */
241
+ function addItemToInternalNode(node, item, index) {
242
+ let char = item.key[index];
243
+ if (!node.children[char]) {
244
+ node.children[char] = createRootNode();
245
+ node.values.push(char);
246
+ }
247
+ addUnsorted(node.children[char], item, index + 1);
248
+ }
249
+ function addItemToLeaf(leaf, item) {
250
+ leaf.entries.push(item);
251
+ }
252
+ /**
253
+ * Mutates the given Leaf to turn it into an InternalNode.
254
+ *
255
+ * NOTE: the node passed in will be DESTRUCTIVELY CHANGED into a different
256
+ * type when passed into this function!
257
+ *
258
+ * @param depth depth of the trie at this level.
259
+ */
260
+ function convertLeafToInternalNode(leaf, depth) {
261
+ let entries = leaf.entries;
262
+ // Alias the current node, as the desired type.
263
+ let internal = leaf;
264
+ internal.type = 'internal';
265
+ delete leaf.entries;
266
+ internal.values = [];
267
+ internal.children = {};
268
+ // Convert the old values array into the format for interior nodes.
269
+ for (let item of entries) {
270
+ let char;
271
+ if (depth < item.key.length) {
272
+ char = item.key[depth];
273
+ }
274
+ else {
275
+ char = INTERNAL_VALUE;
276
+ }
277
+ if (!internal.children[char]) {
278
+ internal.children[char] = createRootNode();
279
+ internal.values.push(char);
280
+ }
281
+ addUnsorted(internal.children[char], item, depth + 1);
282
+ }
283
+ internal.unsorted = true;
284
+ }
285
+ /**
286
+ * Recursively sort the trie, in descending order of weight.
287
+ * @param node any node in the trie
288
+ */
289
+ function sortTrie(node) {
290
+ if (node.type === 'leaf') {
291
+ if (!node.unsorted) {
292
+ return;
293
+ }
294
+ node.entries.sort(function (a, b) { return b.weight - a.weight; });
295
+ }
296
+ else {
297
+ // We MUST recurse and sort children before returning.
298
+ for (let char of node.values) {
299
+ sortTrie(node.children[char]);
300
+ }
301
+ if (!node.unsorted) {
302
+ return;
303
+ }
304
+ node.values.sort((a, b) => {
305
+ return node.children[b].weight - node.children[a].weight;
306
+ });
307
+ }
308
+ delete node.unsorted;
309
+ }
310
+ /**
311
+ * O(n) recursive traversal to sum the total weight of all leaves in the
312
+ * trie, starting at the provided node.
313
+ *
314
+ * @param node The node to start summing weights.
315
+ */
316
+ function sumWeights(node) {
317
+ let val;
318
+ if (node.type === 'leaf') {
319
+ val = node.entries
320
+ .map(entry => entry.weight)
321
+ //.map(entry => isNaN(entry.weight) ? 1 : entry.weight)
322
+ .reduce((acc, count) => acc + count, 0);
323
+ }
324
+ else {
325
+ val = Object.keys(node.children)
326
+ .map((key) => sumWeights(node.children[key]))
327
+ .reduce((acc, count) => acc + count, 0);
328
+ }
329
+ if (isNaN(val)) {
330
+ throw new Error("Unexpected NaN has appeared!");
331
+ }
332
+ return val;
333
+ }
334
+ })(Trie || (Trie = {}));
335
+ /**
336
+ * Detects the encoding of a text file.
337
+ *
338
+ * Supported encodings are:
339
+ *
340
+ * - UTF-8, with or without BOM
341
+ * - UTF-16, little endian, with BOM
342
+ *
343
+ * UTF-16 in big endian is explicitly NOT supported! The reason is two-fold:
344
+ * 1) Node does not support it without resorting to an external library (or
345
+ * swapping every byte in the file!); and 2) I'm not sure anything actually
346
+ * outputs in this format anyway!
347
+ *
348
+ * @param filename filename of the file to detect encoding
349
+ */
350
+ function detectEncoding(buffer) {
351
+ if (buffer.length < 2) {
352
+ return 'utf-8';
353
+ }
354
+ // Note: BOM is U+FEFF
355
+ // In little endian, this is 0xFF 0xFE
356
+ if (buffer[0] == 0xFF && buffer[1] == 0xFE) {
357
+ return 'utf-16le';
358
+ }
359
+ else if (buffer[0] == 0xFE && buffer[1] == 0xFF) {
360
+ // Big Endian, is NOT supported because Node does not support it (???)
361
+ // See: https://stackoverflow.com/a/14551669/6626414
362
+ throw new ModelCompilerError(ModelCompilerMessages.Error_UTF16BEUnsupported());
363
+ }
364
+ else {
365
+ // Assume its in UTF-8, with or without a BOM.
366
+ return 'utf-8';
367
+ }
368
+ }
369
+ //# debugId=d4f5a692-30cf-590f-ae4c-c023b52c77cc
370
+ //# sourceMappingURL=build-trie.js.map