bitgpu 0.5.0 → 0.7.0
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.
- package/README.md +105 -14
- package/THIRD_PARTY_LICENSES.md +19 -0
- package/dist/chat.d.ts +204 -0
- package/dist/chat.js +4946 -0
- package/dist/chat.js.map +1 -0
- package/dist/index.d.ts +2 -189
- package/dist/index.js +157 -61
- package/dist/index.js.map +1 -1
- package/dist/types-CsoJYJlG.d.ts +212 -0
- package/package.json +10 -2
package/dist/chat.js
ADDED
|
@@ -0,0 +1,4946 @@
|
|
|
1
|
+
//#region node_modules/@huggingface/tokenizers/dist/tokenizers.mjs
|
|
2
|
+
var DictionarySplitter = class {
|
|
3
|
+
/**
|
|
4
|
+
* @param dictionary The dictionary of words to use for splitting.
|
|
5
|
+
*/
|
|
6
|
+
constructor(dictionary) {
|
|
7
|
+
this.trie = this._build_trie(dictionary);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Builds a trie from the given dictionary.
|
|
11
|
+
* @param dictionary The dictionary of words to build the trie from.
|
|
12
|
+
* @returns The root node of the trie.
|
|
13
|
+
* @private
|
|
14
|
+
*/
|
|
15
|
+
_build_trie(dictionary) {
|
|
16
|
+
const trie = /* @__PURE__ */ Object.create(null);
|
|
17
|
+
for (const word of dictionary) {
|
|
18
|
+
let node = trie;
|
|
19
|
+
for (let i = 0; i < word.length; ++i) {
|
|
20
|
+
const char = word[i];
|
|
21
|
+
node = node[char] ??= /* @__PURE__ */ Object.create(null);
|
|
22
|
+
}
|
|
23
|
+
node.end = word;
|
|
24
|
+
}
|
|
25
|
+
return trie;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Splits the input text into tokens based on the dictionary.
|
|
29
|
+
* @param text The input text to split.
|
|
30
|
+
* @returns An array of tokens.
|
|
31
|
+
*/
|
|
32
|
+
split(text) {
|
|
33
|
+
const result = [];
|
|
34
|
+
const n = text.length;
|
|
35
|
+
let start = 0;
|
|
36
|
+
let i = 0;
|
|
37
|
+
while (i < n) {
|
|
38
|
+
let node = this.trie;
|
|
39
|
+
let match = null;
|
|
40
|
+
let j = i;
|
|
41
|
+
while (j < n && (node = node[text[j]])) {
|
|
42
|
+
if (node.end) match = node.end;
|
|
43
|
+
++j;
|
|
44
|
+
}
|
|
45
|
+
if (match) {
|
|
46
|
+
if (i > start) result.push(text.slice(start, i));
|
|
47
|
+
result.push(match);
|
|
48
|
+
i += match.length;
|
|
49
|
+
start = i;
|
|
50
|
+
} else ++i;
|
|
51
|
+
}
|
|
52
|
+
if (start < n) result.push(text.slice(start));
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
var DictionarySplitter_default = DictionarySplitter;
|
|
57
|
+
var AddedToken = class {
|
|
58
|
+
/**
|
|
59
|
+
* Creates a new instance of AddedToken.
|
|
60
|
+
* @param config Added token configuration object.
|
|
61
|
+
*/
|
|
62
|
+
constructor(config) {
|
|
63
|
+
this.content = config.content;
|
|
64
|
+
this.id = config.id;
|
|
65
|
+
this.single_word = config.single_word ?? false;
|
|
66
|
+
this.lstrip = config.lstrip ?? false;
|
|
67
|
+
this.rstrip = config.rstrip ?? false;
|
|
68
|
+
this.special = config.special ?? false;
|
|
69
|
+
this.normalized = config.normalized ?? !this.special;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
var AddedToken_default = AddedToken;
|
|
73
|
+
var BYTES_TO_UNICODE = (() => {
|
|
74
|
+
const bs = [
|
|
75
|
+
...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
|
|
76
|
+
...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
|
|
77
|
+
...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0))
|
|
78
|
+
];
|
|
79
|
+
const cs = bs.slice();
|
|
80
|
+
let n = 0;
|
|
81
|
+
for (let b = 0; b < 256; ++b) if (!bs.includes(b)) {
|
|
82
|
+
bs.push(b);
|
|
83
|
+
cs.push(256 + n);
|
|
84
|
+
n += 1;
|
|
85
|
+
}
|
|
86
|
+
const ccs = cs.map((n2) => String.fromCharCode(n2));
|
|
87
|
+
return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
|
|
88
|
+
})();
|
|
89
|
+
var reverse_dictionary = (data) => Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
|
|
90
|
+
var UNICODE_TO_BYTES = reverse_dictionary(BYTES_TO_UNICODE);
|
|
91
|
+
var BLOOM_SPLIT_CHARS = ".,!?…。,、।۔،";
|
|
92
|
+
var PROBLEMATIC_REGEX_MAP = /* @__PURE__ */ new Map([
|
|
93
|
+
["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],
|
|
94
|
+
["(?i:[sdmt]|ll|ve|re)", "(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],
|
|
95
|
+
["[^\\r\\n\\p{L}\\p{N}]?+", "[^\\r\\n\\p{L}\\p{N}]?"],
|
|
96
|
+
["[^\\s\\p{L}\\p{N}]++", "[^\\s\\p{L}\\p{N}]+"],
|
|
97
|
+
["(?>\\p{Nd}{510})", "(?:\\p{Nd}{510})"],
|
|
98
|
+
["\\p{Nd}{3}+", "(?:\\p{Nd}{3})+"],
|
|
99
|
+
["\\G", ""],
|
|
100
|
+
[` ?[^(\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\s${BLOOM_SPLIT_CHARS}]+`]
|
|
101
|
+
]);
|
|
102
|
+
var PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";
|
|
103
|
+
var clean_up_tokenization = (text) => text.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n't/g, "n't").replace(/ 'm/g, "'m").replace(/ 's/g, "'s").replace(/ 've/g, "'ve").replace(/ 're/g, "'re");
|
|
104
|
+
var create_pattern = (pattern, invert = true) => {
|
|
105
|
+
if (pattern.Regex !== void 0) {
|
|
106
|
+
let regex = pattern.Regex.replace(/\\([#&~])/g, "$1");
|
|
107
|
+
regex = regex.replace(/\\A/g, "^").replace(/\\z/g, "$").replace(/\\Z/g, "(?=\\r?\\n?$)");
|
|
108
|
+
for (const [key, value] of PROBLEMATIC_REGEX_MAP) regex = regex.replaceAll(key, value);
|
|
109
|
+
try {
|
|
110
|
+
return new RegExp(regex, "gu");
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (!(error instanceof SyntaxError) || !error.message.toLowerCase().includes("invalid property name")) throw error;
|
|
113
|
+
let changed = false;
|
|
114
|
+
const fixed = regex.replace(/(\\[pP])\{([^}=]+)\}/g, (_, p, n) => {
|
|
115
|
+
try {
|
|
116
|
+
new RegExp(`\\p{${n}}`, "u");
|
|
117
|
+
return `${p}{${n}}`;
|
|
118
|
+
} catch {
|
|
119
|
+
changed = true;
|
|
120
|
+
return `${p}{Script=${n}}`;
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
if (!changed) throw error;
|
|
124
|
+
try {
|
|
125
|
+
return new RegExp(fixed, "gu");
|
|
126
|
+
} catch (e) {
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
} else if (pattern.String !== void 0) {
|
|
131
|
+
const escaped = escape_reg_exp(pattern.String);
|
|
132
|
+
return new RegExp(invert ? escaped : `(${escaped})`, "gu");
|
|
133
|
+
} else {
|
|
134
|
+
console.warn("Unknown pattern type:", pattern);
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
var escape_reg_exp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
139
|
+
var fuse_unk = (arr, tokens_to_ids, unk_token_id) => {
|
|
140
|
+
const fused = [];
|
|
141
|
+
let i = 0;
|
|
142
|
+
while (i < arr.length) {
|
|
143
|
+
fused.push(arr[i]);
|
|
144
|
+
if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {
|
|
145
|
+
++i;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) fused[fused.length - 1] += arr[i];
|
|
149
|
+
}
|
|
150
|
+
return fused;
|
|
151
|
+
};
|
|
152
|
+
var is_chinese_char = (cp) => cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103;
|
|
153
|
+
var is_integral_number = (x) => Number.isInteger(x) || typeof x === "bigint";
|
|
154
|
+
var len = (s) => {
|
|
155
|
+
let length = 0;
|
|
156
|
+
for (const c of s) ++length;
|
|
157
|
+
return length;
|
|
158
|
+
};
|
|
159
|
+
var lowercase_and_remove_accents = (text) => remove_accents(text.toLowerCase());
|
|
160
|
+
var merge_arrays = (...arrs) => Array.prototype.concat.apply([], arrs);
|
|
161
|
+
var object_to_map = (obj) => new Map(Object.entries(obj));
|
|
162
|
+
var regex_split = (text, regex) => {
|
|
163
|
+
const result = [];
|
|
164
|
+
let prev = 0;
|
|
165
|
+
for (const match of text.matchAll(regex)) {
|
|
166
|
+
const full_match = match[0];
|
|
167
|
+
if (prev < match.index) result.push(text.slice(prev, match.index));
|
|
168
|
+
if (full_match.length > 0) result.push(full_match);
|
|
169
|
+
prev = match.index + full_match.length;
|
|
170
|
+
}
|
|
171
|
+
if (prev < text.length) result.push(text.slice(prev));
|
|
172
|
+
return result;
|
|
173
|
+
};
|
|
174
|
+
var remove_accents = (text) => text.replace(/\p{M}/gu, "");
|
|
175
|
+
var validate_object = (obj, name, required_keys = []) => {
|
|
176
|
+
if (!obj || Array.isArray(obj) || typeof obj !== "object") return `${name} must be a valid object`;
|
|
177
|
+
for (const key of required_keys) if (!(key in obj)) return `${name} must contain a "${key}" property`;
|
|
178
|
+
return null;
|
|
179
|
+
};
|
|
180
|
+
var whitespace_split = (text) => text.match(/\S+/g) || [];
|
|
181
|
+
var Callable = class {
|
|
182
|
+
/**
|
|
183
|
+
* Creates a new instance of the Callable class.
|
|
184
|
+
*/
|
|
185
|
+
constructor() {
|
|
186
|
+
const closure = function(...args) {
|
|
187
|
+
return closure._call(...args);
|
|
188
|
+
};
|
|
189
|
+
return Object.setPrototypeOf(closure, new.target.prototype);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
var Callable_default = Callable;
|
|
193
|
+
var Normalizer = class extends Callable_default {
|
|
194
|
+
/**
|
|
195
|
+
* @param config The configuration object for the normalizer.
|
|
196
|
+
*/
|
|
197
|
+
constructor(config) {
|
|
198
|
+
super();
|
|
199
|
+
this.config = config;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Alias for {@link Normalizer#normalize}.
|
|
203
|
+
* @param text The text to normalize.
|
|
204
|
+
* @returns The normalized text.
|
|
205
|
+
*/
|
|
206
|
+
_call(text) {
|
|
207
|
+
return this.normalize(text);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
var Normalizer_default = Normalizer;
|
|
211
|
+
var BertNormalizer = class extends Normalizer_default {
|
|
212
|
+
/**
|
|
213
|
+
* Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
|
|
214
|
+
*
|
|
215
|
+
* @param text The input text to tokenize.
|
|
216
|
+
* @returns The tokenized text with whitespace added around CJK characters.
|
|
217
|
+
*/
|
|
218
|
+
tokenize_chinese_chars(text) {
|
|
219
|
+
const output = [];
|
|
220
|
+
for (let i = 0; i < text.length; ++i) {
|
|
221
|
+
const char = text[i];
|
|
222
|
+
if (is_chinese_char(char.charCodeAt(0))) {
|
|
223
|
+
output.push(" ");
|
|
224
|
+
output.push(char);
|
|
225
|
+
output.push(" ");
|
|
226
|
+
} else output.push(char);
|
|
227
|
+
}
|
|
228
|
+
return output.join("");
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Strips accents from the given text.
|
|
232
|
+
* @param text The text to strip accents from.
|
|
233
|
+
* @returns The text with accents removed.
|
|
234
|
+
*/
|
|
235
|
+
strip_accents(text) {
|
|
236
|
+
return text.normalize("NFD").replace(/\p{Mn}/gu, "");
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Checks whether `char` is a control character.
|
|
240
|
+
* @param char The character to check.
|
|
241
|
+
* @returns Whether `char` is a control character.
|
|
242
|
+
*/
|
|
243
|
+
is_control(char) {
|
|
244
|
+
switch (char) {
|
|
245
|
+
case " ":
|
|
246
|
+
case "\n":
|
|
247
|
+
case "\r": return false;
|
|
248
|
+
default: return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Performs invalid character removal and whitespace cleanup on text.
|
|
253
|
+
* @param text The text to clean.
|
|
254
|
+
* @returns The cleaned text.
|
|
255
|
+
*/
|
|
256
|
+
clean_text(text) {
|
|
257
|
+
const output = [];
|
|
258
|
+
for (const char of text) {
|
|
259
|
+
const cp = char.charCodeAt(0);
|
|
260
|
+
if (cp === 0 || cp === 65533 || this.is_control(char)) continue;
|
|
261
|
+
if (/^\s$/.test(char)) output.push(" ");
|
|
262
|
+
else output.push(char);
|
|
263
|
+
}
|
|
264
|
+
return output.join("");
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Normalizes the given text based on the configuration.
|
|
268
|
+
* @param text The text to normalize.
|
|
269
|
+
* @returns The normalized text.
|
|
270
|
+
*/
|
|
271
|
+
normalize(text) {
|
|
272
|
+
if (this.config.clean_text) text = this.clean_text(text);
|
|
273
|
+
if (this.config.handle_chinese_chars) text = this.tokenize_chinese_chars(text);
|
|
274
|
+
if (this.config.lowercase) {
|
|
275
|
+
text = text.toLowerCase();
|
|
276
|
+
if (this.config.strip_accents !== false) text = this.strip_accents(text);
|
|
277
|
+
} else if (this.config.strip_accents) text = this.strip_accents(text);
|
|
278
|
+
return text;
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
var BertNormalizer_default = BertNormalizer;
|
|
282
|
+
var Precompiled = class extends Normalizer_default {
|
|
283
|
+
/**
|
|
284
|
+
* Create a new instance of Precompiled normalizer.
|
|
285
|
+
* @param config The configuration object.
|
|
286
|
+
*/
|
|
287
|
+
constructor(config) {
|
|
288
|
+
super(config);
|
|
289
|
+
this.charsmap = config.precompiled_charsmap ?? null;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Normalizes the given text by applying the precompiled charsmap.
|
|
293
|
+
* @param text The text to normalize.
|
|
294
|
+
* @returns The normalized text.
|
|
295
|
+
*/
|
|
296
|
+
normalize(text) {
|
|
297
|
+
text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, "");
|
|
298
|
+
text = text.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm, " ");
|
|
299
|
+
if (text.includes("~")) text = text.split("~").map((part) => part.normalize("NFKC")).join("~");
|
|
300
|
+
else text = text.normalize("NFKC");
|
|
301
|
+
return text;
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
var Precompiled_default = Precompiled;
|
|
305
|
+
var Sequence = class extends Normalizer_default {
|
|
306
|
+
/**
|
|
307
|
+
* Create a new instance of NormalizerSequence.
|
|
308
|
+
* @param config The configuration object.
|
|
309
|
+
*/
|
|
310
|
+
constructor(config) {
|
|
311
|
+
super(config);
|
|
312
|
+
this.normalizers = (config.normalizers ?? []).map((x) => create_normalizer_default(x));
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Apply a sequence of Normalizers to the input text.
|
|
316
|
+
* @param text The text to normalize.
|
|
317
|
+
* @returns The normalized text.
|
|
318
|
+
*/
|
|
319
|
+
normalize(text) {
|
|
320
|
+
return this.normalizers.reduce((t, normalizer) => {
|
|
321
|
+
return normalizer ? normalizer.normalize(t) : t;
|
|
322
|
+
}, text);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
var Sequence_default = Sequence;
|
|
326
|
+
var Replace = class extends Normalizer_default {
|
|
327
|
+
/**
|
|
328
|
+
* Normalize the input text by replacing the pattern with the content.
|
|
329
|
+
* @param text The input text to be normalized.
|
|
330
|
+
* @returns The normalized text after replacing the pattern with the content.
|
|
331
|
+
*/
|
|
332
|
+
normalize(text) {
|
|
333
|
+
const pattern = create_pattern(this.config.pattern ?? {});
|
|
334
|
+
return pattern === null ? text : text.replaceAll(pattern, this.config.content ?? "");
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
var Replace_default = Replace;
|
|
338
|
+
var UnicodeNormalizer = class extends Normalizer_default {
|
|
339
|
+
constructor() {
|
|
340
|
+
super(...arguments);
|
|
341
|
+
/**
|
|
342
|
+
* The Unicode normalization form to apply.
|
|
343
|
+
* Should be one of: 'NFC', 'NFD', 'NFKC', or 'NFKD'.
|
|
344
|
+
*/
|
|
345
|
+
this.form = "NFC";
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Normalize the input text by applying Unicode normalization.
|
|
349
|
+
* @param text The input text to be normalized.
|
|
350
|
+
* @returns The normalized text.
|
|
351
|
+
*/
|
|
352
|
+
normalize(text) {
|
|
353
|
+
text = text.normalize(this.form);
|
|
354
|
+
return text;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
var UnicodeNormalizer_default = UnicodeNormalizer;
|
|
358
|
+
var NFC = class extends UnicodeNormalizer_default {
|
|
359
|
+
constructor() {
|
|
360
|
+
super(...arguments);
|
|
361
|
+
this.form = "NFC";
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
var NFC_default = NFC;
|
|
365
|
+
var NFD = class extends UnicodeNormalizer_default {
|
|
366
|
+
constructor() {
|
|
367
|
+
super(...arguments);
|
|
368
|
+
this.form = "NFD";
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
var NFD_default = NFD;
|
|
372
|
+
var NFKC = class extends UnicodeNormalizer_default {
|
|
373
|
+
constructor() {
|
|
374
|
+
super(...arguments);
|
|
375
|
+
this.form = "NFKC";
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
var NFKC_default = NFKC;
|
|
379
|
+
var NFKD = class extends UnicodeNormalizer_default {
|
|
380
|
+
constructor() {
|
|
381
|
+
super(...arguments);
|
|
382
|
+
this.form = "NFKD";
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
var NFKD_default = NFKD;
|
|
386
|
+
var Strip = class extends Normalizer_default {
|
|
387
|
+
/**
|
|
388
|
+
* Strip leading and/or trailing whitespace from the input text.
|
|
389
|
+
* @param text The input text.
|
|
390
|
+
* @returns The normalized text.
|
|
391
|
+
*/
|
|
392
|
+
normalize(text) {
|
|
393
|
+
if (this.config.strip_left && this.config.strip_right) text = text.trim();
|
|
394
|
+
else {
|
|
395
|
+
if (this.config.strip_left) text = text.trimStart();
|
|
396
|
+
if (this.config.strip_right) text = text.trimEnd();
|
|
397
|
+
}
|
|
398
|
+
return text;
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
var Strip_default = Strip;
|
|
402
|
+
var StripAccents = class extends Normalizer_default {
|
|
403
|
+
/**
|
|
404
|
+
* Remove all accents from the text.
|
|
405
|
+
* @param text The input text.
|
|
406
|
+
* @returns The normalized text without accents.
|
|
407
|
+
*/
|
|
408
|
+
normalize(text) {
|
|
409
|
+
return remove_accents(text);
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
var StripAccents_default = StripAccents;
|
|
413
|
+
var Lowercase = class extends Normalizer_default {
|
|
414
|
+
/**
|
|
415
|
+
* Lowercases the input string.
|
|
416
|
+
* @param {string} text The text to normalize.
|
|
417
|
+
* @returns {string} The normalized text.
|
|
418
|
+
*/
|
|
419
|
+
normalize(text) {
|
|
420
|
+
return text.toLowerCase();
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
var Lowercase_default = Lowercase;
|
|
424
|
+
var Prepend = class extends Normalizer_default {
|
|
425
|
+
/**
|
|
426
|
+
* Prepends the input string.
|
|
427
|
+
* @param text The text to normalize.
|
|
428
|
+
* @returns The normalized text.
|
|
429
|
+
*/
|
|
430
|
+
normalize(text) {
|
|
431
|
+
text = this.config.prepend + text;
|
|
432
|
+
return text;
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
var Prepend_default = Prepend;
|
|
436
|
+
function create_normalizer(config) {
|
|
437
|
+
if (config === null) return null;
|
|
438
|
+
switch (config.type) {
|
|
439
|
+
case "BertNormalizer": return new BertNormalizer_default(config);
|
|
440
|
+
case "Precompiled": return new Precompiled_default(config);
|
|
441
|
+
case "Sequence": return new Sequence_default(config);
|
|
442
|
+
case "Replace": return new Replace_default(config);
|
|
443
|
+
case "NFC": return new NFC_default(config);
|
|
444
|
+
case "NFD": return new NFD_default(config);
|
|
445
|
+
case "NFKC": return new NFKC_default(config);
|
|
446
|
+
case "NFKD": return new NFKD_default(config);
|
|
447
|
+
case "Strip": return new Strip_default(config);
|
|
448
|
+
case "StripAccents": return new StripAccents_default(config);
|
|
449
|
+
case "Lowercase": return new Lowercase_default(config);
|
|
450
|
+
case "Prepend": return new Prepend_default(config);
|
|
451
|
+
default: throw new Error(`Unknown Normalizer type: ${config.type}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
var create_normalizer_default = create_normalizer;
|
|
455
|
+
var PreTokenizer = class extends Callable_default {
|
|
456
|
+
/**
|
|
457
|
+
* Tokenizes the given text into pre-tokens.
|
|
458
|
+
* @param text The text or array of texts to pre-tokenize.
|
|
459
|
+
* @param options Additional options for the pre-tokenization logic.
|
|
460
|
+
* @returns An array of pre-tokens.
|
|
461
|
+
*/
|
|
462
|
+
pre_tokenize(text, options) {
|
|
463
|
+
return (Array.isArray(text) ? text.map((x) => this.pre_tokenize_text(x, options)) : this.pre_tokenize_text(text, options)).flat();
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Alias for {@link PreTokenizer#pre_tokenize}.
|
|
467
|
+
* @param text The text or array of texts to pre-tokenize.
|
|
468
|
+
* @param options Additional options for the pre-tokenization logic.
|
|
469
|
+
* @returns An array of pre-tokens.
|
|
470
|
+
*/
|
|
471
|
+
_call(text, options) {
|
|
472
|
+
return this.pre_tokenize(text, options);
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
var PreTokenizer_default = PreTokenizer;
|
|
476
|
+
var ByteLevel = class extends PreTokenizer_default {
|
|
477
|
+
/**
|
|
478
|
+
* Creates a new instance of the `ByteLevelPreTokenizer` class.
|
|
479
|
+
* @param config The configuration object.
|
|
480
|
+
*/
|
|
481
|
+
constructor(config) {
|
|
482
|
+
super();
|
|
483
|
+
this.config = config;
|
|
484
|
+
this.add_prefix_space = this.config.add_prefix_space ?? false;
|
|
485
|
+
this.trim_offsets = this.config.trim_offsets ?? false;
|
|
486
|
+
this.use_regex = this.config.use_regex ?? true;
|
|
487
|
+
this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
|
|
488
|
+
this.byte_encoder = BYTES_TO_UNICODE;
|
|
489
|
+
this.text_encoder = new TextEncoder();
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Tokenizes a single piece of text using byte-level tokenization.
|
|
493
|
+
* @param text The text to tokenize.
|
|
494
|
+
* @param options Additional options for the pre-tokenization logic.
|
|
495
|
+
* @returns An array of tokens.
|
|
496
|
+
*/
|
|
497
|
+
pre_tokenize_text(text, options) {
|
|
498
|
+
if (this.add_prefix_space && !text.startsWith(" ")) text = " " + text;
|
|
499
|
+
return (this.use_regex ? text.match(this.pattern) || [] : [text]).map((token) => Array.from(this.text_encoder.encode(token), (byte) => this.byte_encoder[byte]).join(""));
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
var ByteLevel_default = ByteLevel;
|
|
503
|
+
var Whitespace = class extends PreTokenizer_default {
|
|
504
|
+
/**
|
|
505
|
+
* Pre-tokenizes the input text by splitting it on word boundaries.
|
|
506
|
+
* @param text The text to be pre-tokenized.
|
|
507
|
+
* @param options Additional options for the pre-tokenization logic.
|
|
508
|
+
* @returns An array of tokens produced by splitting the input text on whitespace.
|
|
509
|
+
*/
|
|
510
|
+
pre_tokenize_text(text, options) {
|
|
511
|
+
return text.match(/\w+|[^\w\s]+/g) || [];
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
var Whitespace_default = Whitespace;
|
|
515
|
+
var Metaspace = class extends PreTokenizer_default {
|
|
516
|
+
/**
|
|
517
|
+
* @param config The configuration object for the MetaspacePreTokenizer.
|
|
518
|
+
*/
|
|
519
|
+
constructor(config) {
|
|
520
|
+
super();
|
|
521
|
+
this.replacement = config.replacement ?? "▁";
|
|
522
|
+
this.str_rep = config.str_rep || this.replacement;
|
|
523
|
+
this.prepend_scheme = config.prepend_scheme ?? "always";
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* This method takes a string, replaces spaces with the replacement character,
|
|
527
|
+
* adds a prefix space if requested, and returns a new list of tokens.
|
|
528
|
+
* @param text The text to pre-tokenize.
|
|
529
|
+
* @param options The options for the pre-tokenization.
|
|
530
|
+
* @returns A new list of pre-tokenized tokens.
|
|
531
|
+
*/
|
|
532
|
+
pre_tokenize_text(text, options) {
|
|
533
|
+
const { section_index = void 0 } = options ?? {};
|
|
534
|
+
let normalized = text.replaceAll(" ", this.str_rep);
|
|
535
|
+
if (!normalized.startsWith(this.replacement) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && section_index === 0)) normalized = this.str_rep + normalized;
|
|
536
|
+
return [normalized];
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
var Metaspace_default = Metaspace;
|
|
540
|
+
var Split = class extends PreTokenizer_default {
|
|
541
|
+
/**
|
|
542
|
+
* @param config The configuration options for the pre-tokenizer.
|
|
543
|
+
*/
|
|
544
|
+
constructor(config) {
|
|
545
|
+
super();
|
|
546
|
+
this.config = config;
|
|
547
|
+
this.pattern = create_pattern(this.config.pattern ?? {}, this.config.invert ?? true);
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Tokenizes text by splitting it using the given pattern.
|
|
551
|
+
* @param text The text to tokenize.
|
|
552
|
+
* @returns An array of tokens.
|
|
553
|
+
*/
|
|
554
|
+
pre_tokenize_text(text) {
|
|
555
|
+
if (this.pattern === null) return [];
|
|
556
|
+
if (this.config.invert) return text.match(this.pattern) || [];
|
|
557
|
+
else if (this.config.behavior?.toLowerCase() === "removed") return text.split(this.pattern).filter((x) => x);
|
|
558
|
+
else return regex_split(text, this.pattern);
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
var Split_default = Split;
|
|
562
|
+
var Punctuation = class extends PreTokenizer_default {
|
|
563
|
+
/**
|
|
564
|
+
* @param config The configuration options for the pre-tokenizer.
|
|
565
|
+
*/
|
|
566
|
+
constructor(config) {
|
|
567
|
+
super();
|
|
568
|
+
this.config = config;
|
|
569
|
+
this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, "gu");
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Tokenizes text by splitting it using the given pattern.
|
|
573
|
+
* @param text The text to tokenize.
|
|
574
|
+
* @returns An array of tokens.
|
|
575
|
+
*/
|
|
576
|
+
pre_tokenize_text(text) {
|
|
577
|
+
return text.match(this.pattern) || [];
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
var Punctuation_default = Punctuation;
|
|
581
|
+
var Digits = class extends PreTokenizer_default {
|
|
582
|
+
/**
|
|
583
|
+
* @param config The configuration options for the pre-tokenizer.
|
|
584
|
+
*/
|
|
585
|
+
constructor(config) {
|
|
586
|
+
super();
|
|
587
|
+
this.config = config;
|
|
588
|
+
const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`;
|
|
589
|
+
this.pattern = new RegExp(digit_pattern, "gu");
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Tokenizes text by splitting it using the given pattern.
|
|
593
|
+
* @param text The text to tokenize.
|
|
594
|
+
* @returns An array of tokens.
|
|
595
|
+
*/
|
|
596
|
+
pre_tokenize_text(text) {
|
|
597
|
+
return text.match(this.pattern) || [];
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
var Digits_default = Digits;
|
|
601
|
+
var BertPreTokenizer = class extends PreTokenizer_default {
|
|
602
|
+
/**
|
|
603
|
+
* A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
|
|
604
|
+
* similar to that used in the original implementation of BERT.
|
|
605
|
+
*/
|
|
606
|
+
constructor() {
|
|
607
|
+
super();
|
|
608
|
+
this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, "gu");
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Tokenizes a single text using the BERT pre-tokenization scheme.
|
|
612
|
+
*
|
|
613
|
+
* @param text The text to tokenize.
|
|
614
|
+
* @param options Additional options for the pre-tokenization logic.
|
|
615
|
+
* @returns An array of tokens.
|
|
616
|
+
*/
|
|
617
|
+
pre_tokenize_text(text, options) {
|
|
618
|
+
return text.trim().match(this.pattern) || [];
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
var BertPreTokenizer_default = BertPreTokenizer;
|
|
622
|
+
var Replace2 = class extends PreTokenizer_default {
|
|
623
|
+
/**
|
|
624
|
+
* @param config The configuration options for the pre-tokenizer.
|
|
625
|
+
*/
|
|
626
|
+
constructor(config) {
|
|
627
|
+
super();
|
|
628
|
+
this.config = config;
|
|
629
|
+
this.pattern = create_pattern(this.config.pattern ?? {});
|
|
630
|
+
this.content = this.config.content ?? "";
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Pre-tokenizes the input text by replacing certain characters.
|
|
634
|
+
* @param text The text to be pre-tokenized.
|
|
635
|
+
* @returns An array of tokens produced by replacing certain characters.
|
|
636
|
+
*/
|
|
637
|
+
pre_tokenize_text(text) {
|
|
638
|
+
if (this.pattern === null) return [text];
|
|
639
|
+
return [text.replaceAll(this.pattern, this.config.content ?? "")];
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
var Replace_default2 = Replace2;
|
|
643
|
+
var Sequence2 = class extends PreTokenizer_default {
|
|
644
|
+
/**
|
|
645
|
+
* Creates an instance of PreTokenizerSequence.
|
|
646
|
+
* @param config The configuration object for the pre-tokenizer sequence.
|
|
647
|
+
*/
|
|
648
|
+
constructor(config) {
|
|
649
|
+
super();
|
|
650
|
+
this.tokenizers = (config.pretokenizers ?? []).map((x) => create_pre_tokenizer_default(x));
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Applies each pre-tokenizer in the sequence to the input text in turn.
|
|
654
|
+
* @param text The text to pre-tokenize.
|
|
655
|
+
* @param options Additional options for the pre-tokenization logic.
|
|
656
|
+
* @returns The pre-tokenized text.
|
|
657
|
+
*/
|
|
658
|
+
pre_tokenize_text(text, options) {
|
|
659
|
+
return this.tokenizers.reduce((pre_tokenized_text, tokenizer) => {
|
|
660
|
+
return tokenizer ? tokenizer.pre_tokenize(pre_tokenized_text, options) : pre_tokenized_text;
|
|
661
|
+
}, [text]);
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
var Sequence_default2 = Sequence2;
|
|
665
|
+
var WhitespaceSplit = class extends PreTokenizer_default {
|
|
666
|
+
/**
|
|
667
|
+
* Pre-tokenizes the input text by splitting it on whitespace characters.
|
|
668
|
+
* @param text The text to be pre-tokenized.
|
|
669
|
+
* @returns An array of tokens produced by splitting the input text on whitespace.
|
|
670
|
+
*/
|
|
671
|
+
pre_tokenize_text(text) {
|
|
672
|
+
return whitespace_split(text);
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
var WhitespaceSplit_default = WhitespaceSplit;
|
|
676
|
+
var FixedLength = class extends PreTokenizer_default {
|
|
677
|
+
/**
|
|
678
|
+
* @param config The configuration options for the pre-tokenizer.
|
|
679
|
+
*/
|
|
680
|
+
constructor(config) {
|
|
681
|
+
super();
|
|
682
|
+
this.config = config;
|
|
683
|
+
this._length = config.length;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Pre-tokenizes the input text by splitting it into fixed-length tokens.
|
|
687
|
+
* @param text The text to be pre-tokenized.
|
|
688
|
+
* @returns An array of tokens produced by splitting the input text into fixed-length tokens.
|
|
689
|
+
*/
|
|
690
|
+
pre_tokenize_text(text) {
|
|
691
|
+
const tokens = [];
|
|
692
|
+
for (let i = 0; i < text.length; i += this._length) tokens.push(text.slice(i, i + this._length));
|
|
693
|
+
return tokens;
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
var FixedLength_default = FixedLength;
|
|
697
|
+
function create_pre_tokenizer(config) {
|
|
698
|
+
if (config === null) return null;
|
|
699
|
+
switch (config.type) {
|
|
700
|
+
case "BertPreTokenizer": return new BertPreTokenizer_default();
|
|
701
|
+
case "Sequence": return new Sequence_default2(config);
|
|
702
|
+
case "Whitespace": return new Whitespace_default();
|
|
703
|
+
case "WhitespaceSplit": return new WhitespaceSplit_default();
|
|
704
|
+
case "Metaspace": return new Metaspace_default(config);
|
|
705
|
+
case "ByteLevel": return new ByteLevel_default(config);
|
|
706
|
+
case "Split": return new Split_default(config);
|
|
707
|
+
case "Punctuation": return new Punctuation_default(config);
|
|
708
|
+
case "Digits": return new Digits_default(config);
|
|
709
|
+
case "Replace": return new Replace_default2(config);
|
|
710
|
+
case "FixedLength": return new FixedLength_default(config);
|
|
711
|
+
default: throw new Error(`Unknown PreTokenizer type: ${config.type}`);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
var create_pre_tokenizer_default = create_pre_tokenizer;
|
|
715
|
+
var TokenizerModel = class extends Callable_default {
|
|
716
|
+
/**
|
|
717
|
+
* Creates a new instance of TokenizerModel.
|
|
718
|
+
* @param config The configuration object for the TokenizerModel.
|
|
719
|
+
*/
|
|
720
|
+
constructor(config) {
|
|
721
|
+
super();
|
|
722
|
+
this.config = config;
|
|
723
|
+
this.vocab = [];
|
|
724
|
+
this.tokens_to_ids = /* @__PURE__ */ new Map();
|
|
725
|
+
this.unk_token_id = void 0;
|
|
726
|
+
this.unk_token = void 0;
|
|
727
|
+
this.end_of_word_suffix = void 0;
|
|
728
|
+
this.fuse_unk = this.config.fuse_unk ?? false;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Internal function to call the TokenizerModel instance.
|
|
732
|
+
* @param tokens The tokens to encode.
|
|
733
|
+
* @returns The encoded tokens.
|
|
734
|
+
*/
|
|
735
|
+
_call(tokens) {
|
|
736
|
+
let result = this.encode(tokens);
|
|
737
|
+
if (this.fuse_unk) result = fuse_unk(result, this.tokens_to_ids, this.unk_token_id);
|
|
738
|
+
return result;
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
var TokenizerModel_default = TokenizerModel;
|
|
742
|
+
var WordPieceTokenizer = class extends TokenizerModel_default {
|
|
743
|
+
/**
|
|
744
|
+
* @param config The configuration object.
|
|
745
|
+
*/
|
|
746
|
+
constructor(config) {
|
|
747
|
+
super(config);
|
|
748
|
+
/** The maximum number of characters per word. */
|
|
749
|
+
this.max_input_chars_per_word = 100;
|
|
750
|
+
this.tokens_to_ids = object_to_map(config.vocab);
|
|
751
|
+
this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
|
|
752
|
+
this.unk_token = config.unk_token;
|
|
753
|
+
this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;
|
|
754
|
+
this.vocab = new Array(this.tokens_to_ids.size);
|
|
755
|
+
for (const [key, value] of this.tokens_to_ids) this.vocab[value] = key;
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Encodes an array of tokens using WordPiece encoding.
|
|
759
|
+
* @param tokens The tokens to encode.
|
|
760
|
+
* @returns An array of encoded tokens.
|
|
761
|
+
*/
|
|
762
|
+
encode(tokens) {
|
|
763
|
+
const output_tokens = [];
|
|
764
|
+
for (const token of tokens) {
|
|
765
|
+
const chars = [...token];
|
|
766
|
+
if (chars.length > this.max_input_chars_per_word) {
|
|
767
|
+
output_tokens.push(this.unk_token);
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
let is_unknown = false;
|
|
771
|
+
let start = 0;
|
|
772
|
+
const sub_tokens = [];
|
|
773
|
+
while (start < chars.length) {
|
|
774
|
+
let end = chars.length;
|
|
775
|
+
let current_substring = null;
|
|
776
|
+
while (start < end) {
|
|
777
|
+
let substr = chars.slice(start, end).join("");
|
|
778
|
+
if (start > 0) substr = this.config.continuing_subword_prefix + substr;
|
|
779
|
+
if (this.tokens_to_ids.has(substr)) {
|
|
780
|
+
current_substring = substr;
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
--end;
|
|
784
|
+
}
|
|
785
|
+
if (current_substring === null) {
|
|
786
|
+
is_unknown = true;
|
|
787
|
+
break;
|
|
788
|
+
}
|
|
789
|
+
sub_tokens.push(current_substring);
|
|
790
|
+
start = end;
|
|
791
|
+
}
|
|
792
|
+
if (is_unknown) output_tokens.push(this.unk_token);
|
|
793
|
+
else output_tokens.push(...sub_tokens);
|
|
794
|
+
}
|
|
795
|
+
return output_tokens;
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
var WordPiece_default = WordPieceTokenizer;
|
|
799
|
+
var CharTrieNode = class _CharTrieNode {
|
|
800
|
+
/**
|
|
801
|
+
* Create a new CharTrieNode.
|
|
802
|
+
* @param is_leaf Whether the node is a leaf node or not.
|
|
803
|
+
* @param children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
|
|
804
|
+
*/
|
|
805
|
+
constructor(is_leaf, children) {
|
|
806
|
+
this.is_leaf = is_leaf;
|
|
807
|
+
this.children = children;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Returns a new `CharTrieNode` instance with default values.
|
|
811
|
+
* @returns A new `CharTrieNode` instance with `is_leaf` set to `false` and an empty `children` map.
|
|
812
|
+
*/
|
|
813
|
+
static default() {
|
|
814
|
+
return new _CharTrieNode(false, /* @__PURE__ */ new Map());
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
var CharTrie = class {
|
|
818
|
+
constructor() {
|
|
819
|
+
this.root = CharTrieNode.default();
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Adds one or more `texts` to the trie.
|
|
823
|
+
* @param texts The strings to add to the trie.
|
|
824
|
+
*/
|
|
825
|
+
extend(texts) {
|
|
826
|
+
for (const text of texts) this.push(text);
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Adds text to the trie.
|
|
830
|
+
* @param text The string to add to the trie.
|
|
831
|
+
*/
|
|
832
|
+
push(text) {
|
|
833
|
+
let node = this.root;
|
|
834
|
+
for (const ch of text) {
|
|
835
|
+
let child = node.children.get(ch);
|
|
836
|
+
if (child === void 0) {
|
|
837
|
+
child = CharTrieNode.default();
|
|
838
|
+
node.children.set(ch, child);
|
|
839
|
+
}
|
|
840
|
+
node = child;
|
|
841
|
+
}
|
|
842
|
+
node.is_leaf = true;
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Searches the trie for all strings with a common prefix of `text`.
|
|
846
|
+
* @param text The common prefix to search for.
|
|
847
|
+
* @yields Each string in the trie that has `text` as a prefix.
|
|
848
|
+
*/
|
|
849
|
+
*common_prefix_search(text) {
|
|
850
|
+
let node = this.root;
|
|
851
|
+
if (node === void 0) return;
|
|
852
|
+
let prefix = "";
|
|
853
|
+
for (const ch of text) {
|
|
854
|
+
prefix += ch;
|
|
855
|
+
node = node.children.get(ch);
|
|
856
|
+
if (node === void 0) return;
|
|
857
|
+
if (node.is_leaf) yield prefix;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
var CharTrie_default = CharTrie;
|
|
862
|
+
var TokenLatticeNode = class _TokenLatticeNode {
|
|
863
|
+
/**
|
|
864
|
+
* Represents a node in a token lattice for a given sentence.
|
|
865
|
+
* @param token_id The ID of the token associated with this node.
|
|
866
|
+
* @param node_id The ID of this node.
|
|
867
|
+
* @param pos The starting position of the token in the sentence.
|
|
868
|
+
* @param length The length of the token.
|
|
869
|
+
* @param score The score associated with the token.
|
|
870
|
+
*/
|
|
871
|
+
constructor(token_id, node_id, pos, length, score) {
|
|
872
|
+
this.token_id = token_id;
|
|
873
|
+
this.node_id = node_id;
|
|
874
|
+
this.pos = pos;
|
|
875
|
+
this.length = length;
|
|
876
|
+
this.score = score;
|
|
877
|
+
this.prev = null;
|
|
878
|
+
this.backtrace_score = 0;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Returns a clone of this node.
|
|
882
|
+
* @returns A clone of this node.
|
|
883
|
+
*/
|
|
884
|
+
clone() {
|
|
885
|
+
const n = new _TokenLatticeNode(this.token_id, this.node_id, this.pos, this.length, this.score);
|
|
886
|
+
n.prev = this.prev;
|
|
887
|
+
n.backtrace_score = this.backtrace_score;
|
|
888
|
+
return n;
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
var TokenLattice = class {
|
|
892
|
+
/**
|
|
893
|
+
* Creates a new TokenLattice instance.
|
|
894
|
+
*
|
|
895
|
+
* @param sentence The input sentence to be tokenized.
|
|
896
|
+
* @param bos_token_id The beginning-of-sequence token ID.
|
|
897
|
+
* @param eos_token_id The end-of-sequence token ID.
|
|
898
|
+
*/
|
|
899
|
+
constructor(sentence, bos_token_id, eos_token_id) {
|
|
900
|
+
this.chars = Array.from(sentence);
|
|
901
|
+
this.len = this.chars.length;
|
|
902
|
+
this.bos_token_id = bos_token_id;
|
|
903
|
+
this.eos_token_id = eos_token_id;
|
|
904
|
+
this.nodes = [];
|
|
905
|
+
this.begin_nodes = Array.from({ length: this.len + 1 }, () => []);
|
|
906
|
+
this.end_nodes = Array.from({ length: this.len + 1 }, () => []);
|
|
907
|
+
const bos = new TokenLatticeNode(this.bos_token_id ?? 0, 0, 0, 0, 0);
|
|
908
|
+
const eos = new TokenLatticeNode(this.eos_token_id ?? 0, 1, this.len, 0, 0);
|
|
909
|
+
this.nodes.push(bos.clone());
|
|
910
|
+
this.nodes.push(eos.clone());
|
|
911
|
+
this.begin_nodes[this.len].push(eos);
|
|
912
|
+
this.end_nodes[0].push(bos);
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Inserts a new token node into the token lattice.
|
|
916
|
+
*
|
|
917
|
+
* @param pos The starting position of the token.
|
|
918
|
+
* @param length The length of the token.
|
|
919
|
+
* @param score The score of the token.
|
|
920
|
+
* @param token_id The token ID of the token.
|
|
921
|
+
*/
|
|
922
|
+
insert(pos, length, score, token_id) {
|
|
923
|
+
const node_id = this.nodes.length;
|
|
924
|
+
const node = new TokenLatticeNode(token_id, node_id, pos, length, score);
|
|
925
|
+
this.begin_nodes[pos].push(node);
|
|
926
|
+
this.end_nodes[pos + length].push(node);
|
|
927
|
+
this.nodes.push(node);
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
|
|
931
|
+
*
|
|
932
|
+
* @returns The most likely sequence of tokens.
|
|
933
|
+
*/
|
|
934
|
+
viterbi() {
|
|
935
|
+
const len2 = this.len;
|
|
936
|
+
let pos = 0;
|
|
937
|
+
while (pos <= len2) {
|
|
938
|
+
if (this.begin_nodes[pos].length == 0) return [];
|
|
939
|
+
for (let rnode of this.begin_nodes[pos]) {
|
|
940
|
+
rnode.prev = null;
|
|
941
|
+
let best_score = 0;
|
|
942
|
+
let best_node = null;
|
|
943
|
+
for (let lnode of this.end_nodes[pos]) {
|
|
944
|
+
const score = lnode.backtrace_score + rnode.score;
|
|
945
|
+
if (best_node === null || score > best_score) {
|
|
946
|
+
best_node = lnode.clone();
|
|
947
|
+
best_score = score;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (best_node !== null) {
|
|
951
|
+
rnode.prev = best_node;
|
|
952
|
+
rnode.backtrace_score = best_score;
|
|
953
|
+
} else return [];
|
|
954
|
+
}
|
|
955
|
+
++pos;
|
|
956
|
+
}
|
|
957
|
+
const results = [];
|
|
958
|
+
const prev = this.begin_nodes[len2][0].prev;
|
|
959
|
+
if (prev === null) return [];
|
|
960
|
+
let node = prev.clone();
|
|
961
|
+
while (node.prev !== null) {
|
|
962
|
+
results.push(node.clone());
|
|
963
|
+
node = node.clone().prev.clone();
|
|
964
|
+
}
|
|
965
|
+
results.reverse();
|
|
966
|
+
return results;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Get the text piece for a given node.
|
|
970
|
+
* @param node The node to get the piece for.
|
|
971
|
+
* @returns The array of nodes representing the most likely sequence of tokens.
|
|
972
|
+
*/
|
|
973
|
+
piece(node) {
|
|
974
|
+
return this.chars.slice(node.pos, node.pos + node.length).join("");
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* @returns The most likely sequence of tokens.
|
|
978
|
+
*/
|
|
979
|
+
tokens() {
|
|
980
|
+
return this.viterbi().map((x) => this.piece(x));
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* @returns The most likely sequence of token ids.
|
|
984
|
+
*/
|
|
985
|
+
token_ids() {
|
|
986
|
+
return this.viterbi().map((x) => x.token_id);
|
|
987
|
+
}
|
|
988
|
+
};
|
|
989
|
+
var TokenLattice_default = TokenLattice;
|
|
990
|
+
function min(arr) {
|
|
991
|
+
if (arr.length === 0) throw new Error("Array must not be empty");
|
|
992
|
+
let min_value = arr[0];
|
|
993
|
+
let index_of_min = 0;
|
|
994
|
+
for (let i = 1; i < arr.length; ++i) if (arr[i] < min_value) {
|
|
995
|
+
min_value = arr[i];
|
|
996
|
+
index_of_min = i;
|
|
997
|
+
}
|
|
998
|
+
return [min_value, index_of_min];
|
|
999
|
+
}
|
|
1000
|
+
var Unigram = class extends TokenizerModel_default {
|
|
1001
|
+
/**
|
|
1002
|
+
* Create a new Unigram tokenizer model.
|
|
1003
|
+
* @param config The configuration object for the Unigram model.
|
|
1004
|
+
* @param eos_token
|
|
1005
|
+
*/
|
|
1006
|
+
constructor(config, eos_token) {
|
|
1007
|
+
super(config);
|
|
1008
|
+
const vocab_size = config.vocab.length;
|
|
1009
|
+
this.vocab = new Array(vocab_size);
|
|
1010
|
+
this.scores = new Array(vocab_size);
|
|
1011
|
+
for (let i = 0; i < vocab_size; ++i) [this.vocab[i], this.scores[i]] = config.vocab[i];
|
|
1012
|
+
this.unk_token_id = config.unk_id;
|
|
1013
|
+
this.unk_token = this.vocab[config.unk_id];
|
|
1014
|
+
this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));
|
|
1015
|
+
this.bos_token = " ";
|
|
1016
|
+
this.bos_token_id = this.tokens_to_ids.get(this.bos_token);
|
|
1017
|
+
this.eos_token = eos_token;
|
|
1018
|
+
this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
|
|
1019
|
+
this.unk_token = this.vocab[this.unk_token_id];
|
|
1020
|
+
this.min_score = min(this.scores)[0];
|
|
1021
|
+
this.unk_score = this.min_score - 10;
|
|
1022
|
+
this.scores[this.unk_token_id] = this.unk_score;
|
|
1023
|
+
this.trie = new CharTrie_default();
|
|
1024
|
+
this.trie.extend(this.vocab);
|
|
1025
|
+
this.fuse_unk = true;
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Populates lattice nodes.
|
|
1029
|
+
* @param lattice The token lattice to populate with nodes.
|
|
1030
|
+
*/
|
|
1031
|
+
populate_nodes(lattice) {
|
|
1032
|
+
const chars = lattice.chars;
|
|
1033
|
+
const mblen = 1;
|
|
1034
|
+
let begin_pos = 0;
|
|
1035
|
+
while (begin_pos < chars.length) {
|
|
1036
|
+
let has_single_node = false;
|
|
1037
|
+
const tokens = [];
|
|
1038
|
+
const sliced = chars.slice(begin_pos).join("");
|
|
1039
|
+
const prefixed_tokens = this.trie.common_prefix_search(sliced);
|
|
1040
|
+
for (const token of prefixed_tokens) {
|
|
1041
|
+
tokens.push(token);
|
|
1042
|
+
const token_id = this.tokens_to_ids.get(token);
|
|
1043
|
+
const token_score = this.scores[token_id];
|
|
1044
|
+
const n = len(token);
|
|
1045
|
+
lattice.insert(begin_pos, n, token_score, token_id);
|
|
1046
|
+
if (!has_single_node && n === mblen) has_single_node = true;
|
|
1047
|
+
}
|
|
1048
|
+
if (!has_single_node) lattice.insert(begin_pos, mblen, this.unk_score, this.unk_token_id);
|
|
1049
|
+
begin_pos += mblen;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Encodes an array of tokens into an array of subtokens using the unigram model.
|
|
1054
|
+
*
|
|
1055
|
+
* @param normalized The normalized string.
|
|
1056
|
+
* @returns An array of subtokens obtained by encoding the input tokens using the unigram model.
|
|
1057
|
+
*/
|
|
1058
|
+
tokenize(normalized) {
|
|
1059
|
+
const lattice = new TokenLattice_default(normalized, this.bos_token_id, this.eos_token_id);
|
|
1060
|
+
this.populate_nodes(lattice);
|
|
1061
|
+
return lattice.tokens();
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Encodes an array of tokens using Unigram encoding.
|
|
1065
|
+
* @param tokens The tokens to encode.
|
|
1066
|
+
* @returns An array of encoded tokens.
|
|
1067
|
+
*/
|
|
1068
|
+
encode(tokens) {
|
|
1069
|
+
const to_return = [];
|
|
1070
|
+
for (const token of tokens) {
|
|
1071
|
+
const tokenized = this.tokenize(token);
|
|
1072
|
+
to_return.push(...tokenized);
|
|
1073
|
+
}
|
|
1074
|
+
return to_return;
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
var Unigram_default = Unigram;
|
|
1078
|
+
var PriorityQueue = class {
|
|
1079
|
+
/**
|
|
1080
|
+
* Create a new PriorityQueue.
|
|
1081
|
+
* @param comparator Comparator function to determine priority. Defaults to a MaxHeap.
|
|
1082
|
+
* @param max_size Maximum size of the queue. Defaults to Infinity.
|
|
1083
|
+
*/
|
|
1084
|
+
constructor(comparator = (a, b) => a > b, max_size = Infinity) {
|
|
1085
|
+
this._heap = [];
|
|
1086
|
+
this._comparator = comparator;
|
|
1087
|
+
this._max_size = max_size;
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* The size of the queue
|
|
1091
|
+
*/
|
|
1092
|
+
get size() {
|
|
1093
|
+
return this._heap.length;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Check if the queue is empty.
|
|
1097
|
+
* @returns `true` if the queue is empty, `false` otherwise.
|
|
1098
|
+
*/
|
|
1099
|
+
is_empty() {
|
|
1100
|
+
return this.size === 0;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Return the element with the highest priority in the queue.
|
|
1104
|
+
* @returns The highest priority element in the queue.
|
|
1105
|
+
*/
|
|
1106
|
+
peek() {
|
|
1107
|
+
return this._heap[0];
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Add one or more elements to the queue.
|
|
1111
|
+
* @param values The values to push into the queue.
|
|
1112
|
+
* @returns The new size of the queue.
|
|
1113
|
+
*/
|
|
1114
|
+
push(...values) {
|
|
1115
|
+
return this.extend(values);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Add multiple elements to the queue.
|
|
1119
|
+
* @param values The values to push into the queue.
|
|
1120
|
+
* @returns The new size of the queue.
|
|
1121
|
+
*/
|
|
1122
|
+
extend(values) {
|
|
1123
|
+
for (const value of values) if (this.size < this._max_size) {
|
|
1124
|
+
this._heap.push(value);
|
|
1125
|
+
this._sift_up();
|
|
1126
|
+
} else {
|
|
1127
|
+
const smallest = this._smallest();
|
|
1128
|
+
if (this._comparator(value, this._heap[smallest])) {
|
|
1129
|
+
this._heap[smallest] = value;
|
|
1130
|
+
this._sift_up_from(smallest);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return this.size;
|
|
1134
|
+
}
|
|
1135
|
+
/**
|
|
1136
|
+
* Remove and return the element with the highest priority in the queue.
|
|
1137
|
+
* @returns The element with the highest priority in the queue.
|
|
1138
|
+
*/
|
|
1139
|
+
pop() {
|
|
1140
|
+
const popped_value = this.peek();
|
|
1141
|
+
const bottom = this.size - 1;
|
|
1142
|
+
if (bottom > 0) this._swap(0, bottom);
|
|
1143
|
+
this._heap.pop();
|
|
1144
|
+
this._sift_down();
|
|
1145
|
+
return popped_value;
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Replace the element with the highest priority in the queue with a new value.
|
|
1149
|
+
* @param value The new value.
|
|
1150
|
+
* @returns The replaced value.
|
|
1151
|
+
*/
|
|
1152
|
+
replace(value) {
|
|
1153
|
+
const replaced_value = this.peek();
|
|
1154
|
+
this._heap[0] = value;
|
|
1155
|
+
this._sift_down();
|
|
1156
|
+
return replaced_value;
|
|
1157
|
+
}
|
|
1158
|
+
/**
|
|
1159
|
+
* Compute the index for the parent of the node at index `i`.
|
|
1160
|
+
* @param i The index of the node to get the parent of.
|
|
1161
|
+
* @returns The index of the parent node.
|
|
1162
|
+
* @private
|
|
1163
|
+
*/
|
|
1164
|
+
_parent(i) {
|
|
1165
|
+
return (i + 1 >>> 1) - 1;
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Compute the index for the left child of the node at index `i`.
|
|
1169
|
+
* @param i The index of the node to get the left child of.
|
|
1170
|
+
* @returns The index of the left child.
|
|
1171
|
+
* @private
|
|
1172
|
+
*/
|
|
1173
|
+
_left(i) {
|
|
1174
|
+
return (i << 1) + 1;
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Compute the index for the right child of the node at index `i`.
|
|
1178
|
+
* @param i The index of the node to get the right child of.
|
|
1179
|
+
* @returns The index of the right child.
|
|
1180
|
+
* @private
|
|
1181
|
+
*/
|
|
1182
|
+
_right(i) {
|
|
1183
|
+
return i + 1 << 1;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Check if the element at index `i` is greater than the element at index `j`.
|
|
1187
|
+
* @param i The index of the first element to compare.
|
|
1188
|
+
* @param j The index of the second element to compare.
|
|
1189
|
+
* @returns `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
|
|
1190
|
+
* @private
|
|
1191
|
+
*/
|
|
1192
|
+
_greater(i, j) {
|
|
1193
|
+
return this._comparator(this._heap[i], this._heap[j]);
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Swap the elements at indices `i` and `j`.
|
|
1197
|
+
* @param i The index of the first element to swap.
|
|
1198
|
+
* @param j The index of the second element to swap.
|
|
1199
|
+
* @private
|
|
1200
|
+
*/
|
|
1201
|
+
_swap(i, j) {
|
|
1202
|
+
const temp = this._heap[i];
|
|
1203
|
+
this._heap[i] = this._heap[j];
|
|
1204
|
+
this._heap[j] = temp;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Maintain the heap property by updating positions in the heap,
|
|
1208
|
+
* starting at the last element and moving up the heap.
|
|
1209
|
+
* @private
|
|
1210
|
+
*/
|
|
1211
|
+
_sift_up() {
|
|
1212
|
+
this._sift_up_from(this.size - 1);
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Helper function to sift up from a given node.
|
|
1216
|
+
* @param node The index of the node to start sifting up from.
|
|
1217
|
+
*/
|
|
1218
|
+
_sift_up_from(node) {
|
|
1219
|
+
while (node > 0 && this._greater(node, this._parent(node))) {
|
|
1220
|
+
this._swap(node, this._parent(node));
|
|
1221
|
+
node = this._parent(node);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Maintain the heap property by updating positions in the heap,
|
|
1226
|
+
* starting at the first element and moving down the heap.
|
|
1227
|
+
* @private
|
|
1228
|
+
*/
|
|
1229
|
+
_sift_down() {
|
|
1230
|
+
let node = 0;
|
|
1231
|
+
while (this._left(node) < this.size && this._greater(this._left(node), node) || this._right(node) < this.size && this._greater(this._right(node), node)) {
|
|
1232
|
+
const max_child = this._right(node) < this.size && this._greater(this._right(node), this._left(node)) ? this._right(node) : this._left(node);
|
|
1233
|
+
this._swap(node, max_child);
|
|
1234
|
+
node = max_child;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Get the index of the smallest element in the heap. Since we use an array-based heap,
|
|
1239
|
+
* the index can be computed without needing to traverse the heap.
|
|
1240
|
+
* @private
|
|
1241
|
+
*/
|
|
1242
|
+
_smallest() {
|
|
1243
|
+
return 2 ** Math.floor(Math.log2(this.size)) - 1;
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
var PriorityQueue_default = PriorityQueue;
|
|
1247
|
+
var LRUCache = class {
|
|
1248
|
+
/**
|
|
1249
|
+
* Creates an LRUCache instance.
|
|
1250
|
+
* @param capacity The maximum number of items the cache can hold.
|
|
1251
|
+
*/
|
|
1252
|
+
constructor(capacity) {
|
|
1253
|
+
this.capacity = capacity;
|
|
1254
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Retrieves the value associated with the given key and marks the key as recently used.
|
|
1258
|
+
* @param key The key to retrieve.
|
|
1259
|
+
* @returns The value associated with the key, or undefined if the key does not exist.
|
|
1260
|
+
*/
|
|
1261
|
+
get(key) {
|
|
1262
|
+
if (!this.cache.has(key)) return void 0;
|
|
1263
|
+
const value = this.cache.get(key);
|
|
1264
|
+
this.cache.delete(key);
|
|
1265
|
+
this.cache.set(key, value);
|
|
1266
|
+
return value;
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Inserts or updates the key-value pair in the cache.
|
|
1270
|
+
* If the key already exists, it is updated and marked as recently used.
|
|
1271
|
+
* If the cache exceeds its capacity, the least recently used item is evicted.
|
|
1272
|
+
* @param key The key to add or update.
|
|
1273
|
+
* @param value The value to associate with the key.
|
|
1274
|
+
*/
|
|
1275
|
+
put(key, value) {
|
|
1276
|
+
if (this.cache.has(key)) this.cache.delete(key);
|
|
1277
|
+
this.cache.set(key, value);
|
|
1278
|
+
if (this.cache.size > this.capacity) this.cache.delete(this.cache.keys().next().value);
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Clears the cache.
|
|
1282
|
+
*/
|
|
1283
|
+
clear() {
|
|
1284
|
+
this.cache.clear();
|
|
1285
|
+
}
|
|
1286
|
+
};
|
|
1287
|
+
var LRUCache_default = LRUCache;
|
|
1288
|
+
var BPE = class extends TokenizerModel_default {
|
|
1289
|
+
/**
|
|
1290
|
+
* Create a BPE instance.
|
|
1291
|
+
* @param config The configuration object for BPE.
|
|
1292
|
+
*/
|
|
1293
|
+
constructor(config) {
|
|
1294
|
+
super(config);
|
|
1295
|
+
this.tokens_to_ids = object_to_map(config.vocab);
|
|
1296
|
+
this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
|
|
1297
|
+
this.unk_token = config.unk_token;
|
|
1298
|
+
this.vocab = new Array(this.tokens_to_ids.size);
|
|
1299
|
+
for (const [key, value] of this.tokens_to_ids) this.vocab[value] = key;
|
|
1300
|
+
const use_new_merge_format = Array.isArray(config.merges[0]);
|
|
1301
|
+
this.merges = use_new_merge_format ? config.merges : config.merges.map((x) => x.split(" ", 2));
|
|
1302
|
+
this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));
|
|
1303
|
+
this.end_of_word_suffix = config.end_of_word_suffix;
|
|
1304
|
+
this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;
|
|
1305
|
+
this.byte_fallback = this.config.byte_fallback ?? false;
|
|
1306
|
+
if (this.byte_fallback) this.text_encoder = new TextEncoder();
|
|
1307
|
+
this.ignore_merges = this.config.ignore_merges ?? false;
|
|
1308
|
+
this.max_length_to_cache = 256;
|
|
1309
|
+
this.cache_capacity = 1e4;
|
|
1310
|
+
this.cache = new LRUCache_default(this.cache_capacity);
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Clears the cache.
|
|
1314
|
+
*/
|
|
1315
|
+
clear_cache() {
|
|
1316
|
+
this.cache.clear();
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
|
|
1320
|
+
* queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
|
|
1321
|
+
* @param token The token to encode.
|
|
1322
|
+
* @returns The BPE encoded tokens.
|
|
1323
|
+
*/
|
|
1324
|
+
bpe(token) {
|
|
1325
|
+
if (token.length === 0) return [];
|
|
1326
|
+
const cached = this.cache.get(token);
|
|
1327
|
+
if (cached !== void 0) return cached;
|
|
1328
|
+
const word = Array.from(token);
|
|
1329
|
+
if (this.end_of_word_suffix) word[word.length - 1] += this.end_of_word_suffix;
|
|
1330
|
+
let result = [];
|
|
1331
|
+
if (word.length > 1) {
|
|
1332
|
+
const queue = new PriorityQueue_default((a, b) => a.score < b.score);
|
|
1333
|
+
let starting_node = {
|
|
1334
|
+
token: word[0],
|
|
1335
|
+
bias: 0,
|
|
1336
|
+
prev: null,
|
|
1337
|
+
next: null
|
|
1338
|
+
};
|
|
1339
|
+
let previous_node = starting_node;
|
|
1340
|
+
for (let i = 1; i < word.length; ++i) {
|
|
1341
|
+
const current_node = {
|
|
1342
|
+
bias: i / word.length,
|
|
1343
|
+
token: word[i],
|
|
1344
|
+
prev: previous_node,
|
|
1345
|
+
next: null
|
|
1346
|
+
};
|
|
1347
|
+
previous_node.next = current_node;
|
|
1348
|
+
this.add_node(queue, previous_node);
|
|
1349
|
+
previous_node = current_node;
|
|
1350
|
+
}
|
|
1351
|
+
while (!queue.is_empty()) {
|
|
1352
|
+
const node = queue.pop();
|
|
1353
|
+
if (node.deleted || !node.next || node.next.deleted) continue;
|
|
1354
|
+
node.deleted = true;
|
|
1355
|
+
node.next.deleted = true;
|
|
1356
|
+
if (node.prev) {
|
|
1357
|
+
const new_previous_node = { ...node.prev };
|
|
1358
|
+
node.prev.deleted = true;
|
|
1359
|
+
node.prev = new_previous_node;
|
|
1360
|
+
if (new_previous_node.prev) new_previous_node.prev.next = new_previous_node;
|
|
1361
|
+
else starting_node = new_previous_node;
|
|
1362
|
+
}
|
|
1363
|
+
const merged = {
|
|
1364
|
+
token: node.token + node.next.token,
|
|
1365
|
+
bias: node.bias,
|
|
1366
|
+
prev: node.prev,
|
|
1367
|
+
next: node.next.next
|
|
1368
|
+
};
|
|
1369
|
+
if (merged.prev) {
|
|
1370
|
+
merged.prev.next = merged;
|
|
1371
|
+
this.add_node(queue, merged.prev);
|
|
1372
|
+
} else starting_node = merged;
|
|
1373
|
+
if (merged.next) {
|
|
1374
|
+
merged.next.prev = merged;
|
|
1375
|
+
this.add_node(queue, merged);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
for (let current_node = starting_node; current_node !== null; current_node = current_node.next) result.push(current_node.token);
|
|
1379
|
+
} else result = word;
|
|
1380
|
+
if (this.continuing_subword_suffix) for (let i = 0; i < result.length - 1; ++i) result[i] += this.continuing_subword_suffix;
|
|
1381
|
+
if (token.length < this.max_length_to_cache) this.cache.put(token, result);
|
|
1382
|
+
return result;
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Helper function to add a node to the priority queue.
|
|
1386
|
+
* @param queue
|
|
1387
|
+
* @param node
|
|
1388
|
+
*/
|
|
1389
|
+
add_node(queue, node) {
|
|
1390
|
+
const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));
|
|
1391
|
+
if (rank !== void 0) {
|
|
1392
|
+
node.score = rank + node.bias;
|
|
1393
|
+
queue.push(node);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
|
|
1398
|
+
* @param tokens The input sequence of tokens to encode.
|
|
1399
|
+
* @returns The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
|
|
1400
|
+
*/
|
|
1401
|
+
encode(tokens) {
|
|
1402
|
+
const output_tokens = [];
|
|
1403
|
+
for (const token of tokens) {
|
|
1404
|
+
if (this.ignore_merges && this.tokens_to_ids.has(token)) {
|
|
1405
|
+
output_tokens.push(token);
|
|
1406
|
+
continue;
|
|
1407
|
+
}
|
|
1408
|
+
const bpe_token_list = this.bpe(token);
|
|
1409
|
+
for (const t of bpe_token_list) if (this.tokens_to_ids.has(t)) output_tokens.push(t);
|
|
1410
|
+
else if (this.byte_fallback) {
|
|
1411
|
+
const byte_tokens = Array.from(this.text_encoder.encode(t)).map((x) => `<0x${x.toString(16).toUpperCase().padStart(2, "0")}>`);
|
|
1412
|
+
if (byte_tokens.every((x) => this.tokens_to_ids.has(x))) output_tokens.push(...byte_tokens);
|
|
1413
|
+
else if (this.unk_token != null) output_tokens.push(this.unk_token);
|
|
1414
|
+
} else if (this.unk_token != null) output_tokens.push(this.unk_token);
|
|
1415
|
+
}
|
|
1416
|
+
return output_tokens;
|
|
1417
|
+
}
|
|
1418
|
+
};
|
|
1419
|
+
var BPE_default = BPE;
|
|
1420
|
+
var Legacy = class extends TokenizerModel_default {
|
|
1421
|
+
/**
|
|
1422
|
+
* Create a Legacy tokenizer model instance.
|
|
1423
|
+
* @param config The configuration object for Legacy tokenizer model.
|
|
1424
|
+
* @param more_config Additional configuration object for the Legacy tokenizer model.
|
|
1425
|
+
*/
|
|
1426
|
+
constructor(config, more_config) {
|
|
1427
|
+
super(config);
|
|
1428
|
+
const vocab = config.vocab;
|
|
1429
|
+
this.tokens_to_ids = object_to_map(more_config.target_lang ? vocab[more_config.target_lang] : vocab);
|
|
1430
|
+
this.bos_token = more_config.bos_token;
|
|
1431
|
+
this.bos_token_id = this.tokens_to_ids.get(this.bos_token);
|
|
1432
|
+
this.eos_token = more_config.eos_token;
|
|
1433
|
+
this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
|
|
1434
|
+
this.pad_token = more_config.pad_token;
|
|
1435
|
+
this.pad_token_id = this.tokens_to_ids.get(this.pad_token);
|
|
1436
|
+
this.unk_token = more_config.unk_token;
|
|
1437
|
+
this.unk_token_id = this.tokens_to_ids.get(this.unk_token);
|
|
1438
|
+
this.vocab = new Array(this.tokens_to_ids.size);
|
|
1439
|
+
for (const [key, value] of this.tokens_to_ids) this.vocab[value] = key;
|
|
1440
|
+
}
|
|
1441
|
+
encode(tokens) {
|
|
1442
|
+
return tokens;
|
|
1443
|
+
}
|
|
1444
|
+
};
|
|
1445
|
+
var Legacy_default = Legacy;
|
|
1446
|
+
function create_tokenizer_model(model_config, config) {
|
|
1447
|
+
switch (model_config.type) {
|
|
1448
|
+
case "WordPiece": return new WordPiece_default(model_config);
|
|
1449
|
+
case "Unigram": return new Unigram_default(model_config, config.eos_token);
|
|
1450
|
+
case "BPE": return new BPE_default(model_config);
|
|
1451
|
+
default:
|
|
1452
|
+
if (model_config.vocab) if (Array.isArray(model_config.vocab)) return new Unigram_default(model_config, config.eos_token);
|
|
1453
|
+
else if (Object.hasOwn(model_config, "continuing_subword_prefix") && Object.hasOwn(model_config, "unk_token")) if (Object.hasOwn(model_config, "merges")) return new BPE_default(model_config);
|
|
1454
|
+
else return new WordPiece_default(model_config);
|
|
1455
|
+
else return new Legacy_default(model_config, {
|
|
1456
|
+
target_lang: config.target_lang,
|
|
1457
|
+
bos_token: config.bos_token,
|
|
1458
|
+
eos_token: config.eos_token,
|
|
1459
|
+
pad_token: config.pad_token,
|
|
1460
|
+
unk_token: config.unk_token
|
|
1461
|
+
});
|
|
1462
|
+
throw new Error(`Unknown TokenizerModel type: ${model_config?.type}`);
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
var create_tokenizer_model_default = create_tokenizer_model;
|
|
1466
|
+
var PostProcessor = class extends Callable_default {
|
|
1467
|
+
/**
|
|
1468
|
+
* @param config The configuration for the post-processor.
|
|
1469
|
+
*/
|
|
1470
|
+
constructor(config) {
|
|
1471
|
+
super();
|
|
1472
|
+
this.config = config;
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Alias for {@link PostProcessor#post_process}.
|
|
1476
|
+
* @param tokens The text or array of texts to post-process.
|
|
1477
|
+
* @param args Additional arguments required by the post-processing logic.
|
|
1478
|
+
* @returns The post-processed tokens.
|
|
1479
|
+
*/
|
|
1480
|
+
_call(tokens, ...args) {
|
|
1481
|
+
return this.post_process(tokens, ...args);
|
|
1482
|
+
}
|
|
1483
|
+
};
|
|
1484
|
+
var PostProcessor_default = PostProcessor;
|
|
1485
|
+
var TemplateProcessing = class extends PostProcessor_default {
|
|
1486
|
+
/**
|
|
1487
|
+
* Replaces special tokens in the template with actual tokens.
|
|
1488
|
+
* @param tokens The list of tokens for the first sequence.
|
|
1489
|
+
* @param tokens_pair The list of tokens for the second sequence (optional).
|
|
1490
|
+
* @param add_special_tokens Whether to add the special tokens to the beginning and end of the input.
|
|
1491
|
+
* @returns An object containing the list of tokens with the special tokens replaced with actual tokens.
|
|
1492
|
+
*/
|
|
1493
|
+
post_process(tokens, tokens_pair = null, add_special_tokens = true) {
|
|
1494
|
+
const type = tokens_pair === null ? this.config.single : this.config.pair;
|
|
1495
|
+
let processed_tokens = [];
|
|
1496
|
+
let types = [];
|
|
1497
|
+
for (const item of type) if ("SpecialToken" in item) {
|
|
1498
|
+
if (add_special_tokens) {
|
|
1499
|
+
processed_tokens.push(item.SpecialToken.id);
|
|
1500
|
+
types.push(item.SpecialToken.type_id);
|
|
1501
|
+
}
|
|
1502
|
+
} else if ("Sequence" in item) {
|
|
1503
|
+
if (item.Sequence.id === "A") {
|
|
1504
|
+
processed_tokens = merge_arrays(processed_tokens, tokens);
|
|
1505
|
+
types = merge_arrays(types, new Array(tokens.length).fill(item.Sequence.type_id));
|
|
1506
|
+
} else if (item.Sequence.id === "B") {
|
|
1507
|
+
processed_tokens = merge_arrays(processed_tokens, tokens_pair);
|
|
1508
|
+
types = merge_arrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
return {
|
|
1512
|
+
tokens: processed_tokens,
|
|
1513
|
+
token_type_ids: types
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
};
|
|
1517
|
+
var TemplateProcessing_default = TemplateProcessing;
|
|
1518
|
+
var ByteLevel2 = class extends PostProcessor_default {
|
|
1519
|
+
/**
|
|
1520
|
+
* Post process the given tokens.
|
|
1521
|
+
* @param tokens The list of tokens for the first sequence.
|
|
1522
|
+
* @param tokens_pair The list of tokens for the second sequence (optional).
|
|
1523
|
+
* @returns An object containing the post-processed tokens.
|
|
1524
|
+
*/
|
|
1525
|
+
post_process(tokens, tokens_pair = null) {
|
|
1526
|
+
return {
|
|
1527
|
+
tokens,
|
|
1528
|
+
tokens_pair
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
};
|
|
1532
|
+
var ByteLevel_default2 = ByteLevel2;
|
|
1533
|
+
var BertProcessing = class extends PostProcessor_default {
|
|
1534
|
+
/**
|
|
1535
|
+
* @param config The configuration for the post-processor.
|
|
1536
|
+
* @param config.cls The special tokens to add to the beginning of the input.
|
|
1537
|
+
* @param config.sep The special tokens to add to the end of the input.
|
|
1538
|
+
*/
|
|
1539
|
+
constructor(config) {
|
|
1540
|
+
super(config);
|
|
1541
|
+
this.sep = config.sep;
|
|
1542
|
+
this.cls = config.cls;
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* Adds the special tokens to the beginning and end of the input.
|
|
1546
|
+
* @param tokens The input tokens.
|
|
1547
|
+
* @param tokens_pair An optional second set of input tokens.
|
|
1548
|
+
* @param add_special_tokens Whether to add the special tokens to the beginning and end of the input.
|
|
1549
|
+
* @returns The post-processed tokens with the special tokens added to the beginning and end.
|
|
1550
|
+
*/
|
|
1551
|
+
post_process(tokens, tokens_pair = null, add_special_tokens = true) {
|
|
1552
|
+
if (add_special_tokens) tokens = merge_arrays([this.cls[0]], tokens, [this.sep[0]]);
|
|
1553
|
+
let token_type_ids = new Array(tokens.length).fill(0);
|
|
1554
|
+
if (tokens_pair) {
|
|
1555
|
+
const middle = [];
|
|
1556
|
+
const after = add_special_tokens ? [this.sep[0]] : [];
|
|
1557
|
+
tokens = merge_arrays(tokens, middle, tokens_pair, after);
|
|
1558
|
+
token_type_ids = merge_arrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
|
|
1559
|
+
}
|
|
1560
|
+
return {
|
|
1561
|
+
tokens,
|
|
1562
|
+
token_type_ids
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
};
|
|
1566
|
+
var BertProcessing_default = BertProcessing;
|
|
1567
|
+
var RobertaProcessing = class extends PostProcessor_default {
|
|
1568
|
+
/**
|
|
1569
|
+
* @param config The configuration for the post-processor.
|
|
1570
|
+
* @param config.cls The special tokens to add to the beginning of the input.
|
|
1571
|
+
* @param config.sep The special tokens to add to the end of the input.
|
|
1572
|
+
*/
|
|
1573
|
+
constructor(config) {
|
|
1574
|
+
super(config);
|
|
1575
|
+
this.sep = config.sep;
|
|
1576
|
+
this.cls = config.cls;
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Adds the special tokens to the beginning and end of the input.
|
|
1580
|
+
* @param tokens The input tokens.
|
|
1581
|
+
* @param tokens_pair An optional second set of input tokens.
|
|
1582
|
+
* @param add_special_tokens Whether to add the special tokens to the beginning and end of the input.
|
|
1583
|
+
* @returns The post-processed tokens with the special tokens added to the beginning and end.
|
|
1584
|
+
*/
|
|
1585
|
+
post_process(tokens, tokens_pair, add_special_tokens = true) {
|
|
1586
|
+
if (add_special_tokens) tokens = merge_arrays([this.cls[0]], tokens, [this.sep[0]]);
|
|
1587
|
+
let token_type_ids = new Array(tokens.length).fill(0);
|
|
1588
|
+
if (tokens_pair) {
|
|
1589
|
+
const middle = add_special_tokens ? [this.sep[0]] : [];
|
|
1590
|
+
const after = add_special_tokens ? [this.sep[0]] : [];
|
|
1591
|
+
tokens = merge_arrays(tokens, middle, tokens_pair, after);
|
|
1592
|
+
token_type_ids = merge_arrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
|
|
1593
|
+
}
|
|
1594
|
+
return {
|
|
1595
|
+
tokens,
|
|
1596
|
+
token_type_ids
|
|
1597
|
+
};
|
|
1598
|
+
}
|
|
1599
|
+
};
|
|
1600
|
+
var RobertaProcessing_default = RobertaProcessing;
|
|
1601
|
+
var Sequence3 = class extends PostProcessor_default {
|
|
1602
|
+
/**
|
|
1603
|
+
* Creates a new instance of Sequence post-processor.
|
|
1604
|
+
* @param config The configuration object.
|
|
1605
|
+
*/
|
|
1606
|
+
constructor(config) {
|
|
1607
|
+
super(config);
|
|
1608
|
+
this.processors = (config.processors ?? []).map((x) => create_post_processor_default(x));
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Post process the given tokens.
|
|
1612
|
+
* @param tokens The list of tokens for the first sequence.
|
|
1613
|
+
* @param tokens_pair The list of tokens for the second sequence (optional).
|
|
1614
|
+
* @param add_special_tokens Whether to add the special tokens to the beginning and end of the input.
|
|
1615
|
+
* @returns An object containing the post-processed tokens.
|
|
1616
|
+
*/
|
|
1617
|
+
post_process(tokens, tokens_pair = null, add_special_tokens = true) {
|
|
1618
|
+
let processed_tokens = {
|
|
1619
|
+
tokens,
|
|
1620
|
+
tokens_pair
|
|
1621
|
+
};
|
|
1622
|
+
for (const processor of this.processors) processed_tokens = processor.post_process(processed_tokens.tokens, processed_tokens.tokens_pair, add_special_tokens);
|
|
1623
|
+
return processed_tokens;
|
|
1624
|
+
}
|
|
1625
|
+
};
|
|
1626
|
+
var Sequence_default3 = Sequence3;
|
|
1627
|
+
function create_post_processor(config) {
|
|
1628
|
+
if (config === null) return null;
|
|
1629
|
+
switch (config.type) {
|
|
1630
|
+
case "TemplateProcessing": return new TemplateProcessing_default(config);
|
|
1631
|
+
case "ByteLevel": return new ByteLevel_default2(config);
|
|
1632
|
+
case "BertProcessing": return new BertProcessing_default(config);
|
|
1633
|
+
case "RobertaProcessing": return new RobertaProcessing_default(config);
|
|
1634
|
+
case "Sequence": return new Sequence_default3(config);
|
|
1635
|
+
default: throw new Error(`Unknown PostProcessor type: ${config.type}`);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
var create_post_processor_default = create_post_processor;
|
|
1639
|
+
var Decoder = class extends Callable_default {
|
|
1640
|
+
/**
|
|
1641
|
+
* Creates an instance of `Decoder`.
|
|
1642
|
+
* @param config The configuration object.
|
|
1643
|
+
**/
|
|
1644
|
+
constructor(config) {
|
|
1645
|
+
super();
|
|
1646
|
+
this.config = config;
|
|
1647
|
+
this.added_tokens = [];
|
|
1648
|
+
this.end_of_word_suffix = null;
|
|
1649
|
+
this.trim_offsets = "trim_offsets" in config ? config.trim_offsets : false;
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Calls the `decode` method.
|
|
1653
|
+
*
|
|
1654
|
+
* @param tokens The list of tokens.
|
|
1655
|
+
* @returns The decoded string.
|
|
1656
|
+
*/
|
|
1657
|
+
_call(tokens) {
|
|
1658
|
+
return this.decode(tokens);
|
|
1659
|
+
}
|
|
1660
|
+
/**
|
|
1661
|
+
* Decodes a list of tokens.
|
|
1662
|
+
* @param tokens The list of tokens.
|
|
1663
|
+
* @returns The decoded string.
|
|
1664
|
+
*/
|
|
1665
|
+
decode(tokens) {
|
|
1666
|
+
return this.decode_chain(tokens).join("");
|
|
1667
|
+
}
|
|
1668
|
+
};
|
|
1669
|
+
var Decoder_default = Decoder;
|
|
1670
|
+
var ByteLevel3 = class extends Decoder_default {
|
|
1671
|
+
/**
|
|
1672
|
+
* Create a `ByteLevelDecoder` object.
|
|
1673
|
+
*/
|
|
1674
|
+
constructor(config) {
|
|
1675
|
+
super(config);
|
|
1676
|
+
this.byte_decoder = UNICODE_TO_BYTES;
|
|
1677
|
+
this.text_decoder = new TextDecoder("utf-8", {
|
|
1678
|
+
fatal: false,
|
|
1679
|
+
ignoreBOM: true
|
|
1680
|
+
});
|
|
1681
|
+
this.end_of_word_suffix = null;
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* Convert an array of tokens to string by decoding each byte.
|
|
1685
|
+
* @param tokens Array of tokens to be decoded.
|
|
1686
|
+
* @returns The decoded string.
|
|
1687
|
+
*/
|
|
1688
|
+
convert_tokens_to_string(tokens) {
|
|
1689
|
+
const text = tokens.join("");
|
|
1690
|
+
const byte_array = new Uint8Array([...text].map((c) => this.byte_decoder[c]));
|
|
1691
|
+
return this.text_decoder.decode(byte_array);
|
|
1692
|
+
}
|
|
1693
|
+
decode_chain(tokens) {
|
|
1694
|
+
const sub_texts = [];
|
|
1695
|
+
let current_sub_text = [];
|
|
1696
|
+
for (const token of tokens) if (this.added_tokens.find((x) => x.content === token) !== void 0) {
|
|
1697
|
+
if (current_sub_text.length > 0) {
|
|
1698
|
+
sub_texts.push(this.convert_tokens_to_string(current_sub_text));
|
|
1699
|
+
current_sub_text = [];
|
|
1700
|
+
}
|
|
1701
|
+
sub_texts.push(token);
|
|
1702
|
+
} else current_sub_text.push(token);
|
|
1703
|
+
if (current_sub_text.length > 0) sub_texts.push(this.convert_tokens_to_string(current_sub_text));
|
|
1704
|
+
return sub_texts;
|
|
1705
|
+
}
|
|
1706
|
+
};
|
|
1707
|
+
var ByteLevel_default3 = ByteLevel3;
|
|
1708
|
+
var WordPiece = class extends Decoder_default {
|
|
1709
|
+
/**
|
|
1710
|
+
* Creates a new instance of WordPieceDecoder.
|
|
1711
|
+
* @param config The configuration object.
|
|
1712
|
+
*/
|
|
1713
|
+
constructor(config) {
|
|
1714
|
+
super(config);
|
|
1715
|
+
this.cleanup = config.cleanup;
|
|
1716
|
+
}
|
|
1717
|
+
decode_chain(tokens) {
|
|
1718
|
+
return tokens.map((token, i) => {
|
|
1719
|
+
if (i !== 0) {
|
|
1720
|
+
const prefix = this.config.prefix;
|
|
1721
|
+
if (prefix && token.startsWith(prefix)) token = token.replace(prefix, "");
|
|
1722
|
+
else token = " " + token;
|
|
1723
|
+
}
|
|
1724
|
+
if (this.cleanup) token = clean_up_tokenization(token);
|
|
1725
|
+
return token;
|
|
1726
|
+
});
|
|
1727
|
+
}
|
|
1728
|
+
};
|
|
1729
|
+
var WordPiece_default2 = WordPiece;
|
|
1730
|
+
var Metaspace2 = class extends Decoder_default {
|
|
1731
|
+
/**
|
|
1732
|
+
* Constructs a new MetaspaceDecoder object.
|
|
1733
|
+
* @param config The configuration object for the MetaspaceDecoder.
|
|
1734
|
+
*/
|
|
1735
|
+
constructor(config) {
|
|
1736
|
+
super(config);
|
|
1737
|
+
this.replacement = config.replacement ?? "▁";
|
|
1738
|
+
}
|
|
1739
|
+
decode_chain(tokens) {
|
|
1740
|
+
const result = [];
|
|
1741
|
+
for (let i = 0; i < tokens.length; ++i) {
|
|
1742
|
+
let normalized = tokens[i].replaceAll(this.replacement, " ");
|
|
1743
|
+
if (i == 0 && normalized.startsWith(" ")) normalized = normalized.substring(1);
|
|
1744
|
+
result.push(normalized);
|
|
1745
|
+
}
|
|
1746
|
+
return result;
|
|
1747
|
+
}
|
|
1748
|
+
};
|
|
1749
|
+
var Metaspace_default2 = Metaspace2;
|
|
1750
|
+
var BPE2 = class extends Decoder_default {
|
|
1751
|
+
constructor(config) {
|
|
1752
|
+
super(config);
|
|
1753
|
+
this.suffix = config.suffix ?? "";
|
|
1754
|
+
}
|
|
1755
|
+
decode_chain(tokens) {
|
|
1756
|
+
return tokens.map((token, i) => {
|
|
1757
|
+
return token.replaceAll(this.suffix, i === tokens.length - 1 ? "" : " ");
|
|
1758
|
+
});
|
|
1759
|
+
}
|
|
1760
|
+
};
|
|
1761
|
+
var BPE_default2 = BPE2;
|
|
1762
|
+
var CTC = class extends Decoder_default {
|
|
1763
|
+
constructor(config) {
|
|
1764
|
+
super(config);
|
|
1765
|
+
this.pad_token = config.pad_token ?? "";
|
|
1766
|
+
this.word_delimiter_token = config.word_delimiter_token ?? "";
|
|
1767
|
+
this.cleanup = config.cleanup;
|
|
1768
|
+
}
|
|
1769
|
+
/**
|
|
1770
|
+
* Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
|
|
1771
|
+
* @param tokens Array of tokens to be decoded.
|
|
1772
|
+
* @returns The decoded string.
|
|
1773
|
+
*/
|
|
1774
|
+
convert_tokens_to_string(tokens) {
|
|
1775
|
+
if (tokens.length === 0) return "";
|
|
1776
|
+
const grouped_tokens = [tokens[0]];
|
|
1777
|
+
for (let i = 1; i < tokens.length; ++i) if (tokens[i] !== grouped_tokens.at(-1)) grouped_tokens.push(tokens[i]);
|
|
1778
|
+
let text = grouped_tokens.filter((token) => token !== this.pad_token).join("");
|
|
1779
|
+
if (this.cleanup) text = clean_up_tokenization(text).replaceAll(this.word_delimiter_token, " ").trim();
|
|
1780
|
+
return text;
|
|
1781
|
+
}
|
|
1782
|
+
decode_chain(tokens) {
|
|
1783
|
+
return [this.convert_tokens_to_string(tokens)];
|
|
1784
|
+
}
|
|
1785
|
+
};
|
|
1786
|
+
var CTC_default = CTC;
|
|
1787
|
+
var Sequence4 = class extends Decoder_default {
|
|
1788
|
+
/**
|
|
1789
|
+
* Creates a new instance of DecoderSequence.
|
|
1790
|
+
* @param config The configuration object.
|
|
1791
|
+
*/
|
|
1792
|
+
constructor(config) {
|
|
1793
|
+
super(config);
|
|
1794
|
+
this.decoders = (config.decoders ?? []).map((x) => create_decoder_default(x));
|
|
1795
|
+
}
|
|
1796
|
+
decode_chain(tokens) {
|
|
1797
|
+
return this.decoders.reduce((toks, decoder) => {
|
|
1798
|
+
return decoder.decode_chain(toks);
|
|
1799
|
+
}, tokens);
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
var Sequence_default4 = Sequence4;
|
|
1803
|
+
var Replace3 = class extends Decoder_default {
|
|
1804
|
+
decode_chain(tokens) {
|
|
1805
|
+
const pattern = create_pattern(this.config.pattern);
|
|
1806
|
+
const content = this.config.content ?? "";
|
|
1807
|
+
return pattern === null ? tokens : tokens.map((token) => token.replaceAll(pattern, content));
|
|
1808
|
+
}
|
|
1809
|
+
};
|
|
1810
|
+
var Replace_default3 = Replace3;
|
|
1811
|
+
var Fuse = class extends Decoder_default {
|
|
1812
|
+
decode_chain(tokens) {
|
|
1813
|
+
return [tokens.join("")];
|
|
1814
|
+
}
|
|
1815
|
+
};
|
|
1816
|
+
var Fuse_default = Fuse;
|
|
1817
|
+
var Strip2 = class extends Decoder_default {
|
|
1818
|
+
constructor(config) {
|
|
1819
|
+
super(config);
|
|
1820
|
+
this.content = config.content ?? "";
|
|
1821
|
+
this.start = config.start ?? 0;
|
|
1822
|
+
this.stop = config.stop ?? 0;
|
|
1823
|
+
}
|
|
1824
|
+
decode_chain(tokens) {
|
|
1825
|
+
return tokens.map((token) => {
|
|
1826
|
+
let start_cut = 0;
|
|
1827
|
+
for (let i = 0; i < this.start; ++i) if (token[i] === this.content) {
|
|
1828
|
+
start_cut = i + 1;
|
|
1829
|
+
continue;
|
|
1830
|
+
} else break;
|
|
1831
|
+
let stop_cut = token.length;
|
|
1832
|
+
for (let i = 0; i < this.stop; ++i) {
|
|
1833
|
+
const index = token.length - i - 1;
|
|
1834
|
+
if (token[index] === this.content) {
|
|
1835
|
+
stop_cut = index;
|
|
1836
|
+
continue;
|
|
1837
|
+
} else break;
|
|
1838
|
+
}
|
|
1839
|
+
return token.slice(start_cut, stop_cut);
|
|
1840
|
+
});
|
|
1841
|
+
}
|
|
1842
|
+
};
|
|
1843
|
+
var Strip_default2 = Strip2;
|
|
1844
|
+
var ByteFallback = class extends Decoder_default {
|
|
1845
|
+
constructor(config) {
|
|
1846
|
+
super(config);
|
|
1847
|
+
this.text_decoder = new TextDecoder();
|
|
1848
|
+
}
|
|
1849
|
+
decode_chain(tokens) {
|
|
1850
|
+
const new_tokens = [];
|
|
1851
|
+
let previous_byte_tokens = [];
|
|
1852
|
+
for (const token of tokens) {
|
|
1853
|
+
let bytes = null;
|
|
1854
|
+
if (token.length === 6 && token.startsWith("<0x") && token.endsWith(">")) {
|
|
1855
|
+
const byte = parseInt(token.slice(3, 5), 16);
|
|
1856
|
+
if (!isNaN(byte)) bytes = byte;
|
|
1857
|
+
}
|
|
1858
|
+
if (bytes !== null) previous_byte_tokens.push(bytes);
|
|
1859
|
+
else {
|
|
1860
|
+
if (previous_byte_tokens.length > 0) {
|
|
1861
|
+
const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
|
|
1862
|
+
new_tokens.push(string);
|
|
1863
|
+
previous_byte_tokens = [];
|
|
1864
|
+
}
|
|
1865
|
+
new_tokens.push(token);
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
if (previous_byte_tokens.length > 0) {
|
|
1869
|
+
const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
|
|
1870
|
+
new_tokens.push(string);
|
|
1871
|
+
previous_byte_tokens = [];
|
|
1872
|
+
}
|
|
1873
|
+
return new_tokens;
|
|
1874
|
+
}
|
|
1875
|
+
};
|
|
1876
|
+
var ByteFallback_default = ByteFallback;
|
|
1877
|
+
function create_decoder(config) {
|
|
1878
|
+
if (config === null) return null;
|
|
1879
|
+
switch (config.type) {
|
|
1880
|
+
case "ByteLevel": return new ByteLevel_default3(config);
|
|
1881
|
+
case "WordPiece": return new WordPiece_default2(config);
|
|
1882
|
+
case "Metaspace": return new Metaspace_default2(config);
|
|
1883
|
+
case "BPEDecoder": return new BPE_default2(config);
|
|
1884
|
+
case "CTC": return new CTC_default(config);
|
|
1885
|
+
case "Sequence": return new Sequence_default4(config);
|
|
1886
|
+
case "Replace": return new Replace_default3(config);
|
|
1887
|
+
case "Fuse": return new Fuse_default(config);
|
|
1888
|
+
case "Strip": return new Strip_default2(config);
|
|
1889
|
+
case "ByteFallback": return new ByteFallback_default(config);
|
|
1890
|
+
default: throw new Error(`Unknown Decoder type: ${config.type}`);
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
var create_decoder_default = create_decoder;
|
|
1894
|
+
var Tokenizer = class {
|
|
1895
|
+
constructor(tokenizer, config) {
|
|
1896
|
+
const tokenizer_error = validate_object(tokenizer, "Tokenizer", [
|
|
1897
|
+
"model",
|
|
1898
|
+
"decoder",
|
|
1899
|
+
"post_processor",
|
|
1900
|
+
"pre_tokenizer",
|
|
1901
|
+
"normalizer"
|
|
1902
|
+
]);
|
|
1903
|
+
if (tokenizer_error) throw new Error(tokenizer_error);
|
|
1904
|
+
const config_error = validate_object(config, "Config");
|
|
1905
|
+
if (config_error) throw new Error(config_error);
|
|
1906
|
+
this.tokenizer = tokenizer;
|
|
1907
|
+
this.config = config;
|
|
1908
|
+
this.normalizer = create_normalizer_default(this.tokenizer.normalizer);
|
|
1909
|
+
this.pre_tokenizer = create_pre_tokenizer_default(this.tokenizer.pre_tokenizer);
|
|
1910
|
+
this.model = create_tokenizer_model_default(this.tokenizer.model, this.config);
|
|
1911
|
+
this.post_processor = create_post_processor_default(this.tokenizer.post_processor);
|
|
1912
|
+
this.decoder = create_decoder_default(this.tokenizer.decoder);
|
|
1913
|
+
this.special_tokens = [];
|
|
1914
|
+
this.all_special_ids = [];
|
|
1915
|
+
this.added_tokens = [];
|
|
1916
|
+
const unnormalized_contents = [];
|
|
1917
|
+
const normalized_contents = [];
|
|
1918
|
+
this.added_tokens_map = /* @__PURE__ */ new Map();
|
|
1919
|
+
for (const added_token of this.tokenizer.added_tokens) {
|
|
1920
|
+
const token = new AddedToken_default(added_token);
|
|
1921
|
+
this.added_tokens.push(token);
|
|
1922
|
+
this.model.tokens_to_ids.set(token.content, token.id);
|
|
1923
|
+
this.model.vocab[token.id] = token.content;
|
|
1924
|
+
if (token.special) {
|
|
1925
|
+
this.special_tokens.push(token.content);
|
|
1926
|
+
this.all_special_ids.push(token.id);
|
|
1927
|
+
}
|
|
1928
|
+
this.added_tokens_map.set(token.content, token);
|
|
1929
|
+
if (token.normalized && this.normalizer !== null) {
|
|
1930
|
+
const normalized_content = this.normalizer(token.content);
|
|
1931
|
+
normalized_contents.push(normalized_content);
|
|
1932
|
+
this.added_tokens_map.set(normalized_content, token);
|
|
1933
|
+
} else unnormalized_contents.push(token.content);
|
|
1934
|
+
}
|
|
1935
|
+
(this.config.additional_special_tokens ?? []).forEach((token) => {
|
|
1936
|
+
if (!this.special_tokens.includes(token)) this.special_tokens.push(token);
|
|
1937
|
+
});
|
|
1938
|
+
if (this.decoder) {
|
|
1939
|
+
this.decoder.added_tokens = this.added_tokens;
|
|
1940
|
+
this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;
|
|
1941
|
+
}
|
|
1942
|
+
this.splitter_unnormalized = new DictionarySplitter_default(unnormalized_contents);
|
|
1943
|
+
this.splitter_normalized = new DictionarySplitter_default(normalized_contents);
|
|
1944
|
+
this.remove_space = this.config.remove_space;
|
|
1945
|
+
this.clean_up_tokenization_spaces = this.config.clean_up_tokenization_spaces ?? true;
|
|
1946
|
+
this.do_lowercase_and_remove_accent = this.config.do_lowercase_and_remove_accent ?? false;
|
|
1947
|
+
}
|
|
1948
|
+
encode(text, { text_pair = null, add_special_tokens = true, return_token_type_ids = null } = {}) {
|
|
1949
|
+
const { tokens, token_type_ids } = this.tokenize_helper(text, {
|
|
1950
|
+
text_pair,
|
|
1951
|
+
add_special_tokens
|
|
1952
|
+
});
|
|
1953
|
+
const input_ids = tokens.map((t) => this.added_tokens_map.get(t)?.id ?? this.model.tokens_to_ids.get(t) ?? this.model.unk_token_id);
|
|
1954
|
+
const result = {
|
|
1955
|
+
ids: input_ids,
|
|
1956
|
+
tokens,
|
|
1957
|
+
attention_mask: new Array(input_ids.length).fill(1)
|
|
1958
|
+
};
|
|
1959
|
+
if (return_token_type_ids && token_type_ids) result.token_type_ids = token_type_ids;
|
|
1960
|
+
return result;
|
|
1961
|
+
}
|
|
1962
|
+
decode(token_ids, options = {}) {
|
|
1963
|
+
if (!Array.isArray(token_ids) || token_ids.length === 0 || !is_integral_number(token_ids[0])) throw Error("token_ids must be a non-empty array of integers.");
|
|
1964
|
+
let tokens = token_ids.map((i) => this.model.vocab[Number(i)] ?? this.model.unk_token);
|
|
1965
|
+
if (options.skip_special_tokens) tokens = tokens.filter((x) => !this.special_tokens.includes(x));
|
|
1966
|
+
let decoded = this.decoder ? this.decoder(tokens) : tokens.join(" ");
|
|
1967
|
+
if (this.decoder && this.decoder.end_of_word_suffix) {
|
|
1968
|
+
decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, " ");
|
|
1969
|
+
if (options.skip_special_tokens) decoded = decoded.trim();
|
|
1970
|
+
}
|
|
1971
|
+
if (options.clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) decoded = clean_up_tokenization(decoded);
|
|
1972
|
+
return decoded;
|
|
1973
|
+
}
|
|
1974
|
+
/**
|
|
1975
|
+
* Converts a string into a sequence of tokens.
|
|
1976
|
+
* @param text The sequence to be encoded.
|
|
1977
|
+
* @param options An optional object containing the following properties:
|
|
1978
|
+
* @returns The list of tokens.
|
|
1979
|
+
*/
|
|
1980
|
+
tokenize(text, { text_pair = null, add_special_tokens = false } = {}) {
|
|
1981
|
+
return this.tokenize_helper(text, {
|
|
1982
|
+
text_pair,
|
|
1983
|
+
add_special_tokens
|
|
1984
|
+
}).tokens;
|
|
1985
|
+
}
|
|
1986
|
+
encode_text(text) {
|
|
1987
|
+
if (text === null) return null;
|
|
1988
|
+
const sections = this.splitter_unnormalized.split(text);
|
|
1989
|
+
sections.forEach((section, i) => {
|
|
1990
|
+
const added_token = this.added_tokens_map.get(section);
|
|
1991
|
+
if (added_token) {
|
|
1992
|
+
if (added_token.lstrip && i > 0) sections[i - 1] = sections[i - 1].trimEnd();
|
|
1993
|
+
if (added_token.rstrip && i < sections.length - 1) sections[i + 1] = sections[i + 1].trimStart();
|
|
1994
|
+
}
|
|
1995
|
+
});
|
|
1996
|
+
return sections.flatMap((processed_text, section_index) => {
|
|
1997
|
+
if (processed_text.length === 0) return [];
|
|
1998
|
+
if (this.added_tokens_map.has(processed_text)) return [processed_text];
|
|
1999
|
+
if (this.remove_space === true) processed_text = processed_text.trim().split(/\s+/).join(" ");
|
|
2000
|
+
if (this.do_lowercase_and_remove_accent) processed_text = lowercase_and_remove_accents(processed_text);
|
|
2001
|
+
if (this.normalizer !== null) processed_text = this.normalizer(processed_text);
|
|
2002
|
+
if (processed_text.length === 0) return [];
|
|
2003
|
+
const subsections = this.splitter_normalized.split(processed_text);
|
|
2004
|
+
subsections.forEach((subsection, j) => {
|
|
2005
|
+
const added_token = this.added_tokens_map.get(subsection);
|
|
2006
|
+
if (added_token) {
|
|
2007
|
+
if (added_token.lstrip && j > 0) subsections[j - 1] = subsections[j - 1].trimEnd();
|
|
2008
|
+
if (added_token.rstrip && j < subsections.length - 1) subsections[j + 1] = subsections[j + 1].trimStart();
|
|
2009
|
+
}
|
|
2010
|
+
});
|
|
2011
|
+
return subsections.flatMap((subsection) => {
|
|
2012
|
+
if (subsection.length === 0) return [];
|
|
2013
|
+
if (this.added_tokens_map.has(subsection)) return [subsection];
|
|
2014
|
+
const section_tokens = this.pre_tokenizer !== null ? this.pre_tokenizer(subsection, { section_index }) : [subsection];
|
|
2015
|
+
return this.model(section_tokens);
|
|
2016
|
+
});
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
tokenize_helper(text, { text_pair = null, add_special_tokens = true }) {
|
|
2020
|
+
const tokens1 = this.encode_text(text);
|
|
2021
|
+
const tokens2 = this.encode_text(text_pair || null);
|
|
2022
|
+
return this.post_processor ? this.post_processor(tokens1, tokens2, add_special_tokens) : { tokens: merge_arrays(tokens1 ?? [], tokens2 ?? []) };
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Converts a token string to its corresponding token ID.
|
|
2026
|
+
* @param token The token string to convert.
|
|
2027
|
+
* @returns The token ID, or undefined if the token is not in the vocabulary.
|
|
2028
|
+
*/
|
|
2029
|
+
token_to_id(token) {
|
|
2030
|
+
return this.model.tokens_to_ids.get(token);
|
|
2031
|
+
}
|
|
2032
|
+
/**
|
|
2033
|
+
* Converts a token ID to its corresponding token string.
|
|
2034
|
+
* @param id The token ID to convert.
|
|
2035
|
+
* @returns The token string, or undefined if the ID is not in the vocabulary.
|
|
2036
|
+
*/
|
|
2037
|
+
id_to_token(id) {
|
|
2038
|
+
return this.model.vocab[id];
|
|
2039
|
+
}
|
|
2040
|
+
/**
|
|
2041
|
+
* Returns a mapping of token IDs to AddedToken objects for all added tokens.
|
|
2042
|
+
* @returns A Map where keys are token IDs and values are AddedToken objects.
|
|
2043
|
+
*/
|
|
2044
|
+
get_added_tokens_decoder() {
|
|
2045
|
+
const decoder = /* @__PURE__ */ new Map();
|
|
2046
|
+
for (const token of this.added_tokens) decoder.set(token.id, token);
|
|
2047
|
+
return decoder;
|
|
2048
|
+
}
|
|
2049
|
+
/**
|
|
2050
|
+
* Get the underlying vocabulary
|
|
2051
|
+
* @param with_added_tokens Whether to include the added tokens
|
|
2052
|
+
* @returns The vocabulary
|
|
2053
|
+
*/
|
|
2054
|
+
get_vocab(with_added_tokens = true) {
|
|
2055
|
+
const vocab = /* @__PURE__ */ new Map();
|
|
2056
|
+
for (let i = 0; i < this.model.vocab.length; ++i) {
|
|
2057
|
+
const token = this.model.vocab[i];
|
|
2058
|
+
if (with_added_tokens || !this.added_tokens_map.has(token)) vocab.set(token, i);
|
|
2059
|
+
}
|
|
2060
|
+
return vocab;
|
|
2061
|
+
}
|
|
2062
|
+
};
|
|
2063
|
+
var Tokenizer_default = Tokenizer;
|
|
2064
|
+
//#endregion
|
|
2065
|
+
//#region node_modules/@huggingface/jinja/dist/index.js
|
|
2066
|
+
var __defProp = Object.defineProperty;
|
|
2067
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
2068
|
+
enumerable: true,
|
|
2069
|
+
configurable: true,
|
|
2070
|
+
writable: true,
|
|
2071
|
+
value
|
|
2072
|
+
}) : obj[key] = value;
|
|
2073
|
+
var __publicField = (obj, key, value) => {
|
|
2074
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
2075
|
+
return value;
|
|
2076
|
+
};
|
|
2077
|
+
var TOKEN_TYPES = Object.freeze({
|
|
2078
|
+
Text: "Text",
|
|
2079
|
+
NumericLiteral: "NumericLiteral",
|
|
2080
|
+
StringLiteral: "StringLiteral",
|
|
2081
|
+
Identifier: "Identifier",
|
|
2082
|
+
Equals: "Equals",
|
|
2083
|
+
OpenParen: "OpenParen",
|
|
2084
|
+
CloseParen: "CloseParen",
|
|
2085
|
+
OpenStatement: "OpenStatement",
|
|
2086
|
+
CloseStatement: "CloseStatement",
|
|
2087
|
+
OpenExpression: "OpenExpression",
|
|
2088
|
+
CloseExpression: "CloseExpression",
|
|
2089
|
+
OpenSquareBracket: "OpenSquareBracket",
|
|
2090
|
+
CloseSquareBracket: "CloseSquareBracket",
|
|
2091
|
+
OpenCurlyBracket: "OpenCurlyBracket",
|
|
2092
|
+
CloseCurlyBracket: "CloseCurlyBracket",
|
|
2093
|
+
Comma: "Comma",
|
|
2094
|
+
Dot: "Dot",
|
|
2095
|
+
Colon: "Colon",
|
|
2096
|
+
Pipe: "Pipe",
|
|
2097
|
+
CallOperator: "CallOperator",
|
|
2098
|
+
AdditiveBinaryOperator: "AdditiveBinaryOperator",
|
|
2099
|
+
MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator",
|
|
2100
|
+
ComparisonBinaryOperator: "ComparisonBinaryOperator",
|
|
2101
|
+
UnaryOperator: "UnaryOperator",
|
|
2102
|
+
Comment: "Comment"
|
|
2103
|
+
});
|
|
2104
|
+
var Token = class {
|
|
2105
|
+
/**
|
|
2106
|
+
* Constructs a new Token.
|
|
2107
|
+
* @param {string} value The raw value as seen inside the source code.
|
|
2108
|
+
* @param {TokenType} type The type of token.
|
|
2109
|
+
*/
|
|
2110
|
+
constructor(value, type) {
|
|
2111
|
+
this.value = value;
|
|
2112
|
+
this.type = type;
|
|
2113
|
+
}
|
|
2114
|
+
};
|
|
2115
|
+
function isWord(char) {
|
|
2116
|
+
return /\w/.test(char);
|
|
2117
|
+
}
|
|
2118
|
+
function isInteger(char) {
|
|
2119
|
+
return /[0-9]/.test(char);
|
|
2120
|
+
}
|
|
2121
|
+
function isWhitespace(char) {
|
|
2122
|
+
return /\s/.test(char);
|
|
2123
|
+
}
|
|
2124
|
+
var ORDERED_MAPPING_TABLE = [
|
|
2125
|
+
["{%", TOKEN_TYPES.OpenStatement],
|
|
2126
|
+
["%}", TOKEN_TYPES.CloseStatement],
|
|
2127
|
+
["{{", TOKEN_TYPES.OpenExpression],
|
|
2128
|
+
["}}", TOKEN_TYPES.CloseExpression],
|
|
2129
|
+
["(", TOKEN_TYPES.OpenParen],
|
|
2130
|
+
[")", TOKEN_TYPES.CloseParen],
|
|
2131
|
+
["{", TOKEN_TYPES.OpenCurlyBracket],
|
|
2132
|
+
["}", TOKEN_TYPES.CloseCurlyBracket],
|
|
2133
|
+
["[", TOKEN_TYPES.OpenSquareBracket],
|
|
2134
|
+
["]", TOKEN_TYPES.CloseSquareBracket],
|
|
2135
|
+
[",", TOKEN_TYPES.Comma],
|
|
2136
|
+
[".", TOKEN_TYPES.Dot],
|
|
2137
|
+
[":", TOKEN_TYPES.Colon],
|
|
2138
|
+
["|", TOKEN_TYPES.Pipe],
|
|
2139
|
+
["<=", TOKEN_TYPES.ComparisonBinaryOperator],
|
|
2140
|
+
[">=", TOKEN_TYPES.ComparisonBinaryOperator],
|
|
2141
|
+
["==", TOKEN_TYPES.ComparisonBinaryOperator],
|
|
2142
|
+
["!=", TOKEN_TYPES.ComparisonBinaryOperator],
|
|
2143
|
+
["<", TOKEN_TYPES.ComparisonBinaryOperator],
|
|
2144
|
+
[">", TOKEN_TYPES.ComparisonBinaryOperator],
|
|
2145
|
+
["+", TOKEN_TYPES.AdditiveBinaryOperator],
|
|
2146
|
+
["-", TOKEN_TYPES.AdditiveBinaryOperator],
|
|
2147
|
+
["~", TOKEN_TYPES.AdditiveBinaryOperator],
|
|
2148
|
+
["*", TOKEN_TYPES.MultiplicativeBinaryOperator],
|
|
2149
|
+
["/", TOKEN_TYPES.MultiplicativeBinaryOperator],
|
|
2150
|
+
["%", TOKEN_TYPES.MultiplicativeBinaryOperator],
|
|
2151
|
+
["=", TOKEN_TYPES.Equals]
|
|
2152
|
+
];
|
|
2153
|
+
var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([
|
|
2154
|
+
["n", "\n"],
|
|
2155
|
+
["t", " "],
|
|
2156
|
+
["r", "\r"],
|
|
2157
|
+
["b", "\b"],
|
|
2158
|
+
["f", "\f"],
|
|
2159
|
+
["v", "\v"],
|
|
2160
|
+
["'", "'"],
|
|
2161
|
+
["\"", "\""],
|
|
2162
|
+
["\\", "\\"]
|
|
2163
|
+
]);
|
|
2164
|
+
function preprocess(template, options = {}) {
|
|
2165
|
+
if (template.endsWith("\n")) template = template.slice(0, -1);
|
|
2166
|
+
if (options.lstrip_blocks) template = template.replace(/^[ \t]*({[#%-])/gm, "$1");
|
|
2167
|
+
if (options.trim_blocks) template = template.replace(/([#%-]})\n/g, "$1");
|
|
2168
|
+
return template.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs, (_, before, lstrip, rstrip, after) => (lstrip ? "" : before) + (rstrip ? "" : after));
|
|
2169
|
+
}
|
|
2170
|
+
function tokenize(source, options = {}) {
|
|
2171
|
+
const tokens = [];
|
|
2172
|
+
const src = preprocess(source, options);
|
|
2173
|
+
let cursorPosition = 0;
|
|
2174
|
+
let curlyBracketDepth = 0;
|
|
2175
|
+
const consumeWhile = (predicate) => {
|
|
2176
|
+
let str = "";
|
|
2177
|
+
while (predicate(src[cursorPosition])) {
|
|
2178
|
+
if (src[cursorPosition] === "\\") {
|
|
2179
|
+
++cursorPosition;
|
|
2180
|
+
if (cursorPosition >= src.length) throw new SyntaxError("Unexpected end of input");
|
|
2181
|
+
const escaped = src[cursorPosition++];
|
|
2182
|
+
const unescaped = ESCAPE_CHARACTERS.get(escaped);
|
|
2183
|
+
if (unescaped === void 0) throw new SyntaxError(`Unexpected escaped character: ${escaped}`);
|
|
2184
|
+
str += unescaped;
|
|
2185
|
+
continue;
|
|
2186
|
+
}
|
|
2187
|
+
str += src[cursorPosition++];
|
|
2188
|
+
if (cursorPosition >= src.length) throw new SyntaxError("Unexpected end of input");
|
|
2189
|
+
}
|
|
2190
|
+
return str;
|
|
2191
|
+
};
|
|
2192
|
+
const stripTrailingWhitespace = () => {
|
|
2193
|
+
const lastToken = tokens.at(-1);
|
|
2194
|
+
if (lastToken && lastToken.type === TOKEN_TYPES.Text) {
|
|
2195
|
+
lastToken.value = lastToken.value.trimEnd();
|
|
2196
|
+
if (lastToken.value === "") tokens.pop();
|
|
2197
|
+
}
|
|
2198
|
+
};
|
|
2199
|
+
const skipLeadingWhitespace = () => {
|
|
2200
|
+
while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) ++cursorPosition;
|
|
2201
|
+
};
|
|
2202
|
+
main: while (cursorPosition < src.length) {
|
|
2203
|
+
const lastTokenType = tokens.at(-1)?.type;
|
|
2204
|
+
if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) {
|
|
2205
|
+
let text = "";
|
|
2206
|
+
while (cursorPosition < src.length && !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{" || src[cursorPosition + 1] === "#"))) text += src[cursorPosition++];
|
|
2207
|
+
if (text.length > 0) {
|
|
2208
|
+
tokens.push(new Token(text, TOKEN_TYPES.Text));
|
|
2209
|
+
continue;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") {
|
|
2213
|
+
cursorPosition += 2;
|
|
2214
|
+
const stripBefore = src[cursorPosition] === "-";
|
|
2215
|
+
if (stripBefore) ++cursorPosition;
|
|
2216
|
+
let comment = "";
|
|
2217
|
+
while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") {
|
|
2218
|
+
if (cursorPosition + 2 >= src.length) throw new SyntaxError("Missing end of comment tag");
|
|
2219
|
+
comment += src[cursorPosition++];
|
|
2220
|
+
}
|
|
2221
|
+
const stripAfter = comment.endsWith("-");
|
|
2222
|
+
if (stripAfter) comment = comment.slice(0, -1);
|
|
2223
|
+
if (stripBefore) stripTrailingWhitespace();
|
|
2224
|
+
tokens.push(new Token(comment, TOKEN_TYPES.Comment));
|
|
2225
|
+
cursorPosition += 2;
|
|
2226
|
+
if (stripAfter) skipLeadingWhitespace();
|
|
2227
|
+
continue;
|
|
2228
|
+
}
|
|
2229
|
+
if (src.slice(cursorPosition, cursorPosition + 3) === "{%-") {
|
|
2230
|
+
stripTrailingWhitespace();
|
|
2231
|
+
tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement));
|
|
2232
|
+
cursorPosition += 3;
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
if (src.slice(cursorPosition, cursorPosition + 3) === "{{-") {
|
|
2236
|
+
stripTrailingWhitespace();
|
|
2237
|
+
tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression));
|
|
2238
|
+
curlyBracketDepth = 0;
|
|
2239
|
+
cursorPosition += 3;
|
|
2240
|
+
continue;
|
|
2241
|
+
}
|
|
2242
|
+
consumeWhile(isWhitespace);
|
|
2243
|
+
if (src.slice(cursorPosition, cursorPosition + 3) === "-%}") {
|
|
2244
|
+
tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement));
|
|
2245
|
+
cursorPosition += 3;
|
|
2246
|
+
skipLeadingWhitespace();
|
|
2247
|
+
continue;
|
|
2248
|
+
}
|
|
2249
|
+
if (src.slice(cursorPosition, cursorPosition + 3) === "-}}") {
|
|
2250
|
+
tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression));
|
|
2251
|
+
cursorPosition += 3;
|
|
2252
|
+
skipLeadingWhitespace();
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
const char = src[cursorPosition];
|
|
2256
|
+
if (char === "-" || char === "+") {
|
|
2257
|
+
const lastTokenType2 = tokens.at(-1)?.type;
|
|
2258
|
+
if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) throw new SyntaxError(`Unexpected character: ${char}`);
|
|
2259
|
+
switch (lastTokenType2) {
|
|
2260
|
+
case TOKEN_TYPES.Identifier:
|
|
2261
|
+
case TOKEN_TYPES.NumericLiteral:
|
|
2262
|
+
case TOKEN_TYPES.StringLiteral:
|
|
2263
|
+
case TOKEN_TYPES.CloseParen:
|
|
2264
|
+
case TOKEN_TYPES.CloseSquareBracket: break;
|
|
2265
|
+
default: {
|
|
2266
|
+
++cursorPosition;
|
|
2267
|
+
const num = consumeWhile(isInteger);
|
|
2268
|
+
tokens.push(new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator));
|
|
2269
|
+
continue;
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
for (const [seq, type] of ORDERED_MAPPING_TABLE) {
|
|
2274
|
+
if (seq === "}}" && curlyBracketDepth > 0) continue;
|
|
2275
|
+
if (src.slice(cursorPosition, cursorPosition + seq.length) === seq) {
|
|
2276
|
+
tokens.push(new Token(seq, type));
|
|
2277
|
+
if (type === TOKEN_TYPES.OpenExpression) curlyBracketDepth = 0;
|
|
2278
|
+
else if (type === TOKEN_TYPES.OpenCurlyBracket) ++curlyBracketDepth;
|
|
2279
|
+
else if (type === TOKEN_TYPES.CloseCurlyBracket) --curlyBracketDepth;
|
|
2280
|
+
cursorPosition += seq.length;
|
|
2281
|
+
continue main;
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
if (char === "'" || char === "\"") {
|
|
2285
|
+
++cursorPosition;
|
|
2286
|
+
const str = consumeWhile((c) => c !== char);
|
|
2287
|
+
tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));
|
|
2288
|
+
++cursorPosition;
|
|
2289
|
+
continue;
|
|
2290
|
+
}
|
|
2291
|
+
if (isInteger(char)) {
|
|
2292
|
+
let num = consumeWhile(isInteger);
|
|
2293
|
+
if (tokens.at(-1)?.type !== TOKEN_TYPES.Dot && src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) {
|
|
2294
|
+
++cursorPosition;
|
|
2295
|
+
const frac = consumeWhile(isInteger);
|
|
2296
|
+
num = `${num}.${frac}`;
|
|
2297
|
+
}
|
|
2298
|
+
tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));
|
|
2299
|
+
continue;
|
|
2300
|
+
}
|
|
2301
|
+
if (isWord(char)) {
|
|
2302
|
+
const word = consumeWhile(isWord);
|
|
2303
|
+
tokens.push(new Token(word, TOKEN_TYPES.Identifier));
|
|
2304
|
+
continue;
|
|
2305
|
+
}
|
|
2306
|
+
throw new SyntaxError(`Unexpected character: ${char}`);
|
|
2307
|
+
}
|
|
2308
|
+
return tokens;
|
|
2309
|
+
}
|
|
2310
|
+
var Statement = class {
|
|
2311
|
+
type = "Statement";
|
|
2312
|
+
};
|
|
2313
|
+
var Program = class extends Statement {
|
|
2314
|
+
constructor(body) {
|
|
2315
|
+
super();
|
|
2316
|
+
this.body = body;
|
|
2317
|
+
}
|
|
2318
|
+
type = "Program";
|
|
2319
|
+
};
|
|
2320
|
+
var If = class extends Statement {
|
|
2321
|
+
constructor(test, body, alternate) {
|
|
2322
|
+
super();
|
|
2323
|
+
this.test = test;
|
|
2324
|
+
this.body = body;
|
|
2325
|
+
this.alternate = alternate;
|
|
2326
|
+
}
|
|
2327
|
+
type = "If";
|
|
2328
|
+
};
|
|
2329
|
+
var For = class extends Statement {
|
|
2330
|
+
constructor(loopvar, iterable, body, defaultBlock) {
|
|
2331
|
+
super();
|
|
2332
|
+
this.loopvar = loopvar;
|
|
2333
|
+
this.iterable = iterable;
|
|
2334
|
+
this.body = body;
|
|
2335
|
+
this.defaultBlock = defaultBlock;
|
|
2336
|
+
}
|
|
2337
|
+
type = "For";
|
|
2338
|
+
};
|
|
2339
|
+
var Break = class extends Statement {
|
|
2340
|
+
type = "Break";
|
|
2341
|
+
};
|
|
2342
|
+
var Continue = class extends Statement {
|
|
2343
|
+
type = "Continue";
|
|
2344
|
+
};
|
|
2345
|
+
var SetStatement = class extends Statement {
|
|
2346
|
+
constructor(assignee, value, body) {
|
|
2347
|
+
super();
|
|
2348
|
+
this.assignee = assignee;
|
|
2349
|
+
this.value = value;
|
|
2350
|
+
this.body = body;
|
|
2351
|
+
}
|
|
2352
|
+
type = "Set";
|
|
2353
|
+
};
|
|
2354
|
+
var Macro = class extends Statement {
|
|
2355
|
+
constructor(name, args, body) {
|
|
2356
|
+
super();
|
|
2357
|
+
this.name = name;
|
|
2358
|
+
this.args = args;
|
|
2359
|
+
this.body = body;
|
|
2360
|
+
}
|
|
2361
|
+
type = "Macro";
|
|
2362
|
+
};
|
|
2363
|
+
var Comment = class extends Statement {
|
|
2364
|
+
constructor(value) {
|
|
2365
|
+
super();
|
|
2366
|
+
this.value = value;
|
|
2367
|
+
}
|
|
2368
|
+
type = "Comment";
|
|
2369
|
+
};
|
|
2370
|
+
var Expression = class extends Statement {
|
|
2371
|
+
type = "Expression";
|
|
2372
|
+
};
|
|
2373
|
+
var MemberExpression = class extends Expression {
|
|
2374
|
+
constructor(object, property, computed) {
|
|
2375
|
+
super();
|
|
2376
|
+
this.object = object;
|
|
2377
|
+
this.property = property;
|
|
2378
|
+
this.computed = computed;
|
|
2379
|
+
}
|
|
2380
|
+
type = "MemberExpression";
|
|
2381
|
+
};
|
|
2382
|
+
var CallExpression = class extends Expression {
|
|
2383
|
+
constructor(callee, args) {
|
|
2384
|
+
super();
|
|
2385
|
+
this.callee = callee;
|
|
2386
|
+
this.args = args;
|
|
2387
|
+
}
|
|
2388
|
+
type = "CallExpression";
|
|
2389
|
+
};
|
|
2390
|
+
var Identifier = class extends Expression {
|
|
2391
|
+
/**
|
|
2392
|
+
* @param {string} value The name of the identifier
|
|
2393
|
+
*/
|
|
2394
|
+
constructor(value) {
|
|
2395
|
+
super();
|
|
2396
|
+
this.value = value;
|
|
2397
|
+
}
|
|
2398
|
+
type = "Identifier";
|
|
2399
|
+
};
|
|
2400
|
+
var Literal = class extends Expression {
|
|
2401
|
+
constructor(value) {
|
|
2402
|
+
super();
|
|
2403
|
+
this.value = value;
|
|
2404
|
+
}
|
|
2405
|
+
type = "Literal";
|
|
2406
|
+
};
|
|
2407
|
+
var IntegerLiteral = class extends Literal {
|
|
2408
|
+
type = "IntegerLiteral";
|
|
2409
|
+
};
|
|
2410
|
+
var FloatLiteral = class extends Literal {
|
|
2411
|
+
type = "FloatLiteral";
|
|
2412
|
+
};
|
|
2413
|
+
var StringLiteral = class extends Literal {
|
|
2414
|
+
type = "StringLiteral";
|
|
2415
|
+
};
|
|
2416
|
+
var ArrayLiteral = class extends Literal {
|
|
2417
|
+
type = "ArrayLiteral";
|
|
2418
|
+
};
|
|
2419
|
+
var TupleLiteral = class extends Literal {
|
|
2420
|
+
type = "TupleLiteral";
|
|
2421
|
+
};
|
|
2422
|
+
var ObjectLiteral = class extends Literal {
|
|
2423
|
+
type = "ObjectLiteral";
|
|
2424
|
+
};
|
|
2425
|
+
var BinaryExpression = class extends Expression {
|
|
2426
|
+
constructor(operator, left, right) {
|
|
2427
|
+
super();
|
|
2428
|
+
this.operator = operator;
|
|
2429
|
+
this.left = left;
|
|
2430
|
+
this.right = right;
|
|
2431
|
+
}
|
|
2432
|
+
type = "BinaryExpression";
|
|
2433
|
+
};
|
|
2434
|
+
var FilterExpression = class extends Expression {
|
|
2435
|
+
constructor(operand, filter) {
|
|
2436
|
+
super();
|
|
2437
|
+
this.operand = operand;
|
|
2438
|
+
this.filter = filter;
|
|
2439
|
+
}
|
|
2440
|
+
type = "FilterExpression";
|
|
2441
|
+
};
|
|
2442
|
+
var FilterStatement = class extends Statement {
|
|
2443
|
+
constructor(filter, body) {
|
|
2444
|
+
super();
|
|
2445
|
+
this.filter = filter;
|
|
2446
|
+
this.body = body;
|
|
2447
|
+
}
|
|
2448
|
+
type = "FilterStatement";
|
|
2449
|
+
};
|
|
2450
|
+
var SelectExpression = class extends Expression {
|
|
2451
|
+
constructor(lhs, test) {
|
|
2452
|
+
super();
|
|
2453
|
+
this.lhs = lhs;
|
|
2454
|
+
this.test = test;
|
|
2455
|
+
}
|
|
2456
|
+
type = "SelectExpression";
|
|
2457
|
+
};
|
|
2458
|
+
var TestExpression = class extends Expression {
|
|
2459
|
+
constructor(operand, negate, test) {
|
|
2460
|
+
super();
|
|
2461
|
+
this.operand = operand;
|
|
2462
|
+
this.negate = negate;
|
|
2463
|
+
this.test = test;
|
|
2464
|
+
}
|
|
2465
|
+
type = "TestExpression";
|
|
2466
|
+
};
|
|
2467
|
+
var UnaryExpression = class extends Expression {
|
|
2468
|
+
constructor(operator, argument) {
|
|
2469
|
+
super();
|
|
2470
|
+
this.operator = operator;
|
|
2471
|
+
this.argument = argument;
|
|
2472
|
+
}
|
|
2473
|
+
type = "UnaryExpression";
|
|
2474
|
+
};
|
|
2475
|
+
var SliceExpression = class extends Expression {
|
|
2476
|
+
constructor(start = void 0, stop = void 0, step = void 0) {
|
|
2477
|
+
super();
|
|
2478
|
+
this.start = start;
|
|
2479
|
+
this.stop = stop;
|
|
2480
|
+
this.step = step;
|
|
2481
|
+
}
|
|
2482
|
+
type = "SliceExpression";
|
|
2483
|
+
};
|
|
2484
|
+
var KeywordArgumentExpression = class extends Expression {
|
|
2485
|
+
constructor(key, value) {
|
|
2486
|
+
super();
|
|
2487
|
+
this.key = key;
|
|
2488
|
+
this.value = value;
|
|
2489
|
+
}
|
|
2490
|
+
type = "KeywordArgumentExpression";
|
|
2491
|
+
};
|
|
2492
|
+
var SpreadExpression = class extends Expression {
|
|
2493
|
+
constructor(argument) {
|
|
2494
|
+
super();
|
|
2495
|
+
this.argument = argument;
|
|
2496
|
+
}
|
|
2497
|
+
type = "SpreadExpression";
|
|
2498
|
+
};
|
|
2499
|
+
var CallStatement = class extends Statement {
|
|
2500
|
+
constructor(call, callerArgs, body) {
|
|
2501
|
+
super();
|
|
2502
|
+
this.call = call;
|
|
2503
|
+
this.callerArgs = callerArgs;
|
|
2504
|
+
this.body = body;
|
|
2505
|
+
}
|
|
2506
|
+
type = "CallStatement";
|
|
2507
|
+
};
|
|
2508
|
+
var Ternary = class extends Expression {
|
|
2509
|
+
constructor(condition, trueExpr, falseExpr) {
|
|
2510
|
+
super();
|
|
2511
|
+
this.condition = condition;
|
|
2512
|
+
this.trueExpr = trueExpr;
|
|
2513
|
+
this.falseExpr = falseExpr;
|
|
2514
|
+
}
|
|
2515
|
+
type = "Ternary";
|
|
2516
|
+
};
|
|
2517
|
+
function parse(tokens) {
|
|
2518
|
+
const program = new Program([]);
|
|
2519
|
+
let current = 0;
|
|
2520
|
+
function expect(type, error) {
|
|
2521
|
+
const prev = tokens[current++];
|
|
2522
|
+
if (!prev || prev.type !== type) throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);
|
|
2523
|
+
return prev;
|
|
2524
|
+
}
|
|
2525
|
+
function expectIdentifier(name) {
|
|
2526
|
+
if (!isIdentifier(name)) throw new SyntaxError(`Expected ${name}`);
|
|
2527
|
+
++current;
|
|
2528
|
+
}
|
|
2529
|
+
function parseAny() {
|
|
2530
|
+
switch (tokens[current].type) {
|
|
2531
|
+
case TOKEN_TYPES.Comment: return new Comment(tokens[current++].value);
|
|
2532
|
+
case TOKEN_TYPES.Text: return parseText();
|
|
2533
|
+
case TOKEN_TYPES.OpenStatement: return parseJinjaStatement();
|
|
2534
|
+
case TOKEN_TYPES.OpenExpression: return parseJinjaExpression();
|
|
2535
|
+
default: throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
function is(...types) {
|
|
2539
|
+
return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);
|
|
2540
|
+
}
|
|
2541
|
+
function isStatement(...names) {
|
|
2542
|
+
return tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.Identifier && names.includes(tokens[current + 1]?.value);
|
|
2543
|
+
}
|
|
2544
|
+
function isIdentifier(...names) {
|
|
2545
|
+
return current + names.length <= tokens.length && names.every((name, i) => tokens[current + i].type === "Identifier" && name === tokens[current + i].value);
|
|
2546
|
+
}
|
|
2547
|
+
function parseText() {
|
|
2548
|
+
return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value);
|
|
2549
|
+
}
|
|
2550
|
+
function parseJinjaStatement() {
|
|
2551
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token");
|
|
2552
|
+
if (tokens[current].type !== TOKEN_TYPES.Identifier) throw new SyntaxError(`Unknown statement, got ${tokens[current].type}`);
|
|
2553
|
+
const name = tokens[current].value;
|
|
2554
|
+
let result;
|
|
2555
|
+
switch (name) {
|
|
2556
|
+
case "set":
|
|
2557
|
+
++current;
|
|
2558
|
+
result = parseSetStatement();
|
|
2559
|
+
break;
|
|
2560
|
+
case "if":
|
|
2561
|
+
++current;
|
|
2562
|
+
result = parseIfStatement();
|
|
2563
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
|
|
2564
|
+
expectIdentifier("endif");
|
|
2565
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
|
|
2566
|
+
break;
|
|
2567
|
+
case "macro":
|
|
2568
|
+
++current;
|
|
2569
|
+
result = parseMacroStatement();
|
|
2570
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
|
|
2571
|
+
expectIdentifier("endmacro");
|
|
2572
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
|
|
2573
|
+
break;
|
|
2574
|
+
case "for":
|
|
2575
|
+
++current;
|
|
2576
|
+
result = parseForStatement();
|
|
2577
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
|
|
2578
|
+
expectIdentifier("endfor");
|
|
2579
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
|
|
2580
|
+
break;
|
|
2581
|
+
case "call": {
|
|
2582
|
+
++current;
|
|
2583
|
+
let callerArgs = null;
|
|
2584
|
+
if (is(TOKEN_TYPES.OpenParen)) callerArgs = parseArgs();
|
|
2585
|
+
const callee = parsePrimaryExpression();
|
|
2586
|
+
if (callee.type !== "Identifier") throw new SyntaxError(`Expected identifier following call statement`);
|
|
2587
|
+
const callArgs = parseArgs();
|
|
2588
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2589
|
+
const body = [];
|
|
2590
|
+
while (!isStatement("endcall")) body.push(parseAny());
|
|
2591
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected '{%'");
|
|
2592
|
+
expectIdentifier("endcall");
|
|
2593
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2594
|
+
result = new CallStatement(new CallExpression(callee, callArgs), callerArgs, body);
|
|
2595
|
+
break;
|
|
2596
|
+
}
|
|
2597
|
+
case "break":
|
|
2598
|
+
++current;
|
|
2599
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2600
|
+
result = new Break();
|
|
2601
|
+
break;
|
|
2602
|
+
case "continue":
|
|
2603
|
+
++current;
|
|
2604
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2605
|
+
result = new Continue();
|
|
2606
|
+
break;
|
|
2607
|
+
case "filter": {
|
|
2608
|
+
++current;
|
|
2609
|
+
let filterNode = parsePrimaryExpression();
|
|
2610
|
+
if (filterNode instanceof Identifier && is(TOKEN_TYPES.OpenParen)) filterNode = parseCallExpression(filterNode);
|
|
2611
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2612
|
+
const filterBody = [];
|
|
2613
|
+
while (!isStatement("endfilter")) filterBody.push(parseAny());
|
|
2614
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected '{%'");
|
|
2615
|
+
expectIdentifier("endfilter");
|
|
2616
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected '%}'");
|
|
2617
|
+
result = new FilterStatement(filterNode, filterBody);
|
|
2618
|
+
break;
|
|
2619
|
+
}
|
|
2620
|
+
default: throw new SyntaxError(`Unknown statement type: ${name}`);
|
|
2621
|
+
}
|
|
2622
|
+
return result;
|
|
2623
|
+
}
|
|
2624
|
+
function parseJinjaExpression() {
|
|
2625
|
+
expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token");
|
|
2626
|
+
const result = parseExpression();
|
|
2627
|
+
expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token");
|
|
2628
|
+
return result;
|
|
2629
|
+
}
|
|
2630
|
+
function parseSetStatement() {
|
|
2631
|
+
const left = parseExpressionSequence();
|
|
2632
|
+
let value = null;
|
|
2633
|
+
const body = [];
|
|
2634
|
+
if (is(TOKEN_TYPES.Equals)) {
|
|
2635
|
+
++current;
|
|
2636
|
+
value = parseExpressionSequence();
|
|
2637
|
+
} else {
|
|
2638
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
|
|
2639
|
+
while (!isStatement("endset")) body.push(parseAny());
|
|
2640
|
+
expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
|
|
2641
|
+
expectIdentifier("endset");
|
|
2642
|
+
}
|
|
2643
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2644
|
+
return new SetStatement(left, value, body);
|
|
2645
|
+
}
|
|
2646
|
+
function parseIfStatement() {
|
|
2647
|
+
const test = parseExpression();
|
|
2648
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2649
|
+
const body = [];
|
|
2650
|
+
const alternate = [];
|
|
2651
|
+
while (!isStatement("elif", "else", "endif")) body.push(parseAny());
|
|
2652
|
+
if (isStatement("elif")) {
|
|
2653
|
+
++current;
|
|
2654
|
+
++current;
|
|
2655
|
+
const result = parseIfStatement();
|
|
2656
|
+
alternate.push(result);
|
|
2657
|
+
} else if (isStatement("else")) {
|
|
2658
|
+
++current;
|
|
2659
|
+
++current;
|
|
2660
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2661
|
+
while (!isStatement("endif")) alternate.push(parseAny());
|
|
2662
|
+
}
|
|
2663
|
+
return new If(test, body, alternate);
|
|
2664
|
+
}
|
|
2665
|
+
function parseMacroStatement() {
|
|
2666
|
+
const name = parsePrimaryExpression();
|
|
2667
|
+
if (name.type !== "Identifier") throw new SyntaxError(`Expected identifier following macro statement`);
|
|
2668
|
+
const args = parseArgs();
|
|
2669
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2670
|
+
const body = [];
|
|
2671
|
+
while (!isStatement("endmacro")) body.push(parseAny());
|
|
2672
|
+
return new Macro(name, args, body);
|
|
2673
|
+
}
|
|
2674
|
+
function parseExpressionSequence(primary = false) {
|
|
2675
|
+
const fn = primary ? parsePrimaryExpression : parseExpression;
|
|
2676
|
+
const expressions = [fn()];
|
|
2677
|
+
const isTuple = is(TOKEN_TYPES.Comma);
|
|
2678
|
+
while (isTuple) {
|
|
2679
|
+
++current;
|
|
2680
|
+
expressions.push(fn());
|
|
2681
|
+
if (!is(TOKEN_TYPES.Comma)) break;
|
|
2682
|
+
}
|
|
2683
|
+
return isTuple ? new TupleLiteral(expressions) : expressions[0];
|
|
2684
|
+
}
|
|
2685
|
+
function parseForStatement() {
|
|
2686
|
+
const loopVariable = parseExpressionSequence(true);
|
|
2687
|
+
if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);
|
|
2688
|
+
if (!isIdentifier("in")) throw new SyntaxError("Expected `in` keyword following loop variable");
|
|
2689
|
+
++current;
|
|
2690
|
+
const iterable = parseExpression();
|
|
2691
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2692
|
+
const body = [];
|
|
2693
|
+
while (!isStatement("endfor", "else")) body.push(parseAny());
|
|
2694
|
+
const alternative = [];
|
|
2695
|
+
if (isStatement("else")) {
|
|
2696
|
+
++current;
|
|
2697
|
+
++current;
|
|
2698
|
+
expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
|
|
2699
|
+
while (!isStatement("endfor")) alternative.push(parseAny());
|
|
2700
|
+
}
|
|
2701
|
+
return new For(loopVariable, iterable, body, alternative);
|
|
2702
|
+
}
|
|
2703
|
+
function parseExpression() {
|
|
2704
|
+
return parseIfExpression();
|
|
2705
|
+
}
|
|
2706
|
+
function parseIfExpression() {
|
|
2707
|
+
const a = parseLogicalOrExpression();
|
|
2708
|
+
if (isIdentifier("if")) {
|
|
2709
|
+
++current;
|
|
2710
|
+
const test = parseLogicalOrExpression();
|
|
2711
|
+
if (isIdentifier("else")) {
|
|
2712
|
+
++current;
|
|
2713
|
+
return new Ternary(test, a, parseIfExpression());
|
|
2714
|
+
} else return new SelectExpression(a, test);
|
|
2715
|
+
}
|
|
2716
|
+
return a;
|
|
2717
|
+
}
|
|
2718
|
+
function parseLogicalOrExpression() {
|
|
2719
|
+
let left = parseLogicalAndExpression();
|
|
2720
|
+
while (isIdentifier("or")) {
|
|
2721
|
+
const operator = tokens[current];
|
|
2722
|
+
++current;
|
|
2723
|
+
const right = parseLogicalAndExpression();
|
|
2724
|
+
left = new BinaryExpression(operator, left, right);
|
|
2725
|
+
}
|
|
2726
|
+
return left;
|
|
2727
|
+
}
|
|
2728
|
+
function parseLogicalAndExpression() {
|
|
2729
|
+
let left = parseLogicalNegationExpression();
|
|
2730
|
+
while (isIdentifier("and")) {
|
|
2731
|
+
const operator = tokens[current];
|
|
2732
|
+
++current;
|
|
2733
|
+
const right = parseLogicalNegationExpression();
|
|
2734
|
+
left = new BinaryExpression(operator, left, right);
|
|
2735
|
+
}
|
|
2736
|
+
return left;
|
|
2737
|
+
}
|
|
2738
|
+
function parseLogicalNegationExpression() {
|
|
2739
|
+
let right;
|
|
2740
|
+
while (isIdentifier("not")) {
|
|
2741
|
+
const operator = tokens[current];
|
|
2742
|
+
++current;
|
|
2743
|
+
right = new UnaryExpression(operator, parseLogicalNegationExpression());
|
|
2744
|
+
}
|
|
2745
|
+
return right ?? parseComparisonExpression();
|
|
2746
|
+
}
|
|
2747
|
+
function parseComparisonExpression() {
|
|
2748
|
+
let left = parseAdditiveExpression();
|
|
2749
|
+
while (true) {
|
|
2750
|
+
let operator;
|
|
2751
|
+
if (isIdentifier("not", "in")) {
|
|
2752
|
+
operator = new Token("not in", TOKEN_TYPES.Identifier);
|
|
2753
|
+
current += 2;
|
|
2754
|
+
} else if (isIdentifier("in")) operator = tokens[current++];
|
|
2755
|
+
else if (is(TOKEN_TYPES.ComparisonBinaryOperator)) operator = tokens[current++];
|
|
2756
|
+
else break;
|
|
2757
|
+
const right = parseAdditiveExpression();
|
|
2758
|
+
left = new BinaryExpression(operator, left, right);
|
|
2759
|
+
}
|
|
2760
|
+
return left;
|
|
2761
|
+
}
|
|
2762
|
+
function parseAdditiveExpression() {
|
|
2763
|
+
let left = parseMultiplicativeExpression();
|
|
2764
|
+
while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {
|
|
2765
|
+
const operator = tokens[current];
|
|
2766
|
+
++current;
|
|
2767
|
+
const right = parseMultiplicativeExpression();
|
|
2768
|
+
left = new BinaryExpression(operator, left, right);
|
|
2769
|
+
}
|
|
2770
|
+
return left;
|
|
2771
|
+
}
|
|
2772
|
+
function parseCallMemberExpression() {
|
|
2773
|
+
const member = parseMemberExpression(parsePrimaryExpression());
|
|
2774
|
+
if (is(TOKEN_TYPES.OpenParen)) return parseCallExpression(member);
|
|
2775
|
+
return member;
|
|
2776
|
+
}
|
|
2777
|
+
function parseCallExpression(callee) {
|
|
2778
|
+
let expression = new CallExpression(callee, parseArgs());
|
|
2779
|
+
expression = parseMemberExpression(expression);
|
|
2780
|
+
if (is(TOKEN_TYPES.OpenParen)) expression = parseCallExpression(expression);
|
|
2781
|
+
return expression;
|
|
2782
|
+
}
|
|
2783
|
+
function parseArgs() {
|
|
2784
|
+
expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list");
|
|
2785
|
+
const args = parseArgumentsList();
|
|
2786
|
+
expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list");
|
|
2787
|
+
return args;
|
|
2788
|
+
}
|
|
2789
|
+
function parseArgumentsList() {
|
|
2790
|
+
const args = [];
|
|
2791
|
+
while (!is(TOKEN_TYPES.CloseParen)) {
|
|
2792
|
+
let argument;
|
|
2793
|
+
if (tokens[current].type === TOKEN_TYPES.MultiplicativeBinaryOperator && tokens[current].value === "*") {
|
|
2794
|
+
++current;
|
|
2795
|
+
argument = new SpreadExpression(parseExpression());
|
|
2796
|
+
} else {
|
|
2797
|
+
argument = parseExpression();
|
|
2798
|
+
if (is(TOKEN_TYPES.Equals)) {
|
|
2799
|
+
++current;
|
|
2800
|
+
if (!(argument instanceof Identifier)) throw new SyntaxError(`Expected identifier for keyword argument`);
|
|
2801
|
+
const value = parseExpression();
|
|
2802
|
+
argument = new KeywordArgumentExpression(argument, value);
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
args.push(argument);
|
|
2806
|
+
if (is(TOKEN_TYPES.Comma)) ++current;
|
|
2807
|
+
}
|
|
2808
|
+
return args;
|
|
2809
|
+
}
|
|
2810
|
+
function parseMemberExpressionArgumentsList() {
|
|
2811
|
+
const slices = [];
|
|
2812
|
+
let isSlice = false;
|
|
2813
|
+
while (!is(TOKEN_TYPES.CloseSquareBracket)) if (is(TOKEN_TYPES.Colon)) {
|
|
2814
|
+
slices.push(void 0);
|
|
2815
|
+
++current;
|
|
2816
|
+
isSlice = true;
|
|
2817
|
+
} else {
|
|
2818
|
+
slices.push(parseExpression());
|
|
2819
|
+
if (is(TOKEN_TYPES.Colon)) {
|
|
2820
|
+
++current;
|
|
2821
|
+
isSlice = true;
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
if (slices.length === 0) throw new SyntaxError(`Expected at least one argument for member/slice expression`);
|
|
2825
|
+
if (isSlice) {
|
|
2826
|
+
if (slices.length > 3) throw new SyntaxError(`Expected 0-3 arguments for slice expression`);
|
|
2827
|
+
return new SliceExpression(...slices);
|
|
2828
|
+
}
|
|
2829
|
+
return slices[0];
|
|
2830
|
+
}
|
|
2831
|
+
function parseMemberExpression(object) {
|
|
2832
|
+
while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {
|
|
2833
|
+
const operator = tokens[current];
|
|
2834
|
+
++current;
|
|
2835
|
+
let property;
|
|
2836
|
+
const computed = operator.type === TOKEN_TYPES.OpenSquareBracket;
|
|
2837
|
+
if (computed) {
|
|
2838
|
+
property = parseMemberExpressionArgumentsList();
|
|
2839
|
+
expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket");
|
|
2840
|
+
} else {
|
|
2841
|
+
property = parsePrimaryExpression();
|
|
2842
|
+
if (property.type !== "Identifier" && property.type !== "IntegerLiteral") throw new SyntaxError(`Expected identifier or integer following dot operator`);
|
|
2843
|
+
}
|
|
2844
|
+
object = new MemberExpression(object, property, computed);
|
|
2845
|
+
}
|
|
2846
|
+
return object;
|
|
2847
|
+
}
|
|
2848
|
+
function parseMultiplicativeExpression() {
|
|
2849
|
+
let left = parseTestExpression();
|
|
2850
|
+
while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {
|
|
2851
|
+
const operator = tokens[current++];
|
|
2852
|
+
const right = parseTestExpression();
|
|
2853
|
+
left = new BinaryExpression(operator, left, right);
|
|
2854
|
+
}
|
|
2855
|
+
return left;
|
|
2856
|
+
}
|
|
2857
|
+
function parseTestExpression() {
|
|
2858
|
+
let operand = parseFilterExpression();
|
|
2859
|
+
while (isIdentifier("is")) {
|
|
2860
|
+
++current;
|
|
2861
|
+
const negate = isIdentifier("not");
|
|
2862
|
+
if (negate) ++current;
|
|
2863
|
+
const filter = parsePrimaryExpression();
|
|
2864
|
+
if (!(filter instanceof Identifier)) throw new SyntaxError(`Expected identifier for the test`);
|
|
2865
|
+
operand = new TestExpression(operand, negate, filter);
|
|
2866
|
+
}
|
|
2867
|
+
return operand;
|
|
2868
|
+
}
|
|
2869
|
+
function parseFilterExpression() {
|
|
2870
|
+
let operand = parseCallMemberExpression();
|
|
2871
|
+
while (is(TOKEN_TYPES.Pipe)) {
|
|
2872
|
+
++current;
|
|
2873
|
+
let filter = parsePrimaryExpression();
|
|
2874
|
+
if (!(filter instanceof Identifier)) throw new SyntaxError(`Expected identifier for the filter`);
|
|
2875
|
+
if (is(TOKEN_TYPES.OpenParen)) filter = parseCallExpression(filter);
|
|
2876
|
+
operand = new FilterExpression(operand, filter);
|
|
2877
|
+
}
|
|
2878
|
+
return operand;
|
|
2879
|
+
}
|
|
2880
|
+
function parsePrimaryExpression() {
|
|
2881
|
+
const token = tokens[current++];
|
|
2882
|
+
switch (token.type) {
|
|
2883
|
+
case TOKEN_TYPES.NumericLiteral: {
|
|
2884
|
+
const num = token.value;
|
|
2885
|
+
return num.includes(".") ? new FloatLiteral(Number(num)) : new IntegerLiteral(Number(num));
|
|
2886
|
+
}
|
|
2887
|
+
case TOKEN_TYPES.StringLiteral: {
|
|
2888
|
+
let value = token.value;
|
|
2889
|
+
while (is(TOKEN_TYPES.StringLiteral)) value += tokens[current++].value;
|
|
2890
|
+
return new StringLiteral(value);
|
|
2891
|
+
}
|
|
2892
|
+
case TOKEN_TYPES.Identifier: return new Identifier(token.value);
|
|
2893
|
+
case TOKEN_TYPES.OpenParen: {
|
|
2894
|
+
const expression = parseExpressionSequence();
|
|
2895
|
+
expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis, got ${tokens[current].type} instead.");
|
|
2896
|
+
return expression;
|
|
2897
|
+
}
|
|
2898
|
+
case TOKEN_TYPES.OpenSquareBracket: {
|
|
2899
|
+
const values = [];
|
|
2900
|
+
while (!is(TOKEN_TYPES.CloseSquareBracket)) {
|
|
2901
|
+
values.push(parseExpression());
|
|
2902
|
+
if (is(TOKEN_TYPES.Comma)) ++current;
|
|
2903
|
+
}
|
|
2904
|
+
++current;
|
|
2905
|
+
return new ArrayLiteral(values);
|
|
2906
|
+
}
|
|
2907
|
+
case TOKEN_TYPES.OpenCurlyBracket: {
|
|
2908
|
+
const values = /* @__PURE__ */ new Map();
|
|
2909
|
+
while (!is(TOKEN_TYPES.CloseCurlyBracket)) {
|
|
2910
|
+
const key = parseExpression();
|
|
2911
|
+
expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal");
|
|
2912
|
+
const value = parseExpression();
|
|
2913
|
+
values.set(key, value);
|
|
2914
|
+
if (is(TOKEN_TYPES.Comma)) ++current;
|
|
2915
|
+
}
|
|
2916
|
+
++current;
|
|
2917
|
+
return new ObjectLiteral(values);
|
|
2918
|
+
}
|
|
2919
|
+
default: throw new SyntaxError(`Unexpected token: ${token.type}`);
|
|
2920
|
+
}
|
|
2921
|
+
}
|
|
2922
|
+
while (current < tokens.length) program.body.push(parseAny());
|
|
2923
|
+
return program;
|
|
2924
|
+
}
|
|
2925
|
+
function range(start, stop, step = 1) {
|
|
2926
|
+
if (stop === void 0) {
|
|
2927
|
+
stop = start;
|
|
2928
|
+
start = 0;
|
|
2929
|
+
}
|
|
2930
|
+
if (step === 0) throw new Error("range() step must not be zero");
|
|
2931
|
+
const result = [];
|
|
2932
|
+
if (step > 0) for (let i = start; i < stop; i += step) result.push(i);
|
|
2933
|
+
else for (let i = start; i > stop; i += step) result.push(i);
|
|
2934
|
+
return result;
|
|
2935
|
+
}
|
|
2936
|
+
function slice(array, start, stop, step = 1) {
|
|
2937
|
+
const direction = Math.sign(step);
|
|
2938
|
+
if (direction >= 0) {
|
|
2939
|
+
start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);
|
|
2940
|
+
stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);
|
|
2941
|
+
} else {
|
|
2942
|
+
start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);
|
|
2943
|
+
stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);
|
|
2944
|
+
}
|
|
2945
|
+
const result = [];
|
|
2946
|
+
for (let i = start; direction * i < direction * stop; i += step) result.push(array[i]);
|
|
2947
|
+
return result;
|
|
2948
|
+
}
|
|
2949
|
+
function titleCase(value) {
|
|
2950
|
+
return value.replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2951
|
+
}
|
|
2952
|
+
function strftime_now(format2) {
|
|
2953
|
+
return strftime(/* @__PURE__ */ new Date(), format2);
|
|
2954
|
+
}
|
|
2955
|
+
function strftime(date, format2) {
|
|
2956
|
+
const monthFormatterLong = new Intl.DateTimeFormat(void 0, { month: "long" });
|
|
2957
|
+
const monthFormatterShort = new Intl.DateTimeFormat(void 0, { month: "short" });
|
|
2958
|
+
const pad2 = (n) => n < 10 ? "0" + n : n.toString();
|
|
2959
|
+
return format2.replace(/%[YmdbBHM%]/g, (token) => {
|
|
2960
|
+
switch (token) {
|
|
2961
|
+
case "%Y": return date.getFullYear().toString();
|
|
2962
|
+
case "%m": return pad2(date.getMonth() + 1);
|
|
2963
|
+
case "%d": return pad2(date.getDate());
|
|
2964
|
+
case "%b": return monthFormatterShort.format(date);
|
|
2965
|
+
case "%B": return monthFormatterLong.format(date);
|
|
2966
|
+
case "%H": return pad2(date.getHours());
|
|
2967
|
+
case "%M": return pad2(date.getMinutes());
|
|
2968
|
+
case "%%": return "%";
|
|
2969
|
+
default: return token;
|
|
2970
|
+
}
|
|
2971
|
+
});
|
|
2972
|
+
}
|
|
2973
|
+
function escapeRegExp(s) {
|
|
2974
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2975
|
+
}
|
|
2976
|
+
function replace(str, oldvalue, newvalue, count) {
|
|
2977
|
+
if (count === 0) return str;
|
|
2978
|
+
let remaining = count == null || count < 0 ? Infinity : count;
|
|
2979
|
+
const pattern = oldvalue.length === 0 ? /* @__PURE__ */ new RegExp("(?=)", "gu") : new RegExp(escapeRegExp(oldvalue), "gu");
|
|
2980
|
+
return str.replaceAll(pattern, (match) => {
|
|
2981
|
+
if (remaining > 0) {
|
|
2982
|
+
--remaining;
|
|
2983
|
+
return newvalue;
|
|
2984
|
+
}
|
|
2985
|
+
return match;
|
|
2986
|
+
});
|
|
2987
|
+
}
|
|
2988
|
+
var BreakControl = class extends Error {};
|
|
2989
|
+
var ContinueControl = class extends Error {};
|
|
2990
|
+
var EMPTY_BUILTINS = /* @__PURE__ */ new Map();
|
|
2991
|
+
var RuntimeValue = class {
|
|
2992
|
+
type = "RuntimeValue";
|
|
2993
|
+
value;
|
|
2994
|
+
/**
|
|
2995
|
+
* A collection of built-in functions for this type.
|
|
2996
|
+
*/
|
|
2997
|
+
get builtins() {
|
|
2998
|
+
return EMPTY_BUILTINS;
|
|
2999
|
+
}
|
|
3000
|
+
/**
|
|
3001
|
+
* Creates a new RuntimeValue.
|
|
3002
|
+
*/
|
|
3003
|
+
constructor(value = void 0) {
|
|
3004
|
+
this.value = value;
|
|
3005
|
+
}
|
|
3006
|
+
/**
|
|
3007
|
+
* Determines truthiness or falsiness of the runtime value.
|
|
3008
|
+
* This function should be overridden by subclasses if it has custom truthiness criteria.
|
|
3009
|
+
* @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.
|
|
3010
|
+
*/
|
|
3011
|
+
__bool__() {
|
|
3012
|
+
return new BooleanValue(!!this.value);
|
|
3013
|
+
}
|
|
3014
|
+
toString() {
|
|
3015
|
+
return String(this.value);
|
|
3016
|
+
}
|
|
3017
|
+
};
|
|
3018
|
+
var IntegerValue = class extends RuntimeValue {
|
|
3019
|
+
type = "IntegerValue";
|
|
3020
|
+
};
|
|
3021
|
+
var FloatValue = class extends RuntimeValue {
|
|
3022
|
+
type = "FloatValue";
|
|
3023
|
+
toString() {
|
|
3024
|
+
return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString();
|
|
3025
|
+
}
|
|
3026
|
+
};
|
|
3027
|
+
var StringValue = class extends RuntimeValue {
|
|
3028
|
+
type = "StringValue";
|
|
3029
|
+
_builtins;
|
|
3030
|
+
get builtins() {
|
|
3031
|
+
return this._builtins ??= /* @__PURE__ */ new Map([
|
|
3032
|
+
["upper", new FunctionValue(() => {
|
|
3033
|
+
return new StringValue(this.value.toUpperCase());
|
|
3034
|
+
})],
|
|
3035
|
+
["lower", new FunctionValue(() => {
|
|
3036
|
+
return new StringValue(this.value.toLowerCase());
|
|
3037
|
+
})],
|
|
3038
|
+
["strip", new FunctionValue(() => {
|
|
3039
|
+
return new StringValue(this.value.trim());
|
|
3040
|
+
})],
|
|
3041
|
+
["title", new FunctionValue(() => {
|
|
3042
|
+
return new StringValue(titleCase(this.value));
|
|
3043
|
+
})],
|
|
3044
|
+
["capitalize", new FunctionValue(() => {
|
|
3045
|
+
return new StringValue(this.value.charAt(0).toUpperCase() + this.value.slice(1));
|
|
3046
|
+
})],
|
|
3047
|
+
["length", new IntegerValue(this.value.length)],
|
|
3048
|
+
["rstrip", new FunctionValue(() => {
|
|
3049
|
+
return new StringValue(this.value.trimEnd());
|
|
3050
|
+
})],
|
|
3051
|
+
["lstrip", new FunctionValue(() => {
|
|
3052
|
+
return new StringValue(this.value.trimStart());
|
|
3053
|
+
})],
|
|
3054
|
+
["startswith", new FunctionValue((args) => {
|
|
3055
|
+
if (args.length === 0) throw new Error("startswith() requires at least one argument");
|
|
3056
|
+
const pattern = args[0];
|
|
3057
|
+
if (pattern instanceof StringValue) return new BooleanValue(this.value.startsWith(pattern.value));
|
|
3058
|
+
else if (pattern instanceof ArrayValue) {
|
|
3059
|
+
for (const item of pattern.value) {
|
|
3060
|
+
if (!(item instanceof StringValue)) throw new Error("startswith() tuple elements must be strings");
|
|
3061
|
+
if (this.value.startsWith(item.value)) return new BooleanValue(true);
|
|
3062
|
+
}
|
|
3063
|
+
return new BooleanValue(false);
|
|
3064
|
+
}
|
|
3065
|
+
throw new Error("startswith() argument must be a string or tuple of strings");
|
|
3066
|
+
})],
|
|
3067
|
+
["endswith", new FunctionValue((args) => {
|
|
3068
|
+
if (args.length === 0) throw new Error("endswith() requires at least one argument");
|
|
3069
|
+
const pattern = args[0];
|
|
3070
|
+
if (pattern instanceof StringValue) return new BooleanValue(this.value.endsWith(pattern.value));
|
|
3071
|
+
else if (pattern instanceof ArrayValue) {
|
|
3072
|
+
for (const item of pattern.value) {
|
|
3073
|
+
if (!(item instanceof StringValue)) throw new Error("endswith() tuple elements must be strings");
|
|
3074
|
+
if (this.value.endsWith(item.value)) return new BooleanValue(true);
|
|
3075
|
+
}
|
|
3076
|
+
return new BooleanValue(false);
|
|
3077
|
+
}
|
|
3078
|
+
throw new Error("endswith() argument must be a string or tuple of strings");
|
|
3079
|
+
})],
|
|
3080
|
+
["split", new FunctionValue((args) => {
|
|
3081
|
+
const sep = args[0] ?? new NullValue();
|
|
3082
|
+
if (!(sep instanceof StringValue || sep instanceof NullValue)) throw new Error("sep argument must be a string or null");
|
|
3083
|
+
const maxsplit = args[1] ?? new IntegerValue(-1);
|
|
3084
|
+
if (!(maxsplit instanceof IntegerValue)) throw new Error("maxsplit argument must be a number");
|
|
3085
|
+
let result = [];
|
|
3086
|
+
if (sep instanceof NullValue) {
|
|
3087
|
+
const text = this.value.trimStart();
|
|
3088
|
+
for (const { 0: match, index } of text.matchAll(/\S+/g)) {
|
|
3089
|
+
if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) {
|
|
3090
|
+
result.push(match + text.slice(index + match.length));
|
|
3091
|
+
break;
|
|
3092
|
+
}
|
|
3093
|
+
result.push(match);
|
|
3094
|
+
}
|
|
3095
|
+
} else {
|
|
3096
|
+
if (sep.value === "") throw new Error("empty separator");
|
|
3097
|
+
result = this.value.split(sep.value);
|
|
3098
|
+
if (maxsplit.value !== -1 && result.length > maxsplit.value) result.push(result.splice(maxsplit.value).join(sep.value));
|
|
3099
|
+
}
|
|
3100
|
+
return new ArrayValue(result.map((part) => new StringValue(part)));
|
|
3101
|
+
})],
|
|
3102
|
+
["replace", new FunctionValue((args) => {
|
|
3103
|
+
if (args.length < 2) throw new Error("replace() requires at least two arguments");
|
|
3104
|
+
const oldValue = args[0];
|
|
3105
|
+
const newValue = args[1];
|
|
3106
|
+
if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) throw new Error("replace() arguments must be strings");
|
|
3107
|
+
let count;
|
|
3108
|
+
if (args.length > 2) if (args[2].type === "KeywordArgumentsValue") count = args[2].value.get("count") ?? new NullValue();
|
|
3109
|
+
else count = args[2];
|
|
3110
|
+
else count = new NullValue();
|
|
3111
|
+
if (!(count instanceof IntegerValue || count instanceof NullValue)) throw new Error("replace() count argument must be a number or null");
|
|
3112
|
+
return new StringValue(replace(this.value, oldValue.value, newValue.value, count.value));
|
|
3113
|
+
})]
|
|
3114
|
+
]);
|
|
3115
|
+
}
|
|
3116
|
+
};
|
|
3117
|
+
var BooleanValue = class extends RuntimeValue {
|
|
3118
|
+
type = "BooleanValue";
|
|
3119
|
+
};
|
|
3120
|
+
var NON_ASCII_CHARS = /[\x7f-\uffff]/g;
|
|
3121
|
+
function makeAsciiSafe(str) {
|
|
3122
|
+
return str.replace(NON_ASCII_CHARS, (char) => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0"));
|
|
3123
|
+
}
|
|
3124
|
+
function toJSON(input, options = {}, depth = 0, convertUndefinedToNull = true) {
|
|
3125
|
+
const { indent = null, ensureAscii = false, separators = null, sortKeys = false } = options;
|
|
3126
|
+
let itemSeparator;
|
|
3127
|
+
let keySeparator;
|
|
3128
|
+
if (separators) [itemSeparator, keySeparator] = separators;
|
|
3129
|
+
else if (indent) {
|
|
3130
|
+
itemSeparator = ",";
|
|
3131
|
+
keySeparator = ": ";
|
|
3132
|
+
} else {
|
|
3133
|
+
itemSeparator = ", ";
|
|
3134
|
+
keySeparator = ": ";
|
|
3135
|
+
}
|
|
3136
|
+
switch (input.type) {
|
|
3137
|
+
case "NullValue": return "null";
|
|
3138
|
+
case "UndefinedValue": return convertUndefinedToNull ? "null" : "undefined";
|
|
3139
|
+
case "IntegerValue":
|
|
3140
|
+
case "FloatValue":
|
|
3141
|
+
case "BooleanValue": return JSON.stringify(input.value);
|
|
3142
|
+
case "StringValue": {
|
|
3143
|
+
let result = JSON.stringify(input.value);
|
|
3144
|
+
if (ensureAscii) result = makeAsciiSafe(result);
|
|
3145
|
+
return result;
|
|
3146
|
+
}
|
|
3147
|
+
case "ArrayValue":
|
|
3148
|
+
case "ObjectValue": {
|
|
3149
|
+
const indentValue = indent ? " ".repeat(indent) : "";
|
|
3150
|
+
const basePadding = "\n" + indentValue.repeat(depth);
|
|
3151
|
+
const childrenPadding = basePadding + indentValue;
|
|
3152
|
+
if (input.type === "ArrayValue") {
|
|
3153
|
+
const core = input.value.map((x) => toJSON(x, options, depth + 1, convertUndefinedToNull));
|
|
3154
|
+
return indent ? `[${childrenPadding}${core.join(`${itemSeparator}${childrenPadding}`)}${basePadding}]` : `[${core.join(itemSeparator)}]`;
|
|
3155
|
+
} else {
|
|
3156
|
+
let entries = Array.from(input.value.entries());
|
|
3157
|
+
if (sortKeys) entries = entries.sort(([a], [b]) => a.localeCompare(b));
|
|
3158
|
+
const core = entries.map(([key, value]) => {
|
|
3159
|
+
let keyStr = JSON.stringify(key);
|
|
3160
|
+
if (ensureAscii) keyStr = makeAsciiSafe(keyStr);
|
|
3161
|
+
const v = `${keyStr}${keySeparator}${toJSON(value, options, depth + 1, convertUndefinedToNull)}`;
|
|
3162
|
+
return indent ? `${childrenPadding}${v}` : v;
|
|
3163
|
+
});
|
|
3164
|
+
return indent ? `{${core.join(itemSeparator)}${basePadding}}` : `{${core.join(itemSeparator)}}`;
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
default: throw new Error(`Cannot convert to JSON: ${input.type}`);
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
var ObjectValue = class extends RuntimeValue {
|
|
3171
|
+
type = "ObjectValue";
|
|
3172
|
+
_builtins;
|
|
3173
|
+
/**
|
|
3174
|
+
* NOTE: necessary to override since all JavaScript arrays are considered truthy,
|
|
3175
|
+
* while only non-empty Python arrays are consider truthy.
|
|
3176
|
+
*
|
|
3177
|
+
* e.g.,
|
|
3178
|
+
* - JavaScript: {} && 5 -> 5
|
|
3179
|
+
* - Python: {} and 5 -> {}
|
|
3180
|
+
*/
|
|
3181
|
+
__bool__() {
|
|
3182
|
+
return new BooleanValue(this.value.size > 0);
|
|
3183
|
+
}
|
|
3184
|
+
get builtins() {
|
|
3185
|
+
return this._builtins ??= /* @__PURE__ */ new Map([
|
|
3186
|
+
["get", new FunctionValue(([key, defaultValue]) => {
|
|
3187
|
+
if (!(key instanceof StringValue)) throw new Error(`Object key must be a string: got ${key.type}`);
|
|
3188
|
+
return this.value.get(key.value) ?? defaultValue ?? new NullValue();
|
|
3189
|
+
})],
|
|
3190
|
+
["items", new FunctionValue(() => this.items())],
|
|
3191
|
+
["keys", new FunctionValue(() => this.keys())],
|
|
3192
|
+
["values", new FunctionValue(() => this.values())],
|
|
3193
|
+
["dictsort", new FunctionValue((args) => {
|
|
3194
|
+
let kwargs = /* @__PURE__ */ new Map();
|
|
3195
|
+
const positionalArgs = args.filter((arg) => {
|
|
3196
|
+
if (arg instanceof KeywordArgumentsValue) {
|
|
3197
|
+
kwargs = arg.value;
|
|
3198
|
+
return false;
|
|
3199
|
+
}
|
|
3200
|
+
return true;
|
|
3201
|
+
});
|
|
3202
|
+
const caseSensitive = positionalArgs.at(0) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false);
|
|
3203
|
+
if (!(caseSensitive instanceof BooleanValue)) throw new Error("case_sensitive must be a boolean");
|
|
3204
|
+
const by = positionalArgs.at(1) ?? kwargs.get("by") ?? new StringValue("key");
|
|
3205
|
+
if (!(by instanceof StringValue)) throw new Error("by must be a string");
|
|
3206
|
+
if (!["key", "value"].includes(by.value)) throw new Error("by must be either 'key' or 'value'");
|
|
3207
|
+
const reverse = positionalArgs.at(2) ?? kwargs.get("reverse") ?? new BooleanValue(false);
|
|
3208
|
+
if (!(reverse instanceof BooleanValue)) throw new Error("reverse must be a boolean");
|
|
3209
|
+
return new ArrayValue(Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])).sort((a, b) => {
|
|
3210
|
+
const index = by.value === "key" ? 0 : 1;
|
|
3211
|
+
const aVal = a.value[index];
|
|
3212
|
+
const bVal = b.value[index];
|
|
3213
|
+
const result = compareRuntimeValues(aVal, bVal, caseSensitive.value);
|
|
3214
|
+
return reverse.value ? -result : result;
|
|
3215
|
+
}));
|
|
3216
|
+
})]
|
|
3217
|
+
]);
|
|
3218
|
+
}
|
|
3219
|
+
items() {
|
|
3220
|
+
return new ArrayValue(Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])));
|
|
3221
|
+
}
|
|
3222
|
+
keys() {
|
|
3223
|
+
return new ArrayValue(Array.from(this.value.keys()).map((key) => new StringValue(key)));
|
|
3224
|
+
}
|
|
3225
|
+
values() {
|
|
3226
|
+
return new ArrayValue(Array.from(this.value.values()));
|
|
3227
|
+
}
|
|
3228
|
+
toString() {
|
|
3229
|
+
return toJSON(this, {}, 0, false);
|
|
3230
|
+
}
|
|
3231
|
+
};
|
|
3232
|
+
var KeywordArgumentsValue = class extends ObjectValue {
|
|
3233
|
+
type = "KeywordArgumentsValue";
|
|
3234
|
+
};
|
|
3235
|
+
var ArrayValue = class extends RuntimeValue {
|
|
3236
|
+
type = "ArrayValue";
|
|
3237
|
+
_builtins;
|
|
3238
|
+
get builtins() {
|
|
3239
|
+
return this._builtins ??= /* @__PURE__ */ new Map([["length", new IntegerValue(this.value.length)]]);
|
|
3240
|
+
}
|
|
3241
|
+
/**
|
|
3242
|
+
* NOTE: necessary to override since all JavaScript arrays are considered truthy,
|
|
3243
|
+
* while only non-empty Python arrays are consider truthy.
|
|
3244
|
+
*
|
|
3245
|
+
* e.g.,
|
|
3246
|
+
* - JavaScript: [] && 5 -> 5
|
|
3247
|
+
* - Python: [] and 5 -> []
|
|
3248
|
+
*/
|
|
3249
|
+
__bool__() {
|
|
3250
|
+
return new BooleanValue(this.value.length > 0);
|
|
3251
|
+
}
|
|
3252
|
+
toString() {
|
|
3253
|
+
return toJSON(this, {}, 0, false);
|
|
3254
|
+
}
|
|
3255
|
+
};
|
|
3256
|
+
var TupleValue = class extends ArrayValue {
|
|
3257
|
+
type = "TupleValue";
|
|
3258
|
+
};
|
|
3259
|
+
var FunctionValue = class extends RuntimeValue {
|
|
3260
|
+
type = "FunctionValue";
|
|
3261
|
+
};
|
|
3262
|
+
var NullValue = class extends RuntimeValue {
|
|
3263
|
+
type = "NullValue";
|
|
3264
|
+
};
|
|
3265
|
+
var UndefinedValue = class extends RuntimeValue {
|
|
3266
|
+
type = "UndefinedValue";
|
|
3267
|
+
};
|
|
3268
|
+
var _Environment = class {
|
|
3269
|
+
constructor(parent) {
|
|
3270
|
+
this.parent = parent;
|
|
3271
|
+
}
|
|
3272
|
+
/**
|
|
3273
|
+
* The variables declared in this environment.
|
|
3274
|
+
*/
|
|
3275
|
+
variables = /* @__PURE__ */ new Map([["namespace", new FunctionValue((args) => {
|
|
3276
|
+
if (args.length === 0) return new ObjectValue(/* @__PURE__ */ new Map());
|
|
3277
|
+
if (args.length !== 1 || !(args[0] instanceof ObjectValue)) throw new Error("`namespace` expects either zero arguments or a single object argument");
|
|
3278
|
+
return args[0];
|
|
3279
|
+
})]]);
|
|
3280
|
+
tests = _Environment.TESTS;
|
|
3281
|
+
/**
|
|
3282
|
+
* Set the value of a variable in the current environment.
|
|
3283
|
+
*/
|
|
3284
|
+
set(name, value) {
|
|
3285
|
+
return this.declareVariable(name, convertToRuntimeValues(value));
|
|
3286
|
+
}
|
|
3287
|
+
declareVariable(name, value) {
|
|
3288
|
+
if (this.variables.has(name)) throw new SyntaxError(`Variable already declared: ${name}`);
|
|
3289
|
+
this.variables.set(name, value);
|
|
3290
|
+
return value;
|
|
3291
|
+
}
|
|
3292
|
+
/**
|
|
3293
|
+
* Set variable in the current scope.
|
|
3294
|
+
* See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.
|
|
3295
|
+
*/
|
|
3296
|
+
setVariable(name, value) {
|
|
3297
|
+
this.variables.set(name, value);
|
|
3298
|
+
return value;
|
|
3299
|
+
}
|
|
3300
|
+
/**
|
|
3301
|
+
* Resolve the environment in which the variable is declared.
|
|
3302
|
+
* @param {string} name The name of the variable.
|
|
3303
|
+
* @returns {Environment} The environment in which the variable is declared.
|
|
3304
|
+
*/
|
|
3305
|
+
resolve(name) {
|
|
3306
|
+
if (this.variables.has(name)) return this;
|
|
3307
|
+
if (this.parent) return this.parent.resolve(name);
|
|
3308
|
+
throw new Error(`Unknown variable: ${name}`);
|
|
3309
|
+
}
|
|
3310
|
+
lookupVariable(name) {
|
|
3311
|
+
try {
|
|
3312
|
+
return this.resolve(name).variables.get(name) ?? new UndefinedValue();
|
|
3313
|
+
} catch {
|
|
3314
|
+
return new UndefinedValue();
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
var Environment = _Environment;
|
|
3319
|
+
/**
|
|
3320
|
+
* The tests available in this environment.
|
|
3321
|
+
*/
|
|
3322
|
+
__publicField(Environment, "TESTS", /* @__PURE__ */ new Map([
|
|
3323
|
+
["boolean", (operand) => operand.type === "BooleanValue"],
|
|
3324
|
+
["callable", (operand) => operand instanceof FunctionValue],
|
|
3325
|
+
["odd", (operand) => {
|
|
3326
|
+
if (!(operand instanceof IntegerValue)) throw new Error(`cannot odd on ${operand.type}`);
|
|
3327
|
+
return operand.value % 2 !== 0;
|
|
3328
|
+
}],
|
|
3329
|
+
["even", (operand) => {
|
|
3330
|
+
if (!(operand instanceof IntegerValue)) throw new Error(`cannot even on ${operand.type}`);
|
|
3331
|
+
return operand.value % 2 === 0;
|
|
3332
|
+
}],
|
|
3333
|
+
["false", (operand) => operand.type === "BooleanValue" && !operand.value],
|
|
3334
|
+
["true", (operand) => operand.type === "BooleanValue" && operand.value],
|
|
3335
|
+
["none", (operand) => operand.type === "NullValue"],
|
|
3336
|
+
["string", (operand) => operand.type === "StringValue"],
|
|
3337
|
+
["number", (operand) => operand instanceof IntegerValue || operand instanceof FloatValue],
|
|
3338
|
+
["integer", (operand) => operand instanceof IntegerValue],
|
|
3339
|
+
["iterable", (operand) => operand.type === "ArrayValue" || operand.type === "StringValue"],
|
|
3340
|
+
["mapping", (operand) => operand instanceof ObjectValue],
|
|
3341
|
+
["sequence", (operand) => operand instanceof ArrayValue || operand instanceof ObjectValue || operand instanceof StringValue],
|
|
3342
|
+
["lower", (operand) => {
|
|
3343
|
+
const str = operand.value;
|
|
3344
|
+
return operand.type === "StringValue" && str === str.toLowerCase();
|
|
3345
|
+
}],
|
|
3346
|
+
["upper", (operand) => {
|
|
3347
|
+
const str = operand.value;
|
|
3348
|
+
return operand.type === "StringValue" && str === str.toUpperCase();
|
|
3349
|
+
}],
|
|
3350
|
+
["none", (operand) => operand.type === "NullValue"],
|
|
3351
|
+
["defined", (operand) => operand.type !== "UndefinedValue"],
|
|
3352
|
+
["undefined", (operand) => operand.type === "UndefinedValue"],
|
|
3353
|
+
["equalto", (a, b) => a.value === b.value],
|
|
3354
|
+
["eq", (a, b) => a.value === b.value]
|
|
3355
|
+
]));
|
|
3356
|
+
function setupGlobals(env) {
|
|
3357
|
+
env.set("false", false);
|
|
3358
|
+
env.set("true", true);
|
|
3359
|
+
env.set("none", null);
|
|
3360
|
+
env.set("raise_exception", (args) => {
|
|
3361
|
+
throw new Error(args);
|
|
3362
|
+
});
|
|
3363
|
+
env.set("range", range);
|
|
3364
|
+
env.set("strftime_now", strftime_now);
|
|
3365
|
+
env.set("True", true);
|
|
3366
|
+
env.set("False", false);
|
|
3367
|
+
env.set("None", null);
|
|
3368
|
+
}
|
|
3369
|
+
function getAttributeValue(item, attributePath) {
|
|
3370
|
+
const parts = attributePath.split(".");
|
|
3371
|
+
let value = item;
|
|
3372
|
+
for (const part of parts) if (value instanceof ObjectValue) value = value.value.get(part) ?? new UndefinedValue();
|
|
3373
|
+
else if (value instanceof ArrayValue) {
|
|
3374
|
+
const index = parseInt(part, 10);
|
|
3375
|
+
if (!isNaN(index) && index >= 0 && index < value.value.length) value = value.value[index];
|
|
3376
|
+
else return new UndefinedValue();
|
|
3377
|
+
} else return new UndefinedValue();
|
|
3378
|
+
return value;
|
|
3379
|
+
}
|
|
3380
|
+
function compareRuntimeValues(a, b, caseSensitive = false) {
|
|
3381
|
+
if (a instanceof NullValue && b instanceof NullValue) return 0;
|
|
3382
|
+
if (a instanceof NullValue || b instanceof NullValue) throw new Error(`Cannot compare ${a.type} with ${b.type}`);
|
|
3383
|
+
if (a instanceof UndefinedValue && b instanceof UndefinedValue) return 0;
|
|
3384
|
+
if (a instanceof UndefinedValue || b instanceof UndefinedValue) throw new Error(`Cannot compare ${a.type} with ${b.type}`);
|
|
3385
|
+
const isNumericLike = (v) => v instanceof IntegerValue || v instanceof FloatValue || v instanceof BooleanValue;
|
|
3386
|
+
const getNumericValue = (v) => {
|
|
3387
|
+
if (v instanceof BooleanValue) return v.value ? 1 : 0;
|
|
3388
|
+
return v.value;
|
|
3389
|
+
};
|
|
3390
|
+
if (isNumericLike(a) && isNumericLike(b)) {
|
|
3391
|
+
const aNum = getNumericValue(a);
|
|
3392
|
+
const bNum = getNumericValue(b);
|
|
3393
|
+
return aNum < bNum ? -1 : aNum > bNum ? 1 : 0;
|
|
3394
|
+
}
|
|
3395
|
+
if (a.type !== b.type) throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);
|
|
3396
|
+
switch (a.type) {
|
|
3397
|
+
case "StringValue": {
|
|
3398
|
+
let aStr = a.value;
|
|
3399
|
+
let bStr = b.value;
|
|
3400
|
+
if (!caseSensitive) {
|
|
3401
|
+
aStr = aStr.toLowerCase();
|
|
3402
|
+
bStr = bStr.toLowerCase();
|
|
3403
|
+
}
|
|
3404
|
+
return aStr < bStr ? -1 : aStr > bStr ? 1 : 0;
|
|
3405
|
+
}
|
|
3406
|
+
default: throw new Error(`Cannot compare type: ${a.type}`);
|
|
3407
|
+
}
|
|
3408
|
+
}
|
|
3409
|
+
var Interpreter = class {
|
|
3410
|
+
global;
|
|
3411
|
+
constructor(env) {
|
|
3412
|
+
this.global = env ?? new Environment();
|
|
3413
|
+
}
|
|
3414
|
+
/**
|
|
3415
|
+
* Run the program.
|
|
3416
|
+
*/
|
|
3417
|
+
run(program) {
|
|
3418
|
+
return this.evaluate(program, this.global);
|
|
3419
|
+
}
|
|
3420
|
+
/**
|
|
3421
|
+
* Evaluates expressions following the binary operation type.
|
|
3422
|
+
*/
|
|
3423
|
+
evaluateBinaryExpression(node, environment) {
|
|
3424
|
+
const left = this.evaluate(node.left, environment);
|
|
3425
|
+
switch (node.operator.value) {
|
|
3426
|
+
case "and": return left.__bool__().value ? this.evaluate(node.right, environment) : left;
|
|
3427
|
+
case "or": return left.__bool__().value ? left : this.evaluate(node.right, environment);
|
|
3428
|
+
}
|
|
3429
|
+
const right = this.evaluate(node.right, environment);
|
|
3430
|
+
switch (node.operator.value) {
|
|
3431
|
+
case "==": return new BooleanValue(left.value == right.value);
|
|
3432
|
+
case "!=": return new BooleanValue(left.value != right.value);
|
|
3433
|
+
}
|
|
3434
|
+
if (left instanceof UndefinedValue || right instanceof UndefinedValue) {
|
|
3435
|
+
if (right instanceof UndefinedValue && ["in", "not in"].includes(node.operator.value)) return new BooleanValue(node.operator.value === "not in");
|
|
3436
|
+
throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`);
|
|
3437
|
+
} else if (left instanceof NullValue || right instanceof NullValue) throw new Error("Cannot perform operation on null values");
|
|
3438
|
+
else if (node.operator.value === "~") return new StringValue(left.value.toString() + right.value.toString());
|
|
3439
|
+
else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) {
|
|
3440
|
+
const a = left.value, b = right.value;
|
|
3441
|
+
switch (node.operator.value) {
|
|
3442
|
+
case "+":
|
|
3443
|
+
case "-":
|
|
3444
|
+
case "*": {
|
|
3445
|
+
const res = node.operator.value === "+" ? a + b : node.operator.value === "-" ? a - b : a * b;
|
|
3446
|
+
return left instanceof FloatValue || right instanceof FloatValue ? new FloatValue(res) : new IntegerValue(res);
|
|
3447
|
+
}
|
|
3448
|
+
case "/": return new FloatValue(a / b);
|
|
3449
|
+
case "%": {
|
|
3450
|
+
const rem = a % b;
|
|
3451
|
+
return left instanceof FloatValue || right instanceof FloatValue ? new FloatValue(rem) : new IntegerValue(rem);
|
|
3452
|
+
}
|
|
3453
|
+
case "<": return new BooleanValue(a < b);
|
|
3454
|
+
case ">": return new BooleanValue(a > b);
|
|
3455
|
+
case ">=": return new BooleanValue(a >= b);
|
|
3456
|
+
case "<=": return new BooleanValue(a <= b);
|
|
3457
|
+
}
|
|
3458
|
+
} else if (left instanceof ArrayValue && right instanceof ArrayValue) switch (node.operator.value) {
|
|
3459
|
+
case "+": return new ArrayValue(left.value.concat(right.value));
|
|
3460
|
+
}
|
|
3461
|
+
else if (right instanceof ArrayValue) {
|
|
3462
|
+
const member = right.value.find((x) => x.value === left.value) !== void 0;
|
|
3463
|
+
switch (node.operator.value) {
|
|
3464
|
+
case "in": return new BooleanValue(member);
|
|
3465
|
+
case "not in": return new BooleanValue(!member);
|
|
3466
|
+
}
|
|
3467
|
+
}
|
|
3468
|
+
if (left instanceof StringValue || right instanceof StringValue) switch (node.operator.value) {
|
|
3469
|
+
case "+": return new StringValue(left.value.toString() + right.value.toString());
|
|
3470
|
+
}
|
|
3471
|
+
if (left instanceof StringValue && right instanceof StringValue) switch (node.operator.value) {
|
|
3472
|
+
case "in": return new BooleanValue(right.value.includes(left.value));
|
|
3473
|
+
case "not in": return new BooleanValue(!right.value.includes(left.value));
|
|
3474
|
+
}
|
|
3475
|
+
if (left instanceof StringValue && right instanceof ObjectValue) switch (node.operator.value) {
|
|
3476
|
+
case "in": return new BooleanValue(right.value.has(left.value));
|
|
3477
|
+
case "not in": return new BooleanValue(!right.value.has(left.value));
|
|
3478
|
+
}
|
|
3479
|
+
throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`);
|
|
3480
|
+
}
|
|
3481
|
+
evaluateArguments(args, environment) {
|
|
3482
|
+
const positionalArguments = [];
|
|
3483
|
+
const keywordArguments = /* @__PURE__ */ new Map();
|
|
3484
|
+
for (const argument of args) if (argument.type === "SpreadExpression") {
|
|
3485
|
+
const spreadNode = argument;
|
|
3486
|
+
const val = this.evaluate(spreadNode.argument, environment);
|
|
3487
|
+
if (!(val instanceof ArrayValue)) throw new Error(`Cannot unpack non-iterable type: ${val.type}`);
|
|
3488
|
+
for (const item of val.value) positionalArguments.push(item);
|
|
3489
|
+
} else if (argument.type === "KeywordArgumentExpression") {
|
|
3490
|
+
const kwarg = argument;
|
|
3491
|
+
keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));
|
|
3492
|
+
} else {
|
|
3493
|
+
if (keywordArguments.size > 0) throw new Error("Positional arguments must come before keyword arguments");
|
|
3494
|
+
positionalArguments.push(this.evaluate(argument, environment));
|
|
3495
|
+
}
|
|
3496
|
+
return [positionalArguments, keywordArguments];
|
|
3497
|
+
}
|
|
3498
|
+
applyFilter(operand, filterNode, environment) {
|
|
3499
|
+
if (filterNode.type === "Identifier") {
|
|
3500
|
+
const filter = filterNode;
|
|
3501
|
+
if (filter.value === "safe") return operand;
|
|
3502
|
+
if (filter.value === "tojson") return new StringValue(toJSON(operand, {}));
|
|
3503
|
+
if (operand instanceof ArrayValue) switch (filter.value) {
|
|
3504
|
+
case "list": return operand;
|
|
3505
|
+
case "first": return operand.value[0];
|
|
3506
|
+
case "last": return operand.value[operand.value.length - 1];
|
|
3507
|
+
case "length": return new IntegerValue(operand.value.length);
|
|
3508
|
+
case "reverse": return new ArrayValue(operand.value.slice().reverse());
|
|
3509
|
+
case "sort": return new ArrayValue(operand.value.slice().sort((a, b) => compareRuntimeValues(a, b, false)));
|
|
3510
|
+
case "join": return new StringValue(operand.value.map((x) => x.value).join(""));
|
|
3511
|
+
case "string": return new StringValue(toJSON(operand, {}, 0, false));
|
|
3512
|
+
case "unique": {
|
|
3513
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3514
|
+
const output = [];
|
|
3515
|
+
for (const item of operand.value) if (!seen.has(item.value)) {
|
|
3516
|
+
seen.add(item.value);
|
|
3517
|
+
output.push(item);
|
|
3518
|
+
}
|
|
3519
|
+
return new ArrayValue(output);
|
|
3520
|
+
}
|
|
3521
|
+
default: throw new Error(`Unknown ArrayValue filter: ${filter.value}`);
|
|
3522
|
+
}
|
|
3523
|
+
else if (operand instanceof StringValue) switch (filter.value) {
|
|
3524
|
+
case "length":
|
|
3525
|
+
case "upper":
|
|
3526
|
+
case "lower":
|
|
3527
|
+
case "title":
|
|
3528
|
+
case "capitalize": {
|
|
3529
|
+
const builtin = operand.builtins.get(filter.value);
|
|
3530
|
+
if (builtin instanceof FunctionValue) return builtin.value([], environment);
|
|
3531
|
+
else if (builtin instanceof IntegerValue) return builtin;
|
|
3532
|
+
else throw new Error(`Unknown StringValue filter: ${filter.value}`);
|
|
3533
|
+
}
|
|
3534
|
+
case "trim": return new StringValue(operand.value.trim());
|
|
3535
|
+
case "indent": return new StringValue(operand.value.split("\n").map((x, i) => i === 0 || x.length === 0 ? x : " " + x).join("\n"));
|
|
3536
|
+
case "join":
|
|
3537
|
+
case "string": return operand;
|
|
3538
|
+
case "int": {
|
|
3539
|
+
const val = parseInt(operand.value, 10);
|
|
3540
|
+
return new IntegerValue(isNaN(val) ? 0 : val);
|
|
3541
|
+
}
|
|
3542
|
+
case "float": {
|
|
3543
|
+
const val = parseFloat(operand.value);
|
|
3544
|
+
return new FloatValue(isNaN(val) ? 0 : val);
|
|
3545
|
+
}
|
|
3546
|
+
default: throw new Error(`Unknown StringValue filter: ${filter.value}`);
|
|
3547
|
+
}
|
|
3548
|
+
else if (operand instanceof IntegerValue || operand instanceof FloatValue) switch (filter.value) {
|
|
3549
|
+
case "abs": return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value));
|
|
3550
|
+
case "int": return new IntegerValue(Math.floor(operand.value));
|
|
3551
|
+
case "float": return new FloatValue(operand.value);
|
|
3552
|
+
case "string": return new StringValue(operand.toString());
|
|
3553
|
+
default: throw new Error(`Unknown NumericValue filter: ${filter.value}`);
|
|
3554
|
+
}
|
|
3555
|
+
else if (operand instanceof ObjectValue) switch (filter.value) {
|
|
3556
|
+
case "items": return new ArrayValue(Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])));
|
|
3557
|
+
case "length": return new IntegerValue(operand.value.size);
|
|
3558
|
+
default: {
|
|
3559
|
+
const builtin = operand.builtins.get(filter.value);
|
|
3560
|
+
if (builtin) {
|
|
3561
|
+
if (builtin instanceof FunctionValue) return builtin.value([], environment);
|
|
3562
|
+
return builtin;
|
|
3563
|
+
}
|
|
3564
|
+
throw new Error(`Unknown ObjectValue filter: ${filter.value}`);
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
else if (operand instanceof BooleanValue) switch (filter.value) {
|
|
3568
|
+
case "bool": return new BooleanValue(operand.value);
|
|
3569
|
+
case "int": return new IntegerValue(operand.value ? 1 : 0);
|
|
3570
|
+
case "float": return new FloatValue(operand.value ? 1 : 0);
|
|
3571
|
+
case "string": return new StringValue(operand.value ? "true" : "false");
|
|
3572
|
+
default: throw new Error(`Unknown BooleanValue filter: ${filter.value}`);
|
|
3573
|
+
}
|
|
3574
|
+
throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`);
|
|
3575
|
+
} else if (filterNode.type === "CallExpression") {
|
|
3576
|
+
const filter = filterNode;
|
|
3577
|
+
if (filter.callee.type !== "Identifier") throw new Error(`Unknown filter: ${filter.callee.type}`);
|
|
3578
|
+
const filterName = filter.callee.value;
|
|
3579
|
+
if (filterName === "tojson") {
|
|
3580
|
+
const [, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3581
|
+
const indent = kwargs.get("indent") ?? new NullValue();
|
|
3582
|
+
if (!(indent instanceof IntegerValue || indent instanceof NullValue)) throw new Error("If set, indent must be a number");
|
|
3583
|
+
const ensureAscii = kwargs.get("ensure_ascii") ?? new BooleanValue(false);
|
|
3584
|
+
if (!(ensureAscii instanceof BooleanValue)) throw new Error("If set, ensure_ascii must be a boolean");
|
|
3585
|
+
const sortKeys = kwargs.get("sort_keys") ?? new BooleanValue(false);
|
|
3586
|
+
if (!(sortKeys instanceof BooleanValue)) throw new Error("If set, sort_keys must be a boolean");
|
|
3587
|
+
const separatorsArg = kwargs.get("separators") ?? new NullValue();
|
|
3588
|
+
let separators = null;
|
|
3589
|
+
if (separatorsArg instanceof ArrayValue || separatorsArg instanceof TupleValue) {
|
|
3590
|
+
if (separatorsArg.value.length !== 2) throw new Error("separators must be a tuple of two strings");
|
|
3591
|
+
const [itemSep, keySep] = separatorsArg.value;
|
|
3592
|
+
if (!(itemSep instanceof StringValue) || !(keySep instanceof StringValue)) throw new Error("separators must be a tuple of two strings");
|
|
3593
|
+
separators = [itemSep.value, keySep.value];
|
|
3594
|
+
} else if (!(separatorsArg instanceof NullValue)) throw new Error("If set, separators must be a tuple of two strings");
|
|
3595
|
+
return new StringValue(toJSON(operand, {
|
|
3596
|
+
indent: indent.value,
|
|
3597
|
+
ensureAscii: ensureAscii.value,
|
|
3598
|
+
sortKeys: sortKeys.value,
|
|
3599
|
+
separators
|
|
3600
|
+
}));
|
|
3601
|
+
} else if (filterName === "join") {
|
|
3602
|
+
let value;
|
|
3603
|
+
if (operand instanceof StringValue) value = Array.from(operand.value);
|
|
3604
|
+
else if (operand instanceof ArrayValue) value = operand.value.map((x) => x.value);
|
|
3605
|
+
else throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
|
|
3606
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3607
|
+
const separator = args.at(0) ?? kwargs.get("separator") ?? new StringValue("");
|
|
3608
|
+
if (!(separator instanceof StringValue)) throw new Error("separator must be a string");
|
|
3609
|
+
return new StringValue(value.join(separator.value));
|
|
3610
|
+
} else if (filterName === "int" || filterName === "float") {
|
|
3611
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3612
|
+
const defaultValue = args.at(0) ?? kwargs.get("default") ?? (filterName === "int" ? new IntegerValue(0) : new FloatValue(0));
|
|
3613
|
+
if (operand instanceof StringValue) {
|
|
3614
|
+
const val = filterName === "int" ? parseInt(operand.value, 10) : parseFloat(operand.value);
|
|
3615
|
+
return isNaN(val) ? defaultValue : filterName === "int" ? new IntegerValue(val) : new FloatValue(val);
|
|
3616
|
+
} else if (operand instanceof IntegerValue || operand instanceof FloatValue) return operand;
|
|
3617
|
+
else if (operand instanceof BooleanValue) return filterName === "int" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0);
|
|
3618
|
+
else throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
|
|
3619
|
+
} else if (filterName === "default") {
|
|
3620
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3621
|
+
const defaultValue = args[0] ?? new StringValue("");
|
|
3622
|
+
const booleanValue = args[1] ?? kwargs.get("boolean") ?? new BooleanValue(false);
|
|
3623
|
+
if (!(booleanValue instanceof BooleanValue)) throw new Error("`default` filter flag must be a boolean");
|
|
3624
|
+
if (operand instanceof UndefinedValue || booleanValue.value && !operand.__bool__().value) return defaultValue;
|
|
3625
|
+
return operand;
|
|
3626
|
+
}
|
|
3627
|
+
if (operand instanceof ArrayValue) {
|
|
3628
|
+
switch (filterName) {
|
|
3629
|
+
case "sort": {
|
|
3630
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3631
|
+
const reverse = args.at(0) ?? kwargs.get("reverse") ?? new BooleanValue(false);
|
|
3632
|
+
if (!(reverse instanceof BooleanValue)) throw new Error("reverse must be a boolean");
|
|
3633
|
+
const caseSensitive = args.at(1) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false);
|
|
3634
|
+
if (!(caseSensitive instanceof BooleanValue)) throw new Error("case_sensitive must be a boolean");
|
|
3635
|
+
const attribute = args.at(2) ?? kwargs.get("attribute") ?? new NullValue();
|
|
3636
|
+
if (!(attribute instanceof StringValue || attribute instanceof IntegerValue || attribute instanceof NullValue)) throw new Error("attribute must be a string, integer, or null");
|
|
3637
|
+
const getSortValue = (item) => {
|
|
3638
|
+
if (attribute instanceof NullValue) return item;
|
|
3639
|
+
return getAttributeValue(item, attribute instanceof IntegerValue ? String(attribute.value) : attribute.value);
|
|
3640
|
+
};
|
|
3641
|
+
return new ArrayValue(operand.value.slice().sort((a, b) => {
|
|
3642
|
+
const result = compareRuntimeValues(getSortValue(a), getSortValue(b), caseSensitive.value);
|
|
3643
|
+
return reverse.value ? -result : result;
|
|
3644
|
+
}));
|
|
3645
|
+
}
|
|
3646
|
+
case "selectattr":
|
|
3647
|
+
case "rejectattr": {
|
|
3648
|
+
const select = filterName === "selectattr";
|
|
3649
|
+
if (operand.value.some((x) => !(x instanceof ObjectValue))) throw new Error(`\`${filterName}\` can only be applied to array of objects`);
|
|
3650
|
+
if (filter.args.some((x) => x.type !== "StringLiteral")) throw new Error(`arguments of \`${filterName}\` must be strings`);
|
|
3651
|
+
const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));
|
|
3652
|
+
let testFunction;
|
|
3653
|
+
if (testName) {
|
|
3654
|
+
const test = environment.tests.get(testName.value);
|
|
3655
|
+
if (!test) throw new Error(`Unknown test: ${testName.value}`);
|
|
3656
|
+
testFunction = test;
|
|
3657
|
+
} else testFunction = (...x) => x[0].__bool__().value;
|
|
3658
|
+
return new ArrayValue(operand.value.filter((item) => {
|
|
3659
|
+
const a = item.value.get(attr.value);
|
|
3660
|
+
const result = a ? testFunction(a, value) : false;
|
|
3661
|
+
return select ? result : !result;
|
|
3662
|
+
}));
|
|
3663
|
+
}
|
|
3664
|
+
case "map": {
|
|
3665
|
+
const [, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3666
|
+
if (kwargs.has("attribute")) {
|
|
3667
|
+
const attr = kwargs.get("attribute");
|
|
3668
|
+
if (!(attr instanceof StringValue)) throw new Error("attribute must be a string");
|
|
3669
|
+
const defaultValue = kwargs.get("default");
|
|
3670
|
+
return new ArrayValue(operand.value.map((item) => {
|
|
3671
|
+
if (!(item instanceof ObjectValue)) throw new Error("items in map must be an object");
|
|
3672
|
+
const value = getAttributeValue(item, attr.value);
|
|
3673
|
+
return value instanceof UndefinedValue ? defaultValue ?? new UndefinedValue() : value;
|
|
3674
|
+
}));
|
|
3675
|
+
} else throw new Error("`map` expressions without `attribute` set are not currently supported.");
|
|
3676
|
+
}
|
|
3677
|
+
}
|
|
3678
|
+
throw new Error(`Unknown ArrayValue filter: ${filterName}`);
|
|
3679
|
+
} else if (operand instanceof StringValue) {
|
|
3680
|
+
switch (filterName) {
|
|
3681
|
+
case "indent": {
|
|
3682
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3683
|
+
const width = args.at(0) ?? kwargs.get("width") ?? new IntegerValue(4);
|
|
3684
|
+
if (!(width instanceof IntegerValue)) throw new Error("width must be a number");
|
|
3685
|
+
const first = args.at(1) ?? kwargs.get("first") ?? new BooleanValue(false);
|
|
3686
|
+
const blank = args.at(2) ?? kwargs.get("blank") ?? new BooleanValue(false);
|
|
3687
|
+
const lines = operand.value.split("\n");
|
|
3688
|
+
const indent = " ".repeat(width.value);
|
|
3689
|
+
return new StringValue(lines.map((x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x).join("\n"));
|
|
3690
|
+
}
|
|
3691
|
+
case "replace": {
|
|
3692
|
+
const replaceFn = operand.builtins.get("replace");
|
|
3693
|
+
if (!(replaceFn instanceof FunctionValue)) throw new Error("replace filter not available");
|
|
3694
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3695
|
+
return replaceFn.value([...args, new KeywordArgumentsValue(kwargs)], environment);
|
|
3696
|
+
}
|
|
3697
|
+
}
|
|
3698
|
+
throw new Error(`Unknown StringValue filter: ${filterName}`);
|
|
3699
|
+
} else if (operand instanceof ObjectValue) {
|
|
3700
|
+
const builtin = operand.builtins.get(filterName);
|
|
3701
|
+
if (builtin && builtin instanceof FunctionValue) {
|
|
3702
|
+
const [args, kwargs] = this.evaluateArguments(filter.args, environment);
|
|
3703
|
+
if (kwargs.size > 0) args.push(new KeywordArgumentsValue(kwargs));
|
|
3704
|
+
return builtin.value(args, environment);
|
|
3705
|
+
}
|
|
3706
|
+
throw new Error(`Unknown ObjectValue filter: ${filterName}`);
|
|
3707
|
+
} else throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
|
|
3708
|
+
}
|
|
3709
|
+
throw new Error(`Unknown filter: ${filterNode.type}`);
|
|
3710
|
+
}
|
|
3711
|
+
/**
|
|
3712
|
+
* Evaluates expressions following the filter operation type.
|
|
3713
|
+
*/
|
|
3714
|
+
evaluateFilterExpression(node, environment) {
|
|
3715
|
+
const operand = this.evaluate(node.operand, environment);
|
|
3716
|
+
return this.applyFilter(operand, node.filter, environment);
|
|
3717
|
+
}
|
|
3718
|
+
/**
|
|
3719
|
+
* Evaluates expressions following the test operation type.
|
|
3720
|
+
*/
|
|
3721
|
+
evaluateTestExpression(node, environment) {
|
|
3722
|
+
const operand = this.evaluate(node.operand, environment);
|
|
3723
|
+
const test = environment.tests.get(node.test.value);
|
|
3724
|
+
if (!test) throw new Error(`Unknown test: ${node.test.value}`);
|
|
3725
|
+
const result = test(operand);
|
|
3726
|
+
return new BooleanValue(node.negate ? !result : result);
|
|
3727
|
+
}
|
|
3728
|
+
/**
|
|
3729
|
+
* Evaluates expressions following the select operation type.
|
|
3730
|
+
*/
|
|
3731
|
+
evaluateSelectExpression(node, environment) {
|
|
3732
|
+
if (!this.evaluate(node.test, environment).__bool__().value) return new UndefinedValue();
|
|
3733
|
+
return this.evaluate(node.lhs, environment);
|
|
3734
|
+
}
|
|
3735
|
+
/**
|
|
3736
|
+
* Evaluates expressions following the unary operation type.
|
|
3737
|
+
*/
|
|
3738
|
+
evaluateUnaryExpression(node, environment) {
|
|
3739
|
+
const argument = this.evaluate(node.argument, environment);
|
|
3740
|
+
switch (node.operator.value) {
|
|
3741
|
+
case "not": return new BooleanValue(!argument.value);
|
|
3742
|
+
default: throw new SyntaxError(`Unknown operator: ${node.operator.value}`);
|
|
3743
|
+
}
|
|
3744
|
+
}
|
|
3745
|
+
evaluateTernaryExpression(node, environment) {
|
|
3746
|
+
return this.evaluate(node.condition, environment).__bool__().value ? this.evaluate(node.trueExpr, environment) : this.evaluate(node.falseExpr, environment);
|
|
3747
|
+
}
|
|
3748
|
+
evalProgram(program, environment) {
|
|
3749
|
+
return this.evaluateBlock(program.body, environment);
|
|
3750
|
+
}
|
|
3751
|
+
evaluateBlock(statements, environment) {
|
|
3752
|
+
let result = "";
|
|
3753
|
+
for (const statement of statements) {
|
|
3754
|
+
const lastEvaluated = this.evaluate(statement, environment);
|
|
3755
|
+
if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") result += lastEvaluated.toString();
|
|
3756
|
+
}
|
|
3757
|
+
return new StringValue(result);
|
|
3758
|
+
}
|
|
3759
|
+
evaluateIdentifier(node, environment) {
|
|
3760
|
+
return environment.lookupVariable(node.value);
|
|
3761
|
+
}
|
|
3762
|
+
evaluateCallExpression(expr, environment) {
|
|
3763
|
+
const [args, kwargs] = this.evaluateArguments(expr.args, environment);
|
|
3764
|
+
if (kwargs.size > 0) args.push(new KeywordArgumentsValue(kwargs));
|
|
3765
|
+
const fn = this.evaluate(expr.callee, environment);
|
|
3766
|
+
if (fn.type !== "FunctionValue") throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
|
|
3767
|
+
return fn.value(args, environment);
|
|
3768
|
+
}
|
|
3769
|
+
evaluateSliceExpression(object, expr, environment) {
|
|
3770
|
+
if (!(object instanceof ArrayValue || object instanceof StringValue)) throw new Error("Slice object must be an array or string");
|
|
3771
|
+
const start = this.evaluate(expr.start, environment);
|
|
3772
|
+
const stop = this.evaluate(expr.stop, environment);
|
|
3773
|
+
const step = this.evaluate(expr.step, environment);
|
|
3774
|
+
if (!(start instanceof IntegerValue || start instanceof UndefinedValue)) throw new Error("Slice start must be numeric or undefined");
|
|
3775
|
+
if (!(stop instanceof IntegerValue || stop instanceof UndefinedValue)) throw new Error("Slice stop must be numeric or undefined");
|
|
3776
|
+
if (!(step instanceof IntegerValue || step instanceof UndefinedValue)) throw new Error("Slice step must be numeric or undefined");
|
|
3777
|
+
if (object instanceof ArrayValue) return new ArrayValue(slice(object.value, start.value, stop.value, step.value));
|
|
3778
|
+
else return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(""));
|
|
3779
|
+
}
|
|
3780
|
+
evaluateMemberExpression(expr, environment) {
|
|
3781
|
+
const object = this.evaluate(expr.object, environment);
|
|
3782
|
+
let property;
|
|
3783
|
+
if (expr.computed) if (expr.property.type === "SliceExpression") return this.evaluateSliceExpression(object, expr.property, environment);
|
|
3784
|
+
else property = this.evaluate(expr.property, environment);
|
|
3785
|
+
else if (expr.property.type === "IntegerLiteral") property = new IntegerValue(expr.property.value);
|
|
3786
|
+
else property = new StringValue(expr.property.value);
|
|
3787
|
+
let value;
|
|
3788
|
+
if (object instanceof ObjectValue) {
|
|
3789
|
+
if (!(property instanceof StringValue)) throw new Error(`Cannot access property with non-string: got ${property.type}`);
|
|
3790
|
+
value = object.value.get(property.value) ?? object.builtins.get(property.value);
|
|
3791
|
+
} else if (object instanceof ArrayValue || object instanceof StringValue) if (property instanceof IntegerValue) {
|
|
3792
|
+
value = object.value.at(property.value);
|
|
3793
|
+
if (object instanceof StringValue) value = new StringValue(object.value.at(property.value));
|
|
3794
|
+
} else if (property instanceof StringValue) value = object.builtins.get(property.value);
|
|
3795
|
+
else throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);
|
|
3796
|
+
else {
|
|
3797
|
+
if (!(property instanceof StringValue)) throw new Error(`Cannot access property with non-string: got ${property.type}`);
|
|
3798
|
+
value = object.builtins.get(property.value);
|
|
3799
|
+
}
|
|
3800
|
+
return value instanceof RuntimeValue ? value : new UndefinedValue();
|
|
3801
|
+
}
|
|
3802
|
+
evaluateSet(node, environment) {
|
|
3803
|
+
const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment);
|
|
3804
|
+
if (node.assignee.type === "Identifier") {
|
|
3805
|
+
const variableName = node.assignee.value;
|
|
3806
|
+
environment.setVariable(variableName, rhs);
|
|
3807
|
+
} else if (node.assignee.type === "TupleLiteral") {
|
|
3808
|
+
const tuple = node.assignee;
|
|
3809
|
+
if (!(rhs instanceof ArrayValue)) throw new Error(`Cannot unpack non-iterable type in set: ${rhs.type}`);
|
|
3810
|
+
const arr = rhs.value;
|
|
3811
|
+
if (arr.length !== tuple.value.length) throw new Error(`Too ${tuple.value.length > arr.length ? "few" : "many"} items to unpack in set`);
|
|
3812
|
+
for (let i = 0; i < tuple.value.length; ++i) {
|
|
3813
|
+
const elem = tuple.value[i];
|
|
3814
|
+
if (elem.type !== "Identifier") throw new Error(`Cannot unpack to non-identifier in set: ${elem.type}`);
|
|
3815
|
+
environment.setVariable(elem.value, arr[i]);
|
|
3816
|
+
}
|
|
3817
|
+
} else if (node.assignee.type === "MemberExpression") {
|
|
3818
|
+
const member = node.assignee;
|
|
3819
|
+
const object = this.evaluate(member.object, environment);
|
|
3820
|
+
if (!(object instanceof ObjectValue)) throw new Error("Cannot assign to member of non-object");
|
|
3821
|
+
if (member.property.type !== "Identifier") throw new Error("Cannot assign to member with non-identifier property");
|
|
3822
|
+
object.value.set(member.property.value, rhs);
|
|
3823
|
+
} else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);
|
|
3824
|
+
return new NullValue();
|
|
3825
|
+
}
|
|
3826
|
+
evaluateIf(node, environment) {
|
|
3827
|
+
const test = this.evaluate(node.test, environment);
|
|
3828
|
+
return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);
|
|
3829
|
+
}
|
|
3830
|
+
evaluateFor(node, environment) {
|
|
3831
|
+
const scope = new Environment(environment);
|
|
3832
|
+
let test, iterable;
|
|
3833
|
+
if (node.iterable.type === "SelectExpression") {
|
|
3834
|
+
const select = node.iterable;
|
|
3835
|
+
iterable = this.evaluate(select.lhs, scope);
|
|
3836
|
+
test = select.test;
|
|
3837
|
+
} else iterable = this.evaluate(node.iterable, scope);
|
|
3838
|
+
if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`);
|
|
3839
|
+
if (iterable instanceof ObjectValue) iterable = iterable.keys();
|
|
3840
|
+
const items = [];
|
|
3841
|
+
const scopeUpdateFunctions = [];
|
|
3842
|
+
for (let i = 0; i < iterable.value.length; ++i) {
|
|
3843
|
+
const loopScope = new Environment(scope);
|
|
3844
|
+
const current = iterable.value[i];
|
|
3845
|
+
let scopeUpdateFunction;
|
|
3846
|
+
if (node.loopvar.type === "Identifier") scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);
|
|
3847
|
+
else if (node.loopvar.type === "TupleLiteral") {
|
|
3848
|
+
const loopvar = node.loopvar;
|
|
3849
|
+
if (current.type !== "ArrayValue") throw new Error(`Cannot unpack non-iterable type: ${current.type}`);
|
|
3850
|
+
const c = current;
|
|
3851
|
+
if (loopvar.value.length !== c.value.length) throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`);
|
|
3852
|
+
scopeUpdateFunction = (scope2) => {
|
|
3853
|
+
for (let j = 0; j < loopvar.value.length; ++j) {
|
|
3854
|
+
if (loopvar.value[j].type !== "Identifier") throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);
|
|
3855
|
+
scope2.setVariable(loopvar.value[j].value, c.value[j]);
|
|
3856
|
+
}
|
|
3857
|
+
};
|
|
3858
|
+
} else throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);
|
|
3859
|
+
if (test) {
|
|
3860
|
+
scopeUpdateFunction(loopScope);
|
|
3861
|
+
if (!this.evaluate(test, loopScope).__bool__().value) continue;
|
|
3862
|
+
}
|
|
3863
|
+
items.push(current);
|
|
3864
|
+
scopeUpdateFunctions.push(scopeUpdateFunction);
|
|
3865
|
+
}
|
|
3866
|
+
let result = "";
|
|
3867
|
+
let noIteration = true;
|
|
3868
|
+
for (let i = 0; i < items.length; ++i) {
|
|
3869
|
+
const loop = /* @__PURE__ */ new Map([
|
|
3870
|
+
["index", new IntegerValue(i + 1)],
|
|
3871
|
+
["index0", new IntegerValue(i)],
|
|
3872
|
+
["revindex", new IntegerValue(items.length - i)],
|
|
3873
|
+
["revindex0", new IntegerValue(items.length - i - 1)],
|
|
3874
|
+
["first", new BooleanValue(i === 0)],
|
|
3875
|
+
["last", new BooleanValue(i === items.length - 1)],
|
|
3876
|
+
["length", new IntegerValue(items.length)],
|
|
3877
|
+
["previtem", i > 0 ? items[i - 1] : new UndefinedValue()],
|
|
3878
|
+
["nextitem", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]
|
|
3879
|
+
]);
|
|
3880
|
+
scope.setVariable("loop", new ObjectValue(loop));
|
|
3881
|
+
scopeUpdateFunctions[i](scope);
|
|
3882
|
+
try {
|
|
3883
|
+
const evaluated = this.evaluateBlock(node.body, scope);
|
|
3884
|
+
result += evaluated.value;
|
|
3885
|
+
} catch (err) {
|
|
3886
|
+
if (err instanceof ContinueControl) continue;
|
|
3887
|
+
if (err instanceof BreakControl) break;
|
|
3888
|
+
throw err;
|
|
3889
|
+
}
|
|
3890
|
+
noIteration = false;
|
|
3891
|
+
}
|
|
3892
|
+
if (noIteration) {
|
|
3893
|
+
const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);
|
|
3894
|
+
result += defaultEvaluated.value;
|
|
3895
|
+
}
|
|
3896
|
+
return new StringValue(result);
|
|
3897
|
+
}
|
|
3898
|
+
/**
|
|
3899
|
+
* See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.
|
|
3900
|
+
*/
|
|
3901
|
+
evaluateMacro(node, environment) {
|
|
3902
|
+
environment.setVariable(node.name.value, new FunctionValue((args, scope) => {
|
|
3903
|
+
const macroScope = new Environment(scope);
|
|
3904
|
+
args = args.slice();
|
|
3905
|
+
let kwargs;
|
|
3906
|
+
if (args.at(-1)?.type === "KeywordArgumentsValue") kwargs = args.pop();
|
|
3907
|
+
for (let i = 0; i < node.args.length; ++i) {
|
|
3908
|
+
const nodeArg = node.args[i];
|
|
3909
|
+
const passedArg = args[i];
|
|
3910
|
+
if (nodeArg.type === "Identifier") {
|
|
3911
|
+
const identifier = nodeArg;
|
|
3912
|
+
if (!passedArg) throw new Error(`Missing positional argument: ${identifier.value}`);
|
|
3913
|
+
macroScope.setVariable(identifier.value, passedArg);
|
|
3914
|
+
} else if (nodeArg.type === "KeywordArgumentExpression") {
|
|
3915
|
+
const kwarg = nodeArg;
|
|
3916
|
+
const value = passedArg ?? kwargs?.value.get(kwarg.key.value) ?? this.evaluate(kwarg.value, macroScope);
|
|
3917
|
+
macroScope.setVariable(kwarg.key.value, value);
|
|
3918
|
+
} else throw new Error(`Unknown argument type: ${nodeArg.type}`);
|
|
3919
|
+
}
|
|
3920
|
+
return this.evaluateBlock(node.body, macroScope);
|
|
3921
|
+
}));
|
|
3922
|
+
return new NullValue();
|
|
3923
|
+
}
|
|
3924
|
+
evaluateCallStatement(node, environment) {
|
|
3925
|
+
const callerFn = new FunctionValue((callerArgs, callerEnv) => {
|
|
3926
|
+
const callBlockEnv = new Environment(callerEnv);
|
|
3927
|
+
if (node.callerArgs) for (let i = 0; i < node.callerArgs.length; ++i) {
|
|
3928
|
+
const param = node.callerArgs[i];
|
|
3929
|
+
if (param.type !== "Identifier") throw new Error(`Caller parameter must be an identifier, got ${param.type}`);
|
|
3930
|
+
callBlockEnv.setVariable(param.value, callerArgs[i] ?? new UndefinedValue());
|
|
3931
|
+
}
|
|
3932
|
+
return this.evaluateBlock(node.body, callBlockEnv);
|
|
3933
|
+
});
|
|
3934
|
+
const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment);
|
|
3935
|
+
macroArgs.push(new KeywordArgumentsValue(macroKwargs));
|
|
3936
|
+
const fn = this.evaluate(node.call.callee, environment);
|
|
3937
|
+
if (fn.type !== "FunctionValue") throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
|
|
3938
|
+
const newEnv = new Environment(environment);
|
|
3939
|
+
newEnv.setVariable("caller", callerFn);
|
|
3940
|
+
return fn.value(macroArgs, newEnv);
|
|
3941
|
+
}
|
|
3942
|
+
evaluateFilterStatement(node, environment) {
|
|
3943
|
+
const rendered = this.evaluateBlock(node.body, environment);
|
|
3944
|
+
return this.applyFilter(rendered, node.filter, environment);
|
|
3945
|
+
}
|
|
3946
|
+
evaluate(statement, environment) {
|
|
3947
|
+
if (!statement) return new UndefinedValue();
|
|
3948
|
+
switch (statement.type) {
|
|
3949
|
+
case "Program": return this.evalProgram(statement, environment);
|
|
3950
|
+
case "Set": return this.evaluateSet(statement, environment);
|
|
3951
|
+
case "If": return this.evaluateIf(statement, environment);
|
|
3952
|
+
case "For": return this.evaluateFor(statement, environment);
|
|
3953
|
+
case "Macro": return this.evaluateMacro(statement, environment);
|
|
3954
|
+
case "CallStatement": return this.evaluateCallStatement(statement, environment);
|
|
3955
|
+
case "Break": throw new BreakControl();
|
|
3956
|
+
case "Continue": throw new ContinueControl();
|
|
3957
|
+
case "IntegerLiteral": return new IntegerValue(statement.value);
|
|
3958
|
+
case "FloatLiteral": return new FloatValue(statement.value);
|
|
3959
|
+
case "StringLiteral": return new StringValue(statement.value);
|
|
3960
|
+
case "ArrayLiteral": return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));
|
|
3961
|
+
case "TupleLiteral": return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));
|
|
3962
|
+
case "ObjectLiteral": {
|
|
3963
|
+
const mapping = /* @__PURE__ */ new Map();
|
|
3964
|
+
for (const [key, value] of statement.value) {
|
|
3965
|
+
const evaluatedKey = this.evaluate(key, environment);
|
|
3966
|
+
if (!(evaluatedKey instanceof StringValue)) throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);
|
|
3967
|
+
mapping.set(evaluatedKey.value, this.evaluate(value, environment));
|
|
3968
|
+
}
|
|
3969
|
+
return new ObjectValue(mapping);
|
|
3970
|
+
}
|
|
3971
|
+
case "Identifier": return this.evaluateIdentifier(statement, environment);
|
|
3972
|
+
case "CallExpression": return this.evaluateCallExpression(statement, environment);
|
|
3973
|
+
case "MemberExpression": return this.evaluateMemberExpression(statement, environment);
|
|
3974
|
+
case "UnaryExpression": return this.evaluateUnaryExpression(statement, environment);
|
|
3975
|
+
case "BinaryExpression": return this.evaluateBinaryExpression(statement, environment);
|
|
3976
|
+
case "FilterExpression": return this.evaluateFilterExpression(statement, environment);
|
|
3977
|
+
case "FilterStatement": return this.evaluateFilterStatement(statement, environment);
|
|
3978
|
+
case "TestExpression": return this.evaluateTestExpression(statement, environment);
|
|
3979
|
+
case "SelectExpression": return this.evaluateSelectExpression(statement, environment);
|
|
3980
|
+
case "Ternary": return this.evaluateTernaryExpression(statement, environment);
|
|
3981
|
+
case "Comment": return new NullValue();
|
|
3982
|
+
default: throw new SyntaxError(`Unknown node type: ${statement.type}`);
|
|
3983
|
+
}
|
|
3984
|
+
}
|
|
3985
|
+
};
|
|
3986
|
+
function convertToRuntimeValues(input) {
|
|
3987
|
+
switch (typeof input) {
|
|
3988
|
+
case "number": return Number.isInteger(input) ? new IntegerValue(input) : new FloatValue(input);
|
|
3989
|
+
case "string": return new StringValue(input);
|
|
3990
|
+
case "boolean": return new BooleanValue(input);
|
|
3991
|
+
case "undefined": return new UndefinedValue();
|
|
3992
|
+
case "object": if (input === null) return new NullValue();
|
|
3993
|
+
else if (Array.isArray(input)) return new ArrayValue(input.map(convertToRuntimeValues));
|
|
3994
|
+
else return new ObjectValue(new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)])));
|
|
3995
|
+
case "function": return new FunctionValue((args, _scope) => {
|
|
3996
|
+
return convertToRuntimeValues(input(...args.map((x) => x.value)) ?? null);
|
|
3997
|
+
});
|
|
3998
|
+
default: throw new Error(`Cannot convert to runtime value: ${input}`);
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
var NEWLINE = "\n";
|
|
4002
|
+
var OPEN_STATEMENT = "{%- ";
|
|
4003
|
+
var CLOSE_STATEMENT = " -%}";
|
|
4004
|
+
function getBinaryOperatorPrecedence(expr) {
|
|
4005
|
+
switch (expr.operator.type) {
|
|
4006
|
+
case "MultiplicativeBinaryOperator": return 4;
|
|
4007
|
+
case "AdditiveBinaryOperator": return 3;
|
|
4008
|
+
case "ComparisonBinaryOperator": return 2;
|
|
4009
|
+
case "Identifier":
|
|
4010
|
+
if (expr.operator.value === "and") return 1;
|
|
4011
|
+
if (expr.operator.value === "in" || expr.operator.value === "not in") return 2;
|
|
4012
|
+
return 0;
|
|
4013
|
+
}
|
|
4014
|
+
return 0;
|
|
4015
|
+
}
|
|
4016
|
+
function format(program, indent = " ") {
|
|
4017
|
+
const indentStr = typeof indent === "number" ? " ".repeat(indent) : indent;
|
|
4018
|
+
return formatStatements(program.body, 0, indentStr).replace(/\n$/, "");
|
|
4019
|
+
}
|
|
4020
|
+
function createStatement(...text) {
|
|
4021
|
+
return OPEN_STATEMENT + text.join(" ") + CLOSE_STATEMENT;
|
|
4022
|
+
}
|
|
4023
|
+
function formatStatements(stmts, depth, indentStr) {
|
|
4024
|
+
return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE);
|
|
4025
|
+
}
|
|
4026
|
+
function formatStatement(node, depth, indentStr) {
|
|
4027
|
+
const pad = indentStr.repeat(depth);
|
|
4028
|
+
switch (node.type) {
|
|
4029
|
+
case "Program": return formatStatements(node.body, depth, indentStr);
|
|
4030
|
+
case "If": return formatIf(node, depth, indentStr);
|
|
4031
|
+
case "For": return formatFor(node, depth, indentStr);
|
|
4032
|
+
case "Set": return formatSet(node, depth, indentStr);
|
|
4033
|
+
case "Macro": return formatMacro(node, depth, indentStr);
|
|
4034
|
+
case "Break": return pad + createStatement("break");
|
|
4035
|
+
case "Continue": return pad + createStatement("continue");
|
|
4036
|
+
case "CallStatement": return formatCallStatement(node, depth, indentStr);
|
|
4037
|
+
case "FilterStatement": return formatFilterStatement(node, depth, indentStr);
|
|
4038
|
+
case "Comment": return pad + "{# " + node.value + " #}";
|
|
4039
|
+
default: return pad + "{{- " + formatExpression(node) + " -}}";
|
|
4040
|
+
}
|
|
4041
|
+
}
|
|
4042
|
+
function formatIf(node, depth, indentStr) {
|
|
4043
|
+
const pad = indentStr.repeat(depth);
|
|
4044
|
+
const clauses = [];
|
|
4045
|
+
let current = node;
|
|
4046
|
+
while (current) {
|
|
4047
|
+
clauses.push({
|
|
4048
|
+
test: current.test,
|
|
4049
|
+
body: current.body
|
|
4050
|
+
});
|
|
4051
|
+
if (current.alternate.length === 1 && current.alternate[0].type === "If") current = current.alternate[0];
|
|
4052
|
+
else break;
|
|
4053
|
+
}
|
|
4054
|
+
let out = pad + createStatement("if", formatExpression(clauses[0].test)) + NEWLINE + formatStatements(clauses[0].body, depth + 1, indentStr);
|
|
4055
|
+
for (let i = 1; i < clauses.length; ++i) out += NEWLINE + pad + createStatement("elif", formatExpression(clauses[i].test)) + NEWLINE + formatStatements(clauses[i].body, depth + 1, indentStr);
|
|
4056
|
+
if (current && current.alternate.length > 0) out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(current.alternate, depth + 1, indentStr);
|
|
4057
|
+
out += NEWLINE + pad + createStatement("endif");
|
|
4058
|
+
return out;
|
|
4059
|
+
}
|
|
4060
|
+
function formatFor(node, depth, indentStr) {
|
|
4061
|
+
const pad = indentStr.repeat(depth);
|
|
4062
|
+
let formattedIterable = "";
|
|
4063
|
+
if (node.iterable.type === "SelectExpression") {
|
|
4064
|
+
const n = node.iterable;
|
|
4065
|
+
formattedIterable = `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;
|
|
4066
|
+
} else formattedIterable = formatExpression(node.iterable);
|
|
4067
|
+
let out = pad + createStatement("for", formatExpression(node.loopvar), "in", formattedIterable) + NEWLINE + formatStatements(node.body, depth + 1, indentStr);
|
|
4068
|
+
if (node.defaultBlock.length > 0) out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(node.defaultBlock, depth + 1, indentStr);
|
|
4069
|
+
out += NEWLINE + pad + createStatement("endfor");
|
|
4070
|
+
return out;
|
|
4071
|
+
}
|
|
4072
|
+
function formatSet(node, depth, indentStr) {
|
|
4073
|
+
const pad = indentStr.repeat(depth);
|
|
4074
|
+
const left = formatExpression(node.assignee);
|
|
4075
|
+
const right = node.value ? formatExpression(node.value) : "";
|
|
4076
|
+
const value = pad + createStatement("set", `${left}${node.value ? " = " + right : ""}`);
|
|
4077
|
+
if (node.body.length === 0) return value;
|
|
4078
|
+
return value + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endset");
|
|
4079
|
+
}
|
|
4080
|
+
function formatMacro(node, depth, indentStr) {
|
|
4081
|
+
const pad = indentStr.repeat(depth);
|
|
4082
|
+
const args = node.args.map(formatExpression).join(", ");
|
|
4083
|
+
return pad + createStatement("macro", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endmacro");
|
|
4084
|
+
}
|
|
4085
|
+
function formatCallStatement(node, depth, indentStr) {
|
|
4086
|
+
const pad = indentStr.repeat(depth);
|
|
4087
|
+
const params = node.callerArgs && node.callerArgs.length > 0 ? `(${node.callerArgs.map(formatExpression).join(", ")})` : "";
|
|
4088
|
+
const callExpr = formatExpression(node.call);
|
|
4089
|
+
let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE;
|
|
4090
|
+
out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;
|
|
4091
|
+
out += pad + createStatement("endcall");
|
|
4092
|
+
return out;
|
|
4093
|
+
}
|
|
4094
|
+
function formatFilterStatement(node, depth, indentStr) {
|
|
4095
|
+
const pad = indentStr.repeat(depth);
|
|
4096
|
+
let out = pad + createStatement("filter", node.filter.type === "Identifier" ? node.filter.value : formatExpression(node.filter)) + NEWLINE;
|
|
4097
|
+
out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;
|
|
4098
|
+
out += pad + createStatement("endfilter");
|
|
4099
|
+
return out;
|
|
4100
|
+
}
|
|
4101
|
+
function formatExpression(node, parentPrec = -1) {
|
|
4102
|
+
switch (node.type) {
|
|
4103
|
+
case "SpreadExpression": return `*${formatExpression(node.argument)}`;
|
|
4104
|
+
case "Identifier": return node.value;
|
|
4105
|
+
case "IntegerLiteral": return `${node.value}`;
|
|
4106
|
+
case "FloatLiteral": return `${node.value}`;
|
|
4107
|
+
case "StringLiteral": return JSON.stringify(node.value);
|
|
4108
|
+
case "BinaryExpression": {
|
|
4109
|
+
const n = node;
|
|
4110
|
+
const thisPrecedence = getBinaryOperatorPrecedence(n);
|
|
4111
|
+
const left = formatExpression(n.left, thisPrecedence);
|
|
4112
|
+
const right = formatExpression(n.right, thisPrecedence + 1);
|
|
4113
|
+
const expr = `${left} ${n.operator.value} ${right}`;
|
|
4114
|
+
return thisPrecedence < parentPrec ? `(${expr})` : expr;
|
|
4115
|
+
}
|
|
4116
|
+
case "UnaryExpression": {
|
|
4117
|
+
const n = node;
|
|
4118
|
+
return n.operator.value + (n.operator.value === "not" ? " " : "") + formatExpression(n.argument, Infinity);
|
|
4119
|
+
}
|
|
4120
|
+
case "CallExpression": {
|
|
4121
|
+
const n = node;
|
|
4122
|
+
const args = n.args.map(formatExpression).join(", ");
|
|
4123
|
+
return `${formatExpression(n.callee)}(${args})`;
|
|
4124
|
+
}
|
|
4125
|
+
case "MemberExpression": {
|
|
4126
|
+
const n = node;
|
|
4127
|
+
let obj = formatExpression(n.object);
|
|
4128
|
+
if (![
|
|
4129
|
+
"Identifier",
|
|
4130
|
+
"MemberExpression",
|
|
4131
|
+
"CallExpression",
|
|
4132
|
+
"StringLiteral",
|
|
4133
|
+
"IntegerLiteral",
|
|
4134
|
+
"FloatLiteral",
|
|
4135
|
+
"ArrayLiteral",
|
|
4136
|
+
"TupleLiteral",
|
|
4137
|
+
"ObjectLiteral"
|
|
4138
|
+
].includes(n.object.type)) obj = `(${obj})`;
|
|
4139
|
+
let prop = formatExpression(n.property);
|
|
4140
|
+
if (!n.computed && n.property.type !== "Identifier" && n.property.type !== "IntegerLiteral") prop = `(${prop})`;
|
|
4141
|
+
return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`;
|
|
4142
|
+
}
|
|
4143
|
+
case "FilterExpression": {
|
|
4144
|
+
const n = node;
|
|
4145
|
+
const operand = formatExpression(n.operand, Infinity);
|
|
4146
|
+
if (n.filter.type === "CallExpression") return `${operand} | ${formatExpression(n.filter)}`;
|
|
4147
|
+
return `${operand} | ${n.filter.value}`;
|
|
4148
|
+
}
|
|
4149
|
+
case "SelectExpression": {
|
|
4150
|
+
const n = node;
|
|
4151
|
+
return `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;
|
|
4152
|
+
}
|
|
4153
|
+
case "TestExpression": {
|
|
4154
|
+
const n = node;
|
|
4155
|
+
return `${formatExpression(n.operand)} is${n.negate ? " not" : ""} ${n.test.value}`;
|
|
4156
|
+
}
|
|
4157
|
+
case "ArrayLiteral":
|
|
4158
|
+
case "TupleLiteral": {
|
|
4159
|
+
const elems = node.value.map(formatExpression);
|
|
4160
|
+
const brackets = node.type === "ArrayLiteral" ? "[]" : "()";
|
|
4161
|
+
return `${brackets[0]}${elems.join(", ")}${brackets[1]}`;
|
|
4162
|
+
}
|
|
4163
|
+
case "ObjectLiteral": return `{${Array.from(node.value.entries()).map(([k, v]) => `${formatExpression(k)}: ${formatExpression(v)}`).join(", ")}}`;
|
|
4164
|
+
case "SliceExpression": {
|
|
4165
|
+
const n = node;
|
|
4166
|
+
return `${n.start ? formatExpression(n.start) : ""}:${n.stop ? formatExpression(n.stop) : ""}${n.step ? `:${formatExpression(n.step)}` : ""}`;
|
|
4167
|
+
}
|
|
4168
|
+
case "KeywordArgumentExpression": {
|
|
4169
|
+
const n = node;
|
|
4170
|
+
return `${n.key.value}=${formatExpression(n.value)}`;
|
|
4171
|
+
}
|
|
4172
|
+
case "Ternary": {
|
|
4173
|
+
const n = node;
|
|
4174
|
+
const expr = `${formatExpression(n.trueExpr)} if ${formatExpression(n.condition, 0)} else ${formatExpression(n.falseExpr)}`;
|
|
4175
|
+
return parentPrec > -1 ? `(${expr})` : expr;
|
|
4176
|
+
}
|
|
4177
|
+
default: throw new Error(`Unknown expression type: ${node.type}`);
|
|
4178
|
+
}
|
|
4179
|
+
}
|
|
4180
|
+
var Template = class {
|
|
4181
|
+
parsed;
|
|
4182
|
+
/**
|
|
4183
|
+
* @param {string} template The template string
|
|
4184
|
+
*/
|
|
4185
|
+
constructor(template) {
|
|
4186
|
+
const tokens = tokenize(template, {
|
|
4187
|
+
lstrip_blocks: true,
|
|
4188
|
+
trim_blocks: true
|
|
4189
|
+
});
|
|
4190
|
+
this.parsed = parse(tokens);
|
|
4191
|
+
}
|
|
4192
|
+
render(items) {
|
|
4193
|
+
const env = new Environment();
|
|
4194
|
+
setupGlobals(env);
|
|
4195
|
+
if (items) for (const [key, value] of Object.entries(items)) env.set(key, value);
|
|
4196
|
+
return new Interpreter(env).run(this.parsed).value;
|
|
4197
|
+
}
|
|
4198
|
+
format(options) {
|
|
4199
|
+
return format(this.parsed, options?.indent || " ");
|
|
4200
|
+
}
|
|
4201
|
+
};
|
|
4202
|
+
//#endregion
|
|
4203
|
+
//#region src/chat/tokenizer.ts
|
|
4204
|
+
/*!
|
|
4205
|
+
* bitgpu/chat bundles @huggingface/tokenizers and @huggingface/jinja (Apache-2.0,
|
|
4206
|
+
* (c) Hugging Face) at build time so the published package stays dependency-free.
|
|
4207
|
+
* See THIRD_PARTY_LICENSES.md in the package root.
|
|
4208
|
+
*/
|
|
4209
|
+
const tokenString = (v) => typeof v === "string" ? v : v?.content ?? null;
|
|
4210
|
+
var ChatTokenizer = class {
|
|
4211
|
+
tok;
|
|
4212
|
+
template;
|
|
4213
|
+
templateContext;
|
|
4214
|
+
/** End-of-sequence token id (e.g. <|im_end|> for Qwen3-family models). */
|
|
4215
|
+
eosTokenId;
|
|
4216
|
+
/** The eos token's string form (used to reconstruct the template's turn terminator). */
|
|
4217
|
+
eosToken;
|
|
4218
|
+
constructor(tokenizerJson, tokenizerConfig) {
|
|
4219
|
+
this.tok = new Tokenizer_default(tokenizerJson, tokenizerConfig);
|
|
4220
|
+
const tmpl = tokenizerConfig["chat_template"];
|
|
4221
|
+
this.template = typeof tmpl === "string" ? new Template(tmpl) : null;
|
|
4222
|
+
this.templateContext = {};
|
|
4223
|
+
for (const k of [
|
|
4224
|
+
"bos_token",
|
|
4225
|
+
"eos_token",
|
|
4226
|
+
"pad_token",
|
|
4227
|
+
"unk_token"
|
|
4228
|
+
]) {
|
|
4229
|
+
const s = tokenString(tokenizerConfig[k]);
|
|
4230
|
+
if (s !== null) this.templateContext[k] = s;
|
|
4231
|
+
}
|
|
4232
|
+
const eosStr = tokenString(tokenizerConfig["eos_token"]);
|
|
4233
|
+
const eosId = eosStr !== null ? this.tok.token_to_id(eosStr) : void 0;
|
|
4234
|
+
if (eosStr === null || eosId === void 0) throw new Error("bitgpu/chat: tokenizer_config.json has no resolvable eos_token (needed to stop generation and to reconstruct cached turns)");
|
|
4235
|
+
this.eosToken = eosStr;
|
|
4236
|
+
this.eosTokenId = eosId;
|
|
4237
|
+
}
|
|
4238
|
+
/** Encode text to token ids. `addSpecialTokens` defaults to false: the chat template already
|
|
4239
|
+
* inserts the control tokens, so prompt/delta encoding must not add more. */
|
|
4240
|
+
encode(text, addSpecialTokens = false) {
|
|
4241
|
+
return Array.from(this.tok.encode(text, { add_special_tokens: addSpecialTokens }).ids, Number);
|
|
4242
|
+
}
|
|
4243
|
+
/** Decode token ids to text. `skipSpecialTokens` defaults to true (never surface control tokens). */
|
|
4244
|
+
decode(ids, skipSpecialTokens = true) {
|
|
4245
|
+
if (ids.length === 0) return "";
|
|
4246
|
+
return this.tok.decode(ids, { skip_special_tokens: skipSpecialTokens });
|
|
4247
|
+
}
|
|
4248
|
+
/** The raw vocab string for a token id (byte-alias space for byte-level BPE). */
|
|
4249
|
+
idToToken(id) {
|
|
4250
|
+
return this.tok.id_to_token(id);
|
|
4251
|
+
}
|
|
4252
|
+
/** Ids of all added tokens (ChatML markers, <think>, etc.) - never plain content. */
|
|
4253
|
+
addedTokenIds() {
|
|
4254
|
+
return new Set(this.tok.get_added_tokens_decoder().keys());
|
|
4255
|
+
}
|
|
4256
|
+
get hasChatTemplate() {
|
|
4257
|
+
return this.template !== null;
|
|
4258
|
+
}
|
|
4259
|
+
/** Render a message list to a prompt string via the model's own Jinja chat template
|
|
4260
|
+
* (matches transformers.js apply_chat_template byte-exactly). */
|
|
4261
|
+
applyChatTemplate(messages, opts = {}) {
|
|
4262
|
+
if (!this.template) throw new Error("bitgpu/chat: the model has no chat_template in tokenizer_config.json");
|
|
4263
|
+
return this.template.render({
|
|
4264
|
+
...this.templateContext,
|
|
4265
|
+
messages,
|
|
4266
|
+
add_generation_prompt: opts.addGenerationPrompt ?? true,
|
|
4267
|
+
enable_thinking: opts.enableThinking ?? false
|
|
4268
|
+
});
|
|
4269
|
+
}
|
|
4270
|
+
createDecoderStream(skipSpecialTokens = true) {
|
|
4271
|
+
const ids = [];
|
|
4272
|
+
let emitted = 0;
|
|
4273
|
+
const decodeAll = () => this.tok.decode(ids, { skip_special_tokens: skipSpecialTokens });
|
|
4274
|
+
return {
|
|
4275
|
+
push: (tokenId) => {
|
|
4276
|
+
ids.push(tokenId);
|
|
4277
|
+
const text = decodeAll();
|
|
4278
|
+
let safe = text.length;
|
|
4279
|
+
while (safe > emitted && text.charCodeAt(safe - 1) === 65533) safe--;
|
|
4280
|
+
const out = text.slice(emitted, safe);
|
|
4281
|
+
emitted = safe;
|
|
4282
|
+
return out;
|
|
4283
|
+
},
|
|
4284
|
+
flush: () => {
|
|
4285
|
+
if (ids.length === 0) return "";
|
|
4286
|
+
const text = decodeAll();
|
|
4287
|
+
const out = text.slice(emitted);
|
|
4288
|
+
emitted = text.length;
|
|
4289
|
+
return out;
|
|
4290
|
+
}
|
|
4291
|
+
};
|
|
4292
|
+
}
|
|
4293
|
+
};
|
|
4294
|
+
//#endregion
|
|
4295
|
+
//#region src/chat/think.ts
|
|
4296
|
+
/** Longest suffix of `s` that is a proper prefix of `tag` (what must be held back). */
|
|
4297
|
+
function holdback(s, tag) {
|
|
4298
|
+
const max = Math.min(s.length, tag.length - 1);
|
|
4299
|
+
for (let k = max; k > 0; k--) if (tag.startsWith(s.slice(s.length - k))) return s.length - k;
|
|
4300
|
+
return s.length;
|
|
4301
|
+
}
|
|
4302
|
+
var ThinkSplitter = class {
|
|
4303
|
+
open;
|
|
4304
|
+
close;
|
|
4305
|
+
inside = false;
|
|
4306
|
+
hold = "";
|
|
4307
|
+
constructor(open = "<think>", close = "</think>") {
|
|
4308
|
+
this.open = open;
|
|
4309
|
+
this.close = close;
|
|
4310
|
+
}
|
|
4311
|
+
push(chunk) {
|
|
4312
|
+
let s = this.hold + chunk;
|
|
4313
|
+
this.hold = "";
|
|
4314
|
+
let text = "";
|
|
4315
|
+
let think = "";
|
|
4316
|
+
for (;;) if (!this.inside) {
|
|
4317
|
+
const i = s.indexOf(this.open);
|
|
4318
|
+
if (i === -1) {
|
|
4319
|
+
const safe = holdback(s, this.open);
|
|
4320
|
+
text += s.slice(0, safe);
|
|
4321
|
+
this.hold = s.slice(safe);
|
|
4322
|
+
return {
|
|
4323
|
+
text,
|
|
4324
|
+
think
|
|
4325
|
+
};
|
|
4326
|
+
}
|
|
4327
|
+
text += s.slice(0, i);
|
|
4328
|
+
s = s.slice(i + this.open.length);
|
|
4329
|
+
this.inside = true;
|
|
4330
|
+
} else {
|
|
4331
|
+
const i = s.indexOf(this.close);
|
|
4332
|
+
if (i === -1) {
|
|
4333
|
+
const safe = holdback(s, this.close);
|
|
4334
|
+
think += s.slice(0, safe);
|
|
4335
|
+
this.hold = s.slice(safe);
|
|
4336
|
+
return {
|
|
4337
|
+
text,
|
|
4338
|
+
think
|
|
4339
|
+
};
|
|
4340
|
+
}
|
|
4341
|
+
think += s.slice(0, i);
|
|
4342
|
+
s = s.slice(i + this.close.length);
|
|
4343
|
+
this.inside = false;
|
|
4344
|
+
}
|
|
4345
|
+
}
|
|
4346
|
+
/** Emit whatever is held back. An unterminated think block (generation hit maxTokens inside it)
|
|
4347
|
+
* flushes to the think channel, never to the visible reply. */
|
|
4348
|
+
flush() {
|
|
4349
|
+
const r = this.inside ? {
|
|
4350
|
+
text: "",
|
|
4351
|
+
think: this.hold
|
|
4352
|
+
} : {
|
|
4353
|
+
text: this.hold,
|
|
4354
|
+
think: ""
|
|
4355
|
+
};
|
|
4356
|
+
this.hold = "";
|
|
4357
|
+
this.inside = false;
|
|
4358
|
+
return r;
|
|
4359
|
+
}
|
|
4360
|
+
};
|
|
4361
|
+
/** Stream-safe stop-sequence scanner: emits visible text up to (excluding) the earliest match of
|
|
4362
|
+
* any stop string, holding back chunk-edge suffixes that could begin one (stops can straddle
|
|
4363
|
+
* token boundaries). Once matched, everything further is swallowed. */
|
|
4364
|
+
var StopScanner = class {
|
|
4365
|
+
stops;
|
|
4366
|
+
matched = false;
|
|
4367
|
+
hold = "";
|
|
4368
|
+
constructor(stops) {
|
|
4369
|
+
this.stops = stops;
|
|
4370
|
+
}
|
|
4371
|
+
push(text) {
|
|
4372
|
+
if (this.matched) return "";
|
|
4373
|
+
const s = this.hold + text;
|
|
4374
|
+
let mi = -1;
|
|
4375
|
+
for (const st of this.stops) {
|
|
4376
|
+
const i = s.indexOf(st);
|
|
4377
|
+
if (i !== -1 && (mi === -1 || i < mi)) mi = i;
|
|
4378
|
+
}
|
|
4379
|
+
if (mi !== -1) {
|
|
4380
|
+
this.matched = true;
|
|
4381
|
+
this.hold = "";
|
|
4382
|
+
return s.slice(0, mi);
|
|
4383
|
+
}
|
|
4384
|
+
let safe = s.length;
|
|
4385
|
+
for (const st of this.stops) safe = Math.min(safe, holdback(s, st));
|
|
4386
|
+
this.hold = s.slice(safe);
|
|
4387
|
+
return s.slice(0, safe);
|
|
4388
|
+
}
|
|
4389
|
+
flush() {
|
|
4390
|
+
const r = this.matched ? "" : this.hold;
|
|
4391
|
+
this.hold = "";
|
|
4392
|
+
return r;
|
|
4393
|
+
}
|
|
4394
|
+
};
|
|
4395
|
+
//#endregion
|
|
4396
|
+
//#region src/chat/json.ts
|
|
4397
|
+
const WS = /* @__PURE__ */ new Set([
|
|
4398
|
+
32,
|
|
4399
|
+
9,
|
|
4400
|
+
10,
|
|
4401
|
+
13
|
|
4402
|
+
]);
|
|
4403
|
+
const isDigit = (b) => b >= 48 && b <= 57;
|
|
4404
|
+
const isHex = (b) => isDigit(b) || b >= 65 && b <= 70 || b >= 97 && b <= 102;
|
|
4405
|
+
const numberDone = (s) => s === 1 || s === 2 || s === 4 || s === 7;
|
|
4406
|
+
var JsonMachine = class JsonMachine {
|
|
4407
|
+
stack = [];
|
|
4408
|
+
phase = 0;
|
|
4409
|
+
isKey = false;
|
|
4410
|
+
uLeft = 0;
|
|
4411
|
+
utf8Left = 0;
|
|
4412
|
+
numSub = 2;
|
|
4413
|
+
litWord = "";
|
|
4414
|
+
litPos = 0;
|
|
4415
|
+
clone() {
|
|
4416
|
+
const m = new JsonMachine();
|
|
4417
|
+
m.stack = this.stack.slice();
|
|
4418
|
+
m.phase = this.phase;
|
|
4419
|
+
m.isKey = this.isKey;
|
|
4420
|
+
m.uLeft = this.uLeft;
|
|
4421
|
+
m.utf8Left = this.utf8Left;
|
|
4422
|
+
m.numSub = this.numSub;
|
|
4423
|
+
m.litWord = this.litWord;
|
|
4424
|
+
m.litPos = this.litPos;
|
|
4425
|
+
return m;
|
|
4426
|
+
}
|
|
4427
|
+
get complete() {
|
|
4428
|
+
return this.phase === 12;
|
|
4429
|
+
}
|
|
4430
|
+
/** Feed bytes; false = the text stopped being a valid JSON prefix (state is then undefined). */
|
|
4431
|
+
feed(bytes) {
|
|
4432
|
+
for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
|
|
4433
|
+
return true;
|
|
4434
|
+
}
|
|
4435
|
+
openValue(b) {
|
|
4436
|
+
if (b === 123) {
|
|
4437
|
+
this.stack.push("{");
|
|
4438
|
+
this.phase = 3;
|
|
4439
|
+
} else if (b === 91) {
|
|
4440
|
+
this.stack.push("[");
|
|
4441
|
+
this.phase = 2;
|
|
4442
|
+
} else if (b === 34) {
|
|
4443
|
+
this.isKey = false;
|
|
4444
|
+
this.phase = 7;
|
|
4445
|
+
} else if (b === 45 || isDigit(b)) {
|
|
4446
|
+
this.numSub = b === 45 ? 0 : b === 48 ? 1 : 2;
|
|
4447
|
+
this.phase = 10;
|
|
4448
|
+
} else if (b === 116 || b === 102 || b === 110) {
|
|
4449
|
+
this.litWord = b === 116 ? "true" : b === 102 ? "false" : "null";
|
|
4450
|
+
this.litPos = 1;
|
|
4451
|
+
this.phase = 11;
|
|
4452
|
+
} else return false;
|
|
4453
|
+
return true;
|
|
4454
|
+
}
|
|
4455
|
+
closeValue() {
|
|
4456
|
+
this.phase = this.stack.length === 0 ? 12 : 6;
|
|
4457
|
+
}
|
|
4458
|
+
closeContainer(b) {
|
|
4459
|
+
const want = b === 125 ? "{" : "[";
|
|
4460
|
+
if (this.stack.pop() !== want) return false;
|
|
4461
|
+
this.closeValue();
|
|
4462
|
+
return true;
|
|
4463
|
+
}
|
|
4464
|
+
byte(b) {
|
|
4465
|
+
switch (this.phase) {
|
|
4466
|
+
case 0:
|
|
4467
|
+
if (WS.has(b)) return true;
|
|
4468
|
+
if (b === 123 || b === 91) return this.openValue(b);
|
|
4469
|
+
return false;
|
|
4470
|
+
case 1:
|
|
4471
|
+
if (WS.has(b)) return true;
|
|
4472
|
+
return this.openValue(b);
|
|
4473
|
+
case 2:
|
|
4474
|
+
if (WS.has(b)) return true;
|
|
4475
|
+
if (b === 93) return this.closeContainer(b);
|
|
4476
|
+
return this.openValue(b);
|
|
4477
|
+
case 3:
|
|
4478
|
+
if (WS.has(b)) return true;
|
|
4479
|
+
if (b === 125) return this.closeContainer(b);
|
|
4480
|
+
if (b === 34) {
|
|
4481
|
+
this.isKey = true;
|
|
4482
|
+
this.phase = 7;
|
|
4483
|
+
return true;
|
|
4484
|
+
}
|
|
4485
|
+
return false;
|
|
4486
|
+
case 4:
|
|
4487
|
+
if (WS.has(b)) return true;
|
|
4488
|
+
if (b === 34) {
|
|
4489
|
+
this.isKey = true;
|
|
4490
|
+
this.phase = 7;
|
|
4491
|
+
return true;
|
|
4492
|
+
}
|
|
4493
|
+
return false;
|
|
4494
|
+
case 5:
|
|
4495
|
+
if (WS.has(b)) return true;
|
|
4496
|
+
if (b === 58) {
|
|
4497
|
+
this.phase = 1;
|
|
4498
|
+
return true;
|
|
4499
|
+
}
|
|
4500
|
+
return false;
|
|
4501
|
+
case 6: {
|
|
4502
|
+
if (WS.has(b)) return true;
|
|
4503
|
+
const top = this.stack[this.stack.length - 1];
|
|
4504
|
+
if (b === 44) {
|
|
4505
|
+
this.phase = top === "{" ? 4 : 1;
|
|
4506
|
+
return true;
|
|
4507
|
+
}
|
|
4508
|
+
if (b === 125 && top === "{" || b === 93 && top === "[") return this.closeContainer(b);
|
|
4509
|
+
return false;
|
|
4510
|
+
}
|
|
4511
|
+
case 7:
|
|
4512
|
+
if (this.utf8Left > 0) {
|
|
4513
|
+
if (b >= 128 && b <= 191) {
|
|
4514
|
+
this.utf8Left--;
|
|
4515
|
+
return true;
|
|
4516
|
+
}
|
|
4517
|
+
return false;
|
|
4518
|
+
}
|
|
4519
|
+
if (b === 34) {
|
|
4520
|
+
if (this.isKey) {
|
|
4521
|
+
this.isKey = false;
|
|
4522
|
+
this.phase = 5;
|
|
4523
|
+
} else this.closeValue();
|
|
4524
|
+
return true;
|
|
4525
|
+
}
|
|
4526
|
+
if (b === 92) {
|
|
4527
|
+
this.phase = 8;
|
|
4528
|
+
return true;
|
|
4529
|
+
}
|
|
4530
|
+
if (b < 32) return false;
|
|
4531
|
+
if (b < 128) return true;
|
|
4532
|
+
if (b >= 194 && b <= 223) this.utf8Left = 1;
|
|
4533
|
+
else if (b >= 224 && b <= 239) this.utf8Left = 2;
|
|
4534
|
+
else if (b >= 240 && b <= 244) this.utf8Left = 3;
|
|
4535
|
+
else return false;
|
|
4536
|
+
return true;
|
|
4537
|
+
case 8:
|
|
4538
|
+
if (b === 117) {
|
|
4539
|
+
this.uLeft = 4;
|
|
4540
|
+
this.phase = 9;
|
|
4541
|
+
return true;
|
|
4542
|
+
}
|
|
4543
|
+
if ([
|
|
4544
|
+
34,
|
|
4545
|
+
92,
|
|
4546
|
+
47,
|
|
4547
|
+
98,
|
|
4548
|
+
102,
|
|
4549
|
+
110,
|
|
4550
|
+
114,
|
|
4551
|
+
116
|
|
4552
|
+
].includes(b)) {
|
|
4553
|
+
this.phase = 7;
|
|
4554
|
+
return true;
|
|
4555
|
+
}
|
|
4556
|
+
return false;
|
|
4557
|
+
case 9:
|
|
4558
|
+
if (!isHex(b)) return false;
|
|
4559
|
+
if (--this.uLeft === 0) this.phase = 7;
|
|
4560
|
+
return true;
|
|
4561
|
+
case 10:
|
|
4562
|
+
switch (this.numSub) {
|
|
4563
|
+
case 0:
|
|
4564
|
+
if (!isDigit(b)) return false;
|
|
4565
|
+
this.numSub = b === 48 ? 1 : 2;
|
|
4566
|
+
return true;
|
|
4567
|
+
case 1:
|
|
4568
|
+
case 2:
|
|
4569
|
+
if (isDigit(b)) {
|
|
4570
|
+
if (this.numSub === 1) return false;
|
|
4571
|
+
return true;
|
|
4572
|
+
}
|
|
4573
|
+
break;
|
|
4574
|
+
case 3:
|
|
4575
|
+
if (!isDigit(b)) return false;
|
|
4576
|
+
this.numSub = 4;
|
|
4577
|
+
return true;
|
|
4578
|
+
case 4:
|
|
4579
|
+
if (isDigit(b)) return true;
|
|
4580
|
+
break;
|
|
4581
|
+
case 5:
|
|
4582
|
+
if (b === 43 || b === 45) {
|
|
4583
|
+
this.numSub = 6;
|
|
4584
|
+
return true;
|
|
4585
|
+
}
|
|
4586
|
+
if (!isDigit(b)) return false;
|
|
4587
|
+
this.numSub = 7;
|
|
4588
|
+
return true;
|
|
4589
|
+
case 6:
|
|
4590
|
+
if (!isDigit(b)) return false;
|
|
4591
|
+
this.numSub = 7;
|
|
4592
|
+
return true;
|
|
4593
|
+
case 7:
|
|
4594
|
+
if (isDigit(b)) return true;
|
|
4595
|
+
break;
|
|
4596
|
+
}
|
|
4597
|
+
if (b === 46 && (this.numSub === 1 || this.numSub === 2)) {
|
|
4598
|
+
this.numSub = 3;
|
|
4599
|
+
return true;
|
|
4600
|
+
}
|
|
4601
|
+
if ((b === 101 || b === 69) && numberDone(this.numSub) && this.numSub !== 7) {
|
|
4602
|
+
this.numSub = 5;
|
|
4603
|
+
return true;
|
|
4604
|
+
}
|
|
4605
|
+
if (numberDone(this.numSub)) {
|
|
4606
|
+
this.closeValue();
|
|
4607
|
+
return this.byte(b);
|
|
4608
|
+
}
|
|
4609
|
+
return false;
|
|
4610
|
+
case 11:
|
|
4611
|
+
if (b !== this.litWord.charCodeAt(this.litPos)) return false;
|
|
4612
|
+
if (++this.litPos === this.litWord.length) this.closeValue();
|
|
4613
|
+
return true;
|
|
4614
|
+
case 12: return WS.has(b);
|
|
4615
|
+
}
|
|
4616
|
+
}
|
|
4617
|
+
};
|
|
4618
|
+
function aliasToByte() {
|
|
4619
|
+
const bs = [];
|
|
4620
|
+
for (let i = 33; i <= 126; i++) bs.push(i);
|
|
4621
|
+
for (let i = 161; i <= 172; i++) bs.push(i);
|
|
4622
|
+
for (let i = 174; i <= 255; i++) bs.push(i);
|
|
4623
|
+
const cs = [...bs];
|
|
4624
|
+
let n = 0;
|
|
4625
|
+
for (let b = 0; b < 256; b++) if (!bs.includes(b)) {
|
|
4626
|
+
bs.push(b);
|
|
4627
|
+
cs.push(256 + n);
|
|
4628
|
+
n++;
|
|
4629
|
+
}
|
|
4630
|
+
return new Map(bs.map((b, i) => [cs[i], b]));
|
|
4631
|
+
}
|
|
4632
|
+
/** Precomputed id -> raw bytes lookup (lazy per id; added/special tokens map to null). */
|
|
4633
|
+
var TokenByteTable = class {
|
|
4634
|
+
tk;
|
|
4635
|
+
cache = /* @__PURE__ */ new Map();
|
|
4636
|
+
inv = aliasToByte();
|
|
4637
|
+
added;
|
|
4638
|
+
constructor(tk) {
|
|
4639
|
+
this.tk = tk;
|
|
4640
|
+
this.added = tk.addedTokenIds();
|
|
4641
|
+
}
|
|
4642
|
+
bytes(id) {
|
|
4643
|
+
const hit = this.cache.get(id);
|
|
4644
|
+
if (hit !== void 0) return hit;
|
|
4645
|
+
let out = null;
|
|
4646
|
+
if (!this.added.has(id)) {
|
|
4647
|
+
const s = this.tk.idToToken(id);
|
|
4648
|
+
if (s !== void 0) {
|
|
4649
|
+
const b = new Uint8Array(s.length);
|
|
4650
|
+
let ok = true;
|
|
4651
|
+
for (let i = 0; i < s.length; i++) {
|
|
4652
|
+
const v = this.inv.get(s.charCodeAt(i));
|
|
4653
|
+
if (v === void 0) {
|
|
4654
|
+
ok = false;
|
|
4655
|
+
break;
|
|
4656
|
+
}
|
|
4657
|
+
b[i] = v;
|
|
4658
|
+
}
|
|
4659
|
+
out = ok ? b : null;
|
|
4660
|
+
}
|
|
4661
|
+
}
|
|
4662
|
+
this.cache.set(id, out);
|
|
4663
|
+
return out;
|
|
4664
|
+
}
|
|
4665
|
+
};
|
|
4666
|
+
/** The per-step candidate filter for format:'json': permit candidates whose bytes keep the text
|
|
4667
|
+
* a valid JSON prefix; once the root value is complete, permit ONLY eos so generation ends
|
|
4668
|
+
* naturally. Call advance() with each chosen token to move the real machine forward. */
|
|
4669
|
+
function makeJsonFilter(table, eosTokenId) {
|
|
4670
|
+
const machine = new JsonMachine();
|
|
4671
|
+
return {
|
|
4672
|
+
machine,
|
|
4673
|
+
filter: (ids) => {
|
|
4674
|
+
const out = [];
|
|
4675
|
+
for (const id of ids) {
|
|
4676
|
+
if (machine.complete) {
|
|
4677
|
+
if (id === eosTokenId) out.push(Number(id));
|
|
4678
|
+
continue;
|
|
4679
|
+
}
|
|
4680
|
+
const bytes = table.bytes(Number(id));
|
|
4681
|
+
if (!bytes || bytes.length === 0) continue;
|
|
4682
|
+
if (machine.clone().feed(bytes)) out.push(Number(id));
|
|
4683
|
+
}
|
|
4684
|
+
return out;
|
|
4685
|
+
},
|
|
4686
|
+
advance: (id) => {
|
|
4687
|
+
if (machine.complete) return;
|
|
4688
|
+
const bytes = table.bytes(id);
|
|
4689
|
+
if (bytes) machine.feed(bytes);
|
|
4690
|
+
}
|
|
4691
|
+
};
|
|
4692
|
+
}
|
|
4693
|
+
//#endregion
|
|
4694
|
+
//#region src/chat/index.ts
|
|
4695
|
+
function deriveChatWrap(tk) {
|
|
4696
|
+
if (!tk.hasChatTemplate) return null;
|
|
4697
|
+
try {
|
|
4698
|
+
const render = (msgs, agp) => tk.applyChatTemplate(msgs, {
|
|
4699
|
+
addGenerationPrompt: agp,
|
|
4700
|
+
enableThinking: false
|
|
4701
|
+
});
|
|
4702
|
+
const SENT = "BITGPUSENTINEL";
|
|
4703
|
+
const userOnly = render([{
|
|
4704
|
+
role: "user",
|
|
4705
|
+
content: SENT
|
|
4706
|
+
}], false);
|
|
4707
|
+
const userGen = render([{
|
|
4708
|
+
role: "user",
|
|
4709
|
+
content: SENT
|
|
4710
|
+
}], true);
|
|
4711
|
+
const genPrompt = userGen.slice(userOnly.length);
|
|
4712
|
+
const i = userOnly.indexOf(SENT);
|
|
4713
|
+
if (i < 0 || !userGen.startsWith(userOnly) || !genPrompt.includes("assistant")) return null;
|
|
4714
|
+
const userPrefix = userOnly.slice(0, i);
|
|
4715
|
+
const userSuffix = userOnly.slice(i + 14);
|
|
4716
|
+
if (!userSuffix.includes(tk.eosToken)) return null;
|
|
4717
|
+
return {
|
|
4718
|
+
genPrompt,
|
|
4719
|
+
userPrefix,
|
|
4720
|
+
userSuffix
|
|
4721
|
+
};
|
|
4722
|
+
} catch {
|
|
4723
|
+
return null;
|
|
4724
|
+
}
|
|
4725
|
+
}
|
|
4726
|
+
/** True iff `next` is exactly `committed` plus one new trailing user turn - a clean append, so the
|
|
4727
|
+
* engine can extend its KV cache with just that turn. Compared as MESSAGES, not token ids: chat
|
|
4728
|
+
* templates render past assistant turns differently from live ones (e.g. Qwen3's empty <think>
|
|
4729
|
+
* block), so a re-tokenized history is never a token-prefix of what the cache holds. */
|
|
4730
|
+
function isCleanAppend(committed, next) {
|
|
4731
|
+
if (!committed || next.length !== committed.length + 1) return false;
|
|
4732
|
+
if (next[next.length - 1].role !== "user") return false;
|
|
4733
|
+
for (let i = 0; i < committed.length; i++) if (next[i].role !== committed[i].role || next[i].content !== committed[i].content) return false;
|
|
4734
|
+
return true;
|
|
4735
|
+
}
|
|
4736
|
+
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
4737
|
+
async function createChat(engine, options) {
|
|
4738
|
+
let tk;
|
|
4739
|
+
if (options.tokenizer) tk = new ChatTokenizer(options.tokenizer.json, options.tokenizer.config);
|
|
4740
|
+
else {
|
|
4741
|
+
const base = options.modelUrl?.replace(/\/$/, "");
|
|
4742
|
+
const jsonUrl = options.tokenizerJsonUrl ?? (base ? `${base}/tokenizer.json` : null);
|
|
4743
|
+
const cfgUrl = options.tokenizerConfigUrl ?? (base ? `${base}/tokenizer_config.json` : null);
|
|
4744
|
+
if (!jsonUrl || !cfgUrl) throw new Error("bitgpu/chat: provide modelUrl, tokenizerJsonUrl+tokenizerConfigUrl, or a preloaded tokenizer");
|
|
4745
|
+
const get = options.fetchJson ?? (async (url) => {
|
|
4746
|
+
const res = await fetch(url);
|
|
4747
|
+
if (!res.ok) throw new Error(`bitgpu/chat: fetch ${url} failed: HTTP ${res.status}`);
|
|
4748
|
+
return res.json();
|
|
4749
|
+
});
|
|
4750
|
+
const [json, cfg] = await Promise.all([get(jsonUrl), get(cfgUrl)]);
|
|
4751
|
+
tk = new ChatTokenizer(json, cfg);
|
|
4752
|
+
}
|
|
4753
|
+
const wrap = deriveChatWrap(tk);
|
|
4754
|
+
let committed = null;
|
|
4755
|
+
let cacheEndsAtEos = false;
|
|
4756
|
+
let resetEpoch = 0;
|
|
4757
|
+
const dropCache = () => {
|
|
4758
|
+
committed = null;
|
|
4759
|
+
engine.resetCache();
|
|
4760
|
+
};
|
|
4761
|
+
let chain = Promise.resolve();
|
|
4762
|
+
const serialize = (fn) => {
|
|
4763
|
+
return (...args) => {
|
|
4764
|
+
const run = chain.then(() => fn(...args), () => fn(...args));
|
|
4765
|
+
chain = run.catch(() => void 0);
|
|
4766
|
+
return run;
|
|
4767
|
+
};
|
|
4768
|
+
};
|
|
4769
|
+
let byteTable = null;
|
|
4770
|
+
async function sendImpl(messages, o = {}) {
|
|
4771
|
+
if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
|
|
4772
|
+
const json = o.format === "json";
|
|
4773
|
+
const think = !json && (o.think ?? false);
|
|
4774
|
+
const canReuse = (o.reuseCache ?? true) && !think && wrap !== null && isCleanAppend(committed, messages);
|
|
4775
|
+
let inputTokenIds;
|
|
4776
|
+
if (canReuse) {
|
|
4777
|
+
const w = wrap;
|
|
4778
|
+
const userText = messages[messages.length - 1].content;
|
|
4779
|
+
const deltaStr = `${cacheEndsAtEos ? "" : tk.eosToken}\n${w.userPrefix}${userText}${w.userSuffix}${w.genPrompt}`;
|
|
4780
|
+
inputTokenIds = tk.encode(deltaStr, false);
|
|
4781
|
+
} else {
|
|
4782
|
+
dropCache();
|
|
4783
|
+
inputTokenIds = tk.encode(tk.applyChatTemplate(messages, {
|
|
4784
|
+
addGenerationPrompt: true,
|
|
4785
|
+
enableThinking: think
|
|
4786
|
+
}), false);
|
|
4787
|
+
}
|
|
4788
|
+
const decoder = tk.createDecoderStream(true);
|
|
4789
|
+
const splitter = new ThinkSplitter();
|
|
4790
|
+
const stops = o.stopSequences?.length ? new StopScanner(o.stopSequences) : null;
|
|
4791
|
+
const stopCtl = stops ? new AbortController() : null;
|
|
4792
|
+
const signal = stopCtl ? o.signal ? AbortSignal.any([o.signal, stopCtl.signal]) : stopCtl.signal : o.signal;
|
|
4793
|
+
let text = "";
|
|
4794
|
+
let thinkText = "";
|
|
4795
|
+
const emit = (chunk) => {
|
|
4796
|
+
if (chunk.text) {
|
|
4797
|
+
const visible = stops ? stops.push(chunk.text) : chunk.text;
|
|
4798
|
+
if (visible) {
|
|
4799
|
+
text += visible;
|
|
4800
|
+
o.onText?.(visible);
|
|
4801
|
+
}
|
|
4802
|
+
if (stops?.matched) stopCtl?.abort();
|
|
4803
|
+
}
|
|
4804
|
+
if (chunk.think) {
|
|
4805
|
+
thinkText += chunk.think;
|
|
4806
|
+
o.onThink?.(chunk.think);
|
|
4807
|
+
}
|
|
4808
|
+
};
|
|
4809
|
+
const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
|
|
4810
|
+
const epoch0 = resetEpoch;
|
|
4811
|
+
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId) : null;
|
|
4812
|
+
let result;
|
|
4813
|
+
try {
|
|
4814
|
+
result = await engine.generate(inputTokenIds, {
|
|
4815
|
+
maxTokens,
|
|
4816
|
+
temperature: o.temperature,
|
|
4817
|
+
topK: o.topK,
|
|
4818
|
+
topP: o.topP,
|
|
4819
|
+
repetitionPenalty: o.repetitionPenalty,
|
|
4820
|
+
noRepeatNgramSize: o.noRepeatNgramSize,
|
|
4821
|
+
seed: o.seed,
|
|
4822
|
+
promptLookup: json ? false : o.promptLookup,
|
|
4823
|
+
stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
|
|
4824
|
+
reuseCache: canReuse,
|
|
4825
|
+
signal,
|
|
4826
|
+
candidateFilter: jf ? (ids) => jf.filter(ids) : void 0,
|
|
4827
|
+
onToken: (id) => {
|
|
4828
|
+
jf?.advance(id);
|
|
4829
|
+
emit(splitter.push(decoder.push(id)));
|
|
4830
|
+
}
|
|
4831
|
+
});
|
|
4832
|
+
} catch (err) {
|
|
4833
|
+
if (/maxSeqLen/.test(err.message)) {
|
|
4834
|
+
if (o.onOverflow) {
|
|
4835
|
+
const trimmed = o.onOverflow({
|
|
4836
|
+
promptTokenCount: inputTokenIds.length,
|
|
4837
|
+
maxSeqLen: engine.capabilities.maxSeqLen
|
|
4838
|
+
});
|
|
4839
|
+
if (trimmed && trimmed.length > 0) {
|
|
4840
|
+
dropCache();
|
|
4841
|
+
return await sendImpl(trimmed, {
|
|
4842
|
+
...o,
|
|
4843
|
+
onOverflow: void 0,
|
|
4844
|
+
reuseCache: false
|
|
4845
|
+
});
|
|
4846
|
+
}
|
|
4847
|
+
}
|
|
4848
|
+
} else dropCache();
|
|
4849
|
+
throw err;
|
|
4850
|
+
}
|
|
4851
|
+
emit(splitter.push(decoder.flush()));
|
|
4852
|
+
emit(splitter.flush());
|
|
4853
|
+
const aborted = o.signal?.aborted ?? false;
|
|
4854
|
+
if (aborted || stops?.matched) dropCache();
|
|
4855
|
+
else if (think) dropCache();
|
|
4856
|
+
else if (wrap !== null && text.trim() && resetEpoch === epoch0) {
|
|
4857
|
+
committed = [...messages, {
|
|
4858
|
+
role: "assistant",
|
|
4859
|
+
content: text
|
|
4860
|
+
}];
|
|
4861
|
+
cacheEndsAtEos = false;
|
|
4862
|
+
} else dropCache();
|
|
4863
|
+
return {
|
|
4864
|
+
text,
|
|
4865
|
+
thinkText,
|
|
4866
|
+
tokens: result.tokens,
|
|
4867
|
+
inputTokenIds,
|
|
4868
|
+
finishReason: aborted ? "abort" : stops?.matched ? "stop" : result.tokens.length >= maxTokens ? "length" : "stop",
|
|
4869
|
+
reusedCache: canReuse,
|
|
4870
|
+
prefillMs: result.prefillMs,
|
|
4871
|
+
decodeMs: result.decodeMs,
|
|
4872
|
+
tokensPerSecond: result.tokensPerSecond
|
|
4873
|
+
};
|
|
4874
|
+
}
|
|
4875
|
+
const send = serialize(sendImpl);
|
|
4876
|
+
async function prewarmImpl(messages) {
|
|
4877
|
+
if (wrap === null) return;
|
|
4878
|
+
const str = tk.applyChatTemplate(messages, {
|
|
4879
|
+
addGenerationPrompt: false,
|
|
4880
|
+
enableThinking: false
|
|
4881
|
+
}).replace(/\n$/, "");
|
|
4882
|
+
const epoch0 = resetEpoch;
|
|
4883
|
+
await engine.prefill(tk.encode(str, false));
|
|
4884
|
+
if (resetEpoch !== epoch0) return;
|
|
4885
|
+
committed = [...messages];
|
|
4886
|
+
cacheEndsAtEos = true;
|
|
4887
|
+
}
|
|
4888
|
+
return {
|
|
4889
|
+
send,
|
|
4890
|
+
stream(messages, options = {}) {
|
|
4891
|
+
const queue = [];
|
|
4892
|
+
let notify = null;
|
|
4893
|
+
const wake = () => {
|
|
4894
|
+
notify?.();
|
|
4895
|
+
notify = null;
|
|
4896
|
+
};
|
|
4897
|
+
let done = false;
|
|
4898
|
+
let result = null;
|
|
4899
|
+
let error = null;
|
|
4900
|
+
const run = send(messages, {
|
|
4901
|
+
...options,
|
|
4902
|
+
onText: (d) => {
|
|
4903
|
+
options.onText?.(d);
|
|
4904
|
+
queue.push(d);
|
|
4905
|
+
wake();
|
|
4906
|
+
}
|
|
4907
|
+
}).then((r) => {
|
|
4908
|
+
result = r;
|
|
4909
|
+
}).catch((e) => {
|
|
4910
|
+
error = e;
|
|
4911
|
+
}).finally(() => {
|
|
4912
|
+
done = true;
|
|
4913
|
+
wake();
|
|
4914
|
+
});
|
|
4915
|
+
async function* gen() {
|
|
4916
|
+
for (;;) {
|
|
4917
|
+
if (queue.length > 0) {
|
|
4918
|
+
yield queue.shift();
|
|
4919
|
+
continue;
|
|
4920
|
+
}
|
|
4921
|
+
if (done) break;
|
|
4922
|
+
await new Promise((r) => notify = r);
|
|
4923
|
+
}
|
|
4924
|
+
await run;
|
|
4925
|
+
if (error) throw error;
|
|
4926
|
+
return result;
|
|
4927
|
+
}
|
|
4928
|
+
return gen();
|
|
4929
|
+
},
|
|
4930
|
+
prewarm: serialize(prewarmImpl),
|
|
4931
|
+
countTokens: (messages, opts) => tk.encode(tk.applyChatTemplate(messages, {
|
|
4932
|
+
addGenerationPrompt: opts?.addGenerationPrompt ?? true,
|
|
4933
|
+
enableThinking: opts?.think ?? false
|
|
4934
|
+
}), false).length,
|
|
4935
|
+
reset: () => {
|
|
4936
|
+
resetEpoch++;
|
|
4937
|
+
dropCache();
|
|
4938
|
+
},
|
|
4939
|
+
eosTokenId: tk.eosTokenId,
|
|
4940
|
+
tokenizer: tk
|
|
4941
|
+
};
|
|
4942
|
+
}
|
|
4943
|
+
//#endregion
|
|
4944
|
+
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat };
|
|
4945
|
+
|
|
4946
|
+
//# sourceMappingURL=chat.js.map
|