@cat-of-summer/st-script 1.0.3 → 1.0.5

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.
@@ -0,0 +1,425 @@
1
+ const SLOTS = { '0': /^[0-9]$/, 'a': /^\p{L}$/u, '*': /^[^\n]$/ };
2
+
3
+ const unesc = str => str.replace(/\\(.)/g, '$1');
4
+ const no_g = re => re.global ? new RegExp(re.source, re.flags.replace('g', '')) : re;
5
+
6
+ function scan(str, from) {
7
+ let open = str[from], close = open == '{' ? '}' : ']', depth = 0;
8
+ for (let i = from; i < str.length; i++) {
9
+ let c = str[i];
10
+ if (c == '\\') { i++; continue; }
11
+ if (open == '[' && c == '{') {
12
+ if ((i = scan(str, i)) < 0) return -1;
13
+ } else if (c == open) depth++;
14
+ else if (c == close && --depth == 0) return i;
15
+ }
16
+ return -1;
17
+ }
18
+
19
+ function last_top(body, needle) {
20
+ let depth = 0, found = -1;
21
+ for (let i = 0; i < body.length; i++) {
22
+ if (body[i] == '\\') { i++; continue; }
23
+ if (body[i] == '{' || body[i] == '[') depth++;
24
+ else if (body[i] == '}' || body[i] == ']') depth--;
25
+ else if (depth == 0 && body.startsWith(needle, i)) found = i;
26
+ }
27
+ return found;
28
+ }
29
+
30
+ function classify(body) {
31
+ let fail = () => {
32
+ console.warn('Некорректный блок маски', `{${body}}`);
33
+ return [...`{${body}}`].map(char => ({ type: 'literal', char }));
34
+ };
35
+
36
+ let semi = last_top(body, ';');
37
+ if (semi > 0) {
38
+ let range = body.slice(semi + 1);
39
+ if (/^(\d+|\d*-\d*)$/.test(range) && range != '-') {
40
+ let [min, max] = /^\d+$/.test(range)
41
+ ? [+range, +range]
42
+ : range.split('-').map((n, i) => n === '' ? (i ? Infinity : 0) : +n);
43
+ return max < min ? fail()
44
+ : [{ type: 'repeat', children: compile(body.slice(0, semi)), min, max }];
45
+ }
46
+ }
47
+
48
+ if (body[0] == '{' && body.at(-1) == '}')
49
+ try {
50
+ return [{ type: 'slot', test: new RegExp(`^(?:${body.slice(1, -1)})$`, 'u') }];
51
+ } catch { return fail(); }
52
+
53
+ let arrow = last_top(body, '=>');
54
+ if (arrow > 0) {
55
+ let from = unesc(body.slice(0, arrow)), to = unesc(body.slice(arrow + 2));
56
+ return from.length != 1 || !to ? fail() : [{ type: 'transform', from, to }];
57
+ }
58
+
59
+ return fail();
60
+ }
61
+
62
+ export function compile(pattern) {
63
+ let nodes = [];
64
+
65
+ for (let i = 0; i < pattern.length; i++) {
66
+ let char = pattern[i], end;
67
+
68
+ if (char == '\\')
69
+ nodes.push({ type: 'literal', char: pattern[++i] ?? '\\' });
70
+ else if (char == '[' && (end = scan(pattern, i)) >= 0) {
71
+ nodes.push({ type: 'optional', children: compile(pattern.slice(i + 1, end)) });
72
+ i = end;
73
+ } else if (char == '{' && (end = scan(pattern, i)) >= 0) {
74
+ nodes.push(...classify(pattern.slice(i + 1, end)));
75
+ i = end;
76
+ } else
77
+ nodes.push(SLOTS[char] ? { type: 'slot', test: SLOTS[char] } : { type: 'literal', char });
78
+ }
79
+
80
+ return nodes;
81
+ }
82
+
83
+ function is_fixed(nodes) {
84
+ return nodes.every(node =>
85
+ node.type == 'literal' || node.type == 'slot'
86
+ || node.type == 'repeat' && node.min == node.max && is_fixed(node.children));
87
+ }
88
+
89
+ export function build(mask, base = {}) {
90
+ if (mask && typeof mask == 'object' && !Array.isArray(mask) && !(mask instanceof RegExp)
91
+ && mask.pattern == null && mask.filter == null && mask.numeral == null)
92
+ return Object.entries(mask).flatMap(([key, m]) =>
93
+ build(m, base).map(def => ({ ...def, key })));
94
+
95
+ let defs = (Array.isArray(mask) ? mask : [mask]).map(m => {
96
+ if (typeof m == 'function') return { fn: m, base };
97
+ if (m instanceof RegExp) m = { filter: m };
98
+ if (typeof m == 'string') m = { pattern: m };
99
+
100
+ if (m.numeral) {
101
+ let o = { fraction: 0, group: ' ', decimal: ',', prefix: '', suffix: '', sign: false, ...m.numeral };
102
+ return { numeral: o, fixed: false, valid: null, message: m.message ?? o.message,
103
+ filler: m.filler ?? base.filler, before_char: null, before_slot: null };
104
+ }
105
+
106
+ let nodes = m.pattern != null
107
+ ? compile(m.pattern)
108
+ : [{ type: 'repeat', min: 0, max: m.max_length ?? Infinity, greedy: true,
109
+ children: [{ type: 'slot', test: no_g(m.filter) }] }];
110
+
111
+ return {
112
+ nodes,
113
+ fixed: m.pattern != null && is_fixed(nodes),
114
+ valid: m.valid ? no_g(m.valid) : (m.filter ? /./ : null),
115
+ message: m.message,
116
+ filler: m.filler ?? base.filler,
117
+ before_char: m.before_char ?? base.before_char,
118
+ before_slot: m.before_slot ?? base.before_slot
119
+ };
120
+ });
121
+
122
+ defs.forEach((def, i) => def.key ??= i);
123
+ return defs;
124
+ }
125
+
126
+ export function filler(def, ordinal) {
127
+ let f = def.filler ?? '_';
128
+ return f[ordinal] ?? f.at(-1) ?? '_';
129
+ }
130
+
131
+ export function prepare(def, input_string, ctx) {
132
+ let chars = [...String(input_string ?? '')];
133
+ if (!def.before_char) return chars;
134
+
135
+ return chars.flatMap(char => {
136
+ let out = def.before_char(ctx?.input, { char });
137
+ if (out === false || out === '' || out === null) return [];
138
+ return typeof out == 'string' ? [...out] : [char];
139
+ });
140
+ }
141
+
142
+ function takes(node, c, s) {
143
+ if (node.type == 'slot') return node.test.test(c);
144
+ if (node.type == 'transform') return node.from === c || s.input.slice(s.ip, s.ip + node.to.length).join('') === node.to;
145
+ if (node.type == 'repeat') return consumes(node.children, c, s);
146
+ return false;
147
+ }
148
+
149
+ function consumes(nodes, c, s, entry) {
150
+ for (let node of nodes) {
151
+ if (node.type == 'literal') {
152
+ if (!entry && node.char === c) return true;
153
+ continue;
154
+ }
155
+ if (node.type == 'optional' || node.type == 'repeat' && node.min == 0) {
156
+ if (consumes(node.children, c, s, entry)) return true;
157
+ continue;
158
+ }
159
+ return takes(node, c, s);
160
+ }
161
+ return entry ? nodes.some(node => node.type == 'literal' && node.char === c) : false;
162
+ }
163
+
164
+ function accept(s, text, fmt_text, kind = 'char', ordinal = null) {
165
+ s.units.push({
166
+ kind, ordinal,
167
+ stream_start: s.stream.length, stream_end: s.stream.length + text.length,
168
+ fmt_start: s.formatted.length, fmt_end: s.formatted.length + fmt_text.length
169
+ });
170
+ s.stream += text;
171
+ if (kind == 'char') s.raw += text;
172
+ if (ordinal != null) s.cells[ordinal] = kind == 'char' ? text : null;
173
+ s.formatted += fmt_text;
174
+ }
175
+
176
+ function stop(s) {
177
+ if (s.stop_fmt < 0) s.stop_fmt = s.formatted.length + s.tail.length;
178
+ }
179
+
180
+ function exhaust(s) {
181
+ s.complete = false;
182
+ s.done = true;
183
+ stop(s);
184
+ }
185
+
186
+ function walk(nodes, s, def) {
187
+ for (let i = 0; i < nodes.length; i++) {
188
+ let node = nodes[i];
189
+
190
+ if (node.type == 'literal') {
191
+ if (s.done) s.ph += node.char;
192
+ else if (s.ip < s.input.length) {
193
+ if (s.input[s.ip] === node.char) {
194
+ s.ip++;
195
+ s.consumed++;
196
+ accept(s, node.char, node.char, 'literal');
197
+ } else
198
+ s.formatted += node.char;
199
+ } else s.tail += node.char;
200
+
201
+ } else if (node.type == 'slot') {
202
+ let ordinal = s.ordinal++, fill = filler(def, ordinal);
203
+ if (s.done) {
204
+ s.ph_slots.push({ fmt: s.formatted.length + s.tail.length + s.ph.length, node });
205
+ s.ph += fill;
206
+ continue;
207
+ }
208
+ let no_fix = false;
209
+ for (;;) {
210
+ if (s.ip >= s.input.length) {
211
+ exhaust(s);
212
+ s.ph_slots.push({ fmt: s.formatted.length + s.tail.length, node });
213
+ s.ph += fill;
214
+ break;
215
+ }
216
+ let c = s.input[s.ip];
217
+ if (node.test.test(c)) {
218
+ if (def.before_slot && !no_fix) {
219
+ let out = def.before_slot(s.ctx?.input,
220
+ { char: c, slot: ordinal, cells: s.cells, raw: s.raw, node });
221
+ if (out === false) { s.ip++; continue; }
222
+ if (typeof out == 'string' && out !== c) {
223
+ s.input.splice(s.ip, 1, ...out);
224
+ no_fix = true;
225
+ continue;
226
+ }
227
+ }
228
+ accept(s, c, c, 'char', ordinal);
229
+ } else if (c === fill) {
230
+ s.complete = false;
231
+ accept(s, c, c, 'hole', ordinal);
232
+ } else { s.ip++; continue; }
233
+ s.ip++;
234
+ s.consumed++;
235
+ break;
236
+ }
237
+
238
+ } else if (node.type == 'transform') {
239
+ if (s.done) { s.ph += node.to; continue; }
240
+ for (;;) {
241
+ if (s.ip >= s.input.length) {
242
+ exhaust(s);
243
+ s.ph += node.to;
244
+ break;
245
+ }
246
+ if (s.input.slice(s.ip, s.ip + node.to.length).join('') === node.to)
247
+ s.ip += node.to.length, s.consumed += node.to.length;
248
+ else if (s.input[s.ip] === node.from)
249
+ s.ip++, s.consumed++;
250
+ else { s.ip++; continue; }
251
+ accept(s, node.to, node.to);
252
+ break;
253
+ }
254
+
255
+ } else if (node.type == 'repeat') {
256
+ if (s.done) {
257
+ for (let k = 0; k < node.min; k++) walk(node.children, s, def);
258
+ continue;
259
+ }
260
+ let count = 0;
261
+ while (count < node.max) {
262
+ if (s.ip >= s.input.length) {
263
+ if (count < node.min) {
264
+ exhaust(s);
265
+ for (let k = count; k < node.min; k++) walk(node.children, s, def);
266
+ } else stop(s);
267
+ break;
268
+ }
269
+ if (!consumes(node.children, s.input[s.ip], s)) {
270
+ if (!node.greedy && count >= node.min) break;
271
+ s.ip++;
272
+ continue;
273
+ }
274
+ let before = s.ip;
275
+ walk(node.children, s, def);
276
+ if (s.done) {
277
+ for (let k = count + 1; k < node.min; k++) walk(node.children, s, def);
278
+ break;
279
+ }
280
+ if (s.ip === before) break;
281
+ count++;
282
+ }
283
+
284
+ } else if (node.type == 'optional') {
285
+ if (s.done) continue;
286
+ let rest = nodes.slice(i + 1), entered = false;
287
+ while (s.ip < s.input.length) {
288
+ let c = s.input[s.ip];
289
+ if (consumes(node.children, c, s, true)) {
290
+ entered = true;
291
+ walk(node.children, s, def);
292
+ break;
293
+ }
294
+ if (consumes(rest, c, s)) break;
295
+ s.ip++;
296
+ }
297
+ if (!entered && s.ip >= s.input.length) stop(s);
298
+ }
299
+ }
300
+ }
301
+
302
+ function numeral(def, input_string) {
303
+ let o = def.numeral;
304
+ let str = String(input_string ?? '');
305
+ let neg = o.sign && str.includes('-');
306
+
307
+ let digits;
308
+ if (o.decimal && (str.includes(o.decimal) || str.includes('.'))) {
309
+ let esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
310
+ let num = str.replace(new RegExp(`[^0-9${esc(o.decimal)}.]`, 'g'), '').replace(o.decimal, '.');
311
+ let val = parseFloat(num);
312
+ digits = Number.isFinite(val) ? String(Math.round(val * 10 ** o.fraction)) : '';
313
+ } else {
314
+ let ds = str.replace(/\D/g, '');
315
+ digits = ds === '' ? '' : (ds.replace(/^0+/, '') || '0');
316
+ }
317
+
318
+ if (!digits) {
319
+ let body = o.prefix + filler(def, 0);
320
+ if (o.fraction) {
321
+ body += o.decimal;
322
+ for (let i = 1; i <= o.fraction; i++) body += filler(def, i);
323
+ }
324
+ return { stream: '', raw: '', formatted: '', tail: '', ph: body + o.suffix,
325
+ ph_slots: [], complete: false, consumed: 0, units: [], cells: [], stop_fmt: body.length };
326
+ }
327
+
328
+ let f = o.fraction;
329
+ let padded = digits.padStart(f + 1, '0');
330
+ let int = (f ? padded.slice(0, -f) : padded).replace(/^0+(?=\d)/, '');
331
+ let frac = f ? padded.slice(-f) : '';
332
+ let first_sig = int.length + frac.length - digits.length;
333
+
334
+ let raw = (neg ? '-' : '') + digits;
335
+ let formatted = '', units = [], si = 0, gi = 0;
336
+ let lit = txt => { formatted += txt; };
337
+ let chr = ch => {
338
+ units.push({ kind: 'char', ordinal: null,
339
+ stream_start: si, stream_end: si + 1,
340
+ fmt_start: formatted.length, fmt_end: formatted.length + 1 });
341
+ formatted += ch; si++;
342
+ };
343
+
344
+ lit(o.prefix);
345
+ if (neg) chr('-');
346
+ for (let idx = 0; idx < int.length; idx++, gi++) {
347
+ if (idx && (int.length - idx) % 3 == 0) lit(o.group);
348
+ gi >= first_sig ? chr(int[idx]) : lit(int[idx]);
349
+ }
350
+ if (f) {
351
+ lit(o.decimal);
352
+ for (let idx = 0; idx < frac.length; idx++, gi++)
353
+ gi >= first_sig ? chr(frac[idx]) : lit(frac[idx]);
354
+ }
355
+ let stop_fmt = formatted.length;
356
+ lit(o.suffix);
357
+
358
+ let value = (neg ? -1 : 1) * parseFloat(int + (f ? '.' + frac : ''));
359
+ let complete = (o.min == null || value >= o.min) && (o.max == null || value <= o.max);
360
+
361
+ return { stream: raw, raw, formatted, tail: '', ph: '', ph_slots: [],
362
+ complete, consumed: raw.length, units, cells: [], stop_fmt };
363
+ }
364
+
365
+ export function run(def, input_string, ctx) {
366
+ if (def.numeral) return numeral(def, input_string);
367
+
368
+ let s = {
369
+ input: prepare(def, input_string, ctx),
370
+ ctx,
371
+ ip: 0,
372
+ stream: '', raw: '', formatted: '', tail: '', ph: '',
373
+ ph_slots: [], units: [], cells: [],
374
+ consumed: 0, ordinal: 0,
375
+ complete: true, done: false, stop_fmt: -1
376
+ };
377
+
378
+ walk(def.nodes, s, def);
379
+ if (s.stop_fmt < 0) s.stop_fmt = s.formatted.length;
380
+ if (def.valid) s.complete = s.complete && def.valid.test(s.raw);
381
+
382
+ return {
383
+ stream: s.stream, raw: s.raw, formatted: s.formatted, tail: s.tail,
384
+ ph: s.ph, ph_slots: s.ph_slots, complete: s.complete, consumed: s.consumed,
385
+ units: s.units, cells: s.cells, stop_fmt: s.stop_fmt
386
+ };
387
+ }
388
+
389
+ export function run_all(defs, input_string, ctx = {}) {
390
+ let resolved = [];
391
+ ctx = { ...ctx, stream: String(input_string ?? '') };
392
+ for (let def of defs)
393
+ def.fn ? resolved.push(...build(def.fn(ctx), def.base).map(d => ({ ...d, key: def.key ?? d.key })))
394
+ : resolved.push(def);
395
+
396
+ let best = null;
397
+ for (let def of resolved) {
398
+ let result = run(def, input_string, ctx);
399
+ if (!best
400
+ || result.consumed > best.result.consumed
401
+ || result.consumed == best.result.consumed && result.complete && !best.result.complete)
402
+ best = { result, def, mask_id: def.key };
403
+ }
404
+ return best;
405
+ }
406
+
407
+ export function render(result, placeholder) {
408
+ if (placeholder == 'always') return result.formatted + result.tail + result.ph;
409
+ if (placeholder === false) return result.formatted;
410
+ return result.formatted + result.tail;
411
+ }
412
+
413
+ export function caret_for(result, stream_pos) {
414
+ for (let unit of result.units) {
415
+ if (unit.kind == 'literal') continue;
416
+ if (stream_pos <= unit.stream_start || stream_pos < unit.stream_end)
417
+ return unit.fmt_start;
418
+ }
419
+ return result.stop_fmt;
420
+ }
421
+
422
+ export function cap(result, n) {
423
+ let chars = result.units.filter(u => u.kind == 'char');
424
+ return chars.length > n ? chars[n - 1].stream_end : result.stream.length;
425
+ }