janja 2.1.0 → 2.1.2

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/dist/index.esm.js CHANGED
@@ -1,193 +1,457 @@
1
- var NodeType;
2
- (function (NodeType) {
3
- NodeType["TEMPLATE"] = "TEMPLATE";
4
- NodeType["COMMENT"] = "COMMENT";
5
- NodeType["OUTPUT"] = "OUTPUT";
6
- NodeType["TEXT"] = "TEXT";
7
- NodeType["IF"] = "IF";
8
- NodeType["ELSE"] = "ELSE";
9
- NodeType["ELSE_IF"] = "ELSE_IF";
10
- NodeType["FOR"] = "FOR";
11
- NodeType["BREAK"] = "BREAK";
12
- NodeType["CONTINUE"] = "CONTINUE";
13
- NodeType["EXP"] = "EXP";
14
- NodeType["INCLUDE"] = "INCLUDE";
15
- NodeType["BLOCK"] = "BLOCK";
16
- NodeType["SUPER"] = "SUPER";
17
- NodeType["MACRO"] = "MACRO";
18
- NodeType["CALLER"] = "CALLER";
19
- NodeType["CALL"] = "CALL";
20
- NodeType["SET"] = "SET";
21
- NodeType["CAPTURE"] = "CAPTURE";
22
- NodeType["UNKNOWN"] = "UNKNOWN";
23
- NodeType["UNEXPECTED"] = "UNEXPECTED";
24
- })(NodeType || (NodeType = {}));
25
- class Traversal {
26
- constructor() {
27
- Object.defineProperty(this, "type", {
1
+ function highlightSource(message, source, { start: { line: l1, column: c1 }, end: { line: l2, column: c2 } }) {
2
+ const output = [];
3
+ const caretLines = new Set();
4
+ const addCaretLine = (index) => {
5
+ caretLines.add(index - 2);
6
+ caretLines.add(index - 1);
7
+ caretLines.add(index);
8
+ caretLines.add(index + 1);
9
+ caretLines.add(index + 2);
10
+ };
11
+ const lines = source.split('\n');
12
+ const indentWidth = String(lines.length).length + 2;
13
+ let caretLinesCount = 0;
14
+ lines.forEach((line, index) => {
15
+ if (!line) {
16
+ return;
17
+ }
18
+ output.push(`${`${index + 1}| `.padStart(indentWidth, ' ')}${line}`);
19
+ if (l1 === index + 1) {
20
+ const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c1 - 1)}^${l1 === l2 && c2 > c1 + 1 ? `${' '.repeat(c2 - c1 - 2)}^` : ''}`;
21
+ if (/\S/.test(caretLine)) {
22
+ output.push(caretLine);
23
+ }
24
+ addCaretLine(++caretLinesCount + index);
25
+ }
26
+ if (l1 !== l2 && l2 === index + 1) {
27
+ const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c2 - 1)}${'^'.repeat(1)}`;
28
+ if (/\S/.test(caretLine)) {
29
+ output.push(caretLine);
30
+ }
31
+ addCaretLine(++caretLinesCount + index);
32
+ }
33
+ });
34
+ const emptyLine = `${' '.repeat(indentWidth)}...`;
35
+ return `${message}
36
+
37
+ ${output
38
+ .map((line, index) => (caretLines.has(index) ? line : emptyLine))
39
+ .reduce((acc, line) => line === emptyLine && acc.at(-1) === line ? acc : [...acc, line], [])
40
+ .join('\n')}
41
+ `;
42
+ }
43
+
44
+ class CompileError extends SyntaxError {
45
+ constructor(message, src, loc) {
46
+ super(message);
47
+ Object.defineProperty(this, "src", {
28
48
  enumerable: true,
29
49
  configurable: true,
30
50
  writable: true,
31
- value: null
51
+ value: src
32
52
  });
33
53
  Object.defineProperty(this, "loc", {
34
54
  enumerable: true,
35
55
  configurable: true,
36
56
  writable: true,
37
- value: null
38
- });
39
- Object.defineProperty(this, "body", {
40
- enumerable: true,
41
- configurable: true,
42
- writable: true,
43
- value: void 0
57
+ value: loc
44
58
  });
59
+ this.name = 'CompileError';
60
+ CompileError.captureStackTrace?.(this, this.constructor);
45
61
  }
46
- traverse(cb) {
47
- this.body?.forEach(cb);
62
+ get details() {
63
+ return this.loc
64
+ ? highlightSource(this.message, this.src, this.loc)
65
+ : this.message;
48
66
  }
49
67
  }
50
- class RootNode extends Traversal {
51
- constructor(body, loc) {
52
- super();
53
- Object.defineProperty(this, "body", {
54
- enumerable: true,
55
- configurable: true,
56
- writable: true,
57
- value: body
58
- });
59
- Object.defineProperty(this, "loc", {
68
+
69
+ const CONTEXT = 'c';
70
+ const ESCAPE = 'e';
71
+ const FILTERS = 'f';
72
+
73
+ /**
74
+ * Contains the source map information.
75
+ * @example
76
+ * - template:
77
+ * {{ foo }}
78
+ *
79
+ * - compiled:
80
+ * s+=e(foo);
81
+ *
82
+ * - sourceMap:
83
+ * Mapping {
84
+ * source: {
85
+ * start: {
86
+ * line: 2,
87
+ * column: 4,
88
+ * },
89
+ * end: {
90
+ * line: 3,
91
+ * column: 5,
92
+ * },
93
+ * },
94
+ * target: {
95
+ * start: {
96
+ * line: 2,
97
+ * column: 3,
98
+ * },
99
+ * end: {
100
+ * line: 3,
101
+ * column: 8,
102
+ * },
103
+ * }
104
+ * }
105
+ */
106
+ class SourceMap {
107
+ constructor() {
108
+ Object.defineProperty(this, "mappings", {
60
109
  enumerable: true,
61
110
  configurable: true,
62
111
  writable: true,
63
- value: loc
112
+ value: []
64
113
  });
65
- Object.defineProperty(this, "type", {
66
- enumerable: true,
67
- configurable: true,
68
- writable: true,
69
- value: NodeType.TEMPLATE
114
+ }
115
+ addMapping(source, target) {
116
+ this.mappings.push({
117
+ source,
118
+ target,
70
119
  });
71
120
  }
121
+ getSourceLoc({ line, column }) {
122
+ return this.mappings
123
+ .filter(({ target: { start, end } }) => start.line <= line &&
124
+ end.line >= line &&
125
+ (start.line < line || start.column <= column) &&
126
+ (end.line > line || end.column >= column))
127
+ .map(({ source }) => source);
128
+ }
72
129
  }
73
- class OutputNode extends Traversal {
74
- constructor(val, loc, strip, exp) {
75
- super();
76
- Object.defineProperty(this, "val", {
77
- enumerable: true,
78
- configurable: true,
79
- writable: true,
80
- value: val
81
- });
82
- Object.defineProperty(this, "loc", {
83
- enumerable: true,
84
- configurable: true,
85
- writable: true,
86
- value: loc
87
- });
88
- Object.defineProperty(this, "strip", {
89
- enumerable: true,
90
- configurable: true,
91
- writable: true,
92
- value: strip
93
- });
94
- Object.defineProperty(this, "exp", {
130
+
131
+ class OutScript extends SourceMap {
132
+ constructor() {
133
+ super(...arguments);
134
+ Object.defineProperty(this, "code", {
95
135
  enumerable: true,
96
136
  configurable: true,
97
137
  writable: true,
98
- value: exp
138
+ value: ''
99
139
  });
100
- Object.defineProperty(this, "type", {
101
- enumerable: true,
102
- configurable: true,
103
- writable: true,
104
- value: NodeType.OUTPUT
140
+ }
141
+ get script() {
142
+ // eslint-disable-next-line no-new-func
143
+ return new Function(CONTEXT, ESCAPE, FILTERS, this.code);
144
+ }
145
+ start() {
146
+ this.pushRaw(null, 'return(async()=>{', 'let s="";');
147
+ }
148
+ end() {
149
+ this.pushRaw(null, 'return s;', '})();');
150
+ }
151
+ pushRaw(loc, ...lines) {
152
+ const start = this.code.length;
153
+ for (const line of lines) {
154
+ this.code += line;
155
+ }
156
+ if (!loc) {
157
+ return;
158
+ }
159
+ this.addMapping(loc, {
160
+ start: {
161
+ line: 1,
162
+ column: start,
163
+ },
164
+ end: {
165
+ line: 1,
166
+ column: this.code.length,
167
+ },
105
168
  });
106
169
  }
170
+ pushStr(loc, s) {
171
+ if (s) {
172
+ this.pushRaw(loc, `s+="${s
173
+ .replace(/\\/g, '\\\\')
174
+ .replace(/"/g, '\\"')
175
+ .replace(/[\n\r]/g, '\\n')}";`);
176
+ }
177
+ }
178
+ pushVar(loc, v) {
179
+ this.pushRaw(loc, `s+=${ESCAPE}(${v});`);
180
+ }
107
181
  }
108
- class TextNode extends Traversal {
109
- constructor(val, loc, strip) {
110
- super();
111
- Object.defineProperty(this, "val", {
112
- enumerable: true,
113
- configurable: true,
114
- writable: true,
115
- value: val
116
- });
117
- Object.defineProperty(this, "loc", {
182
+
183
+ class Context extends OutScript {
184
+ constructor() {
185
+ super(...arguments);
186
+ Object.defineProperty(this, "context", {
118
187
  enumerable: true,
119
188
  configurable: true,
120
189
  writable: true,
121
- value: loc
190
+ value: CONTEXT
122
191
  });
123
- Object.defineProperty(this, "strip", {
192
+ Object.defineProperty(this, "contexts", {
124
193
  enumerable: true,
125
194
  configurable: true,
126
195
  writable: true,
127
- value: strip
196
+ value: [CONTEXT]
128
197
  });
129
- Object.defineProperty(this, "type", {
198
+ Object.defineProperty(this, "index", {
130
199
  enumerable: true,
131
200
  configurable: true,
132
201
  writable: true,
133
- value: NodeType.TEXT
202
+ value: 0
134
203
  });
135
204
  }
205
+ in() {
206
+ this.context = `${this.context}_${this.index++}`;
207
+ this.contexts.push(this.context);
208
+ return this.context;
209
+ }
210
+ out() {
211
+ if (this.context === CONTEXT) {
212
+ return;
213
+ }
214
+ this.contexts.pop();
215
+ this.context = this.contexts.at(-1);
216
+ }
136
217
  }
137
- class IfNode extends Traversal {
138
- constructor(test, body, alternatives, loc, strip) {
139
- super();
140
- Object.defineProperty(this, "test", {
141
- enumerable: true,
142
- configurable: true,
143
- writable: true,
144
- value: test
145
- });
146
- Object.defineProperty(this, "body", {
147
- enumerable: true,
148
- configurable: true,
149
- writable: true,
150
- value: body
151
- });
152
- Object.defineProperty(this, "alternatives", {
218
+
219
+ class Safe extends String {
220
+ constructor(value) {
221
+ super(`${value}`);
222
+ }
223
+ }
224
+
225
+ function escape(v) {
226
+ return `${v}`
227
+ .replace(/&/g, '&amp;')
228
+ .replace(/"/g, '&#34;')
229
+ .replace(/'/g, '&#39;')
230
+ .replace(/</g, '&lt;')
231
+ .replace(/>/g, '&gt;');
232
+ }
233
+
234
+ function abs(value = 0) {
235
+ return Math.abs(value);
236
+ }
237
+ function add(value = 0, addend = 0) {
238
+ return value + addend;
239
+ }
240
+ function capitalize(value = '') {
241
+ return value.replace(/\b\w/g, (match) => match.toUpperCase());
242
+ }
243
+ function ceil(value = 0) {
244
+ return Math.ceil(value);
245
+ }
246
+ function compact(value = []) {
247
+ return value.filter((v) => v != null);
248
+ }
249
+ function div(value = 0, divisor = 1) {
250
+ return value / divisor;
251
+ }
252
+ function entries(value = {}) {
253
+ return Object.entries(value);
254
+ }
255
+ function even(value = 0) {
256
+ return +value % 2 === 0;
257
+ }
258
+ function fallback(value, defaultValue, anyFalsy = false) {
259
+ return anyFalsy ? value || defaultValue : (value ?? defaultValue);
260
+ }
261
+ function first(value = []) {
262
+ return [...value][0];
263
+ }
264
+ function get(value, ...path) {
265
+ return path.reduce((acc, cur) => acc && typeof acc === 'object' && cur in acc ? acc[cur] : undefined, value);
266
+ }
267
+ function groupby(value = [], key) {
268
+ return value.reduce((o, v) => {
269
+ const k = v[key];
270
+ return {
271
+ ...o,
272
+ [k]: [...(o[k] || []), v],
273
+ };
274
+ }, {});
275
+ }
276
+ function join(value = [], separator = '') {
277
+ return [...value].join(separator);
278
+ }
279
+ function json(value = null, indent = 0) {
280
+ return new Safe(JSON.stringify(value, null, indent));
281
+ }
282
+ function keys(value = {}) {
283
+ return Object.keys(value);
284
+ }
285
+ function last(value = []) {
286
+ return [...value].reverse()[0];
287
+ }
288
+ function length(value = '') {
289
+ return value.length;
290
+ }
291
+ function lower(value = '') {
292
+ return value.toLowerCase();
293
+ }
294
+ function map(value = [], key, defaultValue) {
295
+ return value.map((o) => o[key] ?? defaultValue);
296
+ }
297
+ function max(value = 0, ...rest) {
298
+ return Math.max(value, ...rest);
299
+ }
300
+ function min(value = 0, ...rest) {
301
+ return Math.min(value, ...rest);
302
+ }
303
+ function mul(value = 0, multiplier = 1) {
304
+ return value * multiplier;
305
+ }
306
+ function odd(value = 0) {
307
+ return +value % 2 === 1;
308
+ }
309
+ function omit(value = {}, ...omitKeys) {
310
+ return Object.entries(value).reduce((o, [k, v]) => (omitKeys.includes(k) ? o : { ...o, [k]: v }), {});
311
+ }
312
+ function pick(value = {}, ...pickKeys) {
313
+ return pickKeys.reduce((o, k) => ({ ...o, [k]: value[k] }), {});
314
+ }
315
+ function repeat(value = '', count = 0) {
316
+ return value.repeat(count);
317
+ }
318
+ function replace(value = '', search, replacement) {
319
+ return value.replace(new RegExp(search, 'g'), replacement);
320
+ }
321
+ function reverse(value = []) {
322
+ return Array.isArray(value) ? value.reverse() : [...value].reverse().join('');
323
+ }
324
+ function safe(value = '') {
325
+ return new Safe(value);
326
+ }
327
+ function slice(value = '', start = 0, end) {
328
+ return value.slice(start, end);
329
+ }
330
+ function sort(value = []) {
331
+ return Array.isArray(value) ? value.sort() : [...value].sort().join('');
332
+ }
333
+ function split(value = '', separator = '') {
334
+ return value.split(separator);
335
+ }
336
+ function sub(value = 0, subtrahend = 0) {
337
+ return value - subtrahend;
338
+ }
339
+ function sum(value = []) {
340
+ return value.reduce((a, b) => a + b, 0);
341
+ }
342
+ function trim(value = '') {
343
+ return value.trim();
344
+ }
345
+ function truncate(value = '', maxLength = 0, truncateStr = '...') {
346
+ return (value.slice(0, maxLength) + (value.length > maxLength ? truncateStr : ''));
347
+ }
348
+ function unique(value = '') {
349
+ return Array.isArray(value)
350
+ ? Array.from(new Set(value))
351
+ : Array.from(new Set(value)).join('');
352
+ }
353
+ function upper(value = '') {
354
+ return value.toUpperCase();
355
+ }
356
+ function urldecode(value = '') {
357
+ return decodeURIComponent(value);
358
+ }
359
+ function urlencode(value = '') {
360
+ return encodeURIComponent(value);
361
+ }
362
+ function values(value = {}) {
363
+ return Object.values(value);
364
+ }
365
+
366
+ var _filters = /*#__PURE__*/Object.freeze({
367
+ __proto__: null,
368
+ abs: abs,
369
+ add: add,
370
+ capitalize: capitalize,
371
+ ceil: ceil,
372
+ compact: compact,
373
+ div: div,
374
+ entries: entries,
375
+ escape: escape,
376
+ even: even,
377
+ fallback: fallback,
378
+ first: first,
379
+ get: get,
380
+ groupby: groupby,
381
+ join: join,
382
+ json: json,
383
+ keys: keys,
384
+ last: last,
385
+ length: length,
386
+ lower: lower,
387
+ map: map,
388
+ max: max,
389
+ min: min,
390
+ mul: mul,
391
+ odd: odd,
392
+ omit: omit,
393
+ pick: pick,
394
+ repeat: repeat,
395
+ replace: replace,
396
+ reverse: reverse,
397
+ safe: safe,
398
+ slice: slice,
399
+ sort: sort,
400
+ split: split,
401
+ sub: sub,
402
+ sum: sum,
403
+ trim: trim,
404
+ truncate: truncate,
405
+ unique: unique,
406
+ upper: upper,
407
+ urldecode: urldecode,
408
+ urlencode: urlencode,
409
+ values: values
410
+ });
411
+
412
+ async function compileBlock({ val: { value }, loc }, compiler) {
413
+ compiler.pushRaw(loc, `if(b["${value}"]&&!(b["${value}"].u++)){`, `s+=await b["${value}"].s?.pop()?.()??"";`, '}');
414
+ }
415
+ async function compileSuper({ loc }, compiler) {
416
+ if (!compiler.state.block) {
417
+ compiler.options.debug?.(new CompileError('"super" should be used inside a block', compiler.template, loc));
418
+ return;
419
+ }
420
+ compiler.pushRaw(loc, `s+=await b["${compiler.state.block}"]?.s?.pop()?.()??"";`);
421
+ }
422
+ const compilers$c = {
423
+ BLOCK: compileBlock,
424
+ SUPER: compileSuper,
425
+ };
426
+
427
+ class Traversal {
428
+ constructor() {
429
+ Object.defineProperty(this, "type", {
153
430
  enumerable: true,
154
431
  configurable: true,
155
432
  writable: true,
156
- value: alternatives
433
+ value: null
157
434
  });
158
435
  Object.defineProperty(this, "loc", {
159
436
  enumerable: true,
160
437
  configurable: true,
161
438
  writable: true,
162
- value: loc
163
- });
164
- Object.defineProperty(this, "strip", {
165
- enumerable: true,
166
- configurable: true,
167
- writable: true,
168
- value: strip
439
+ value: null
169
440
  });
170
- Object.defineProperty(this, "type", {
441
+ Object.defineProperty(this, "body", {
171
442
  enumerable: true,
172
443
  configurable: true,
173
444
  writable: true,
174
- value: NodeType.IF
445
+ value: void 0
175
446
  });
176
447
  }
177
448
  traverse(cb) {
178
449
  this.body?.forEach(cb);
179
- this.alternatives?.forEach((node) => node.body?.forEach(cb));
180
450
  }
181
451
  }
182
- class ElseIfNode extends Traversal {
183
- constructor(test, body, loc, strip) {
452
+ class RootNode extends Traversal {
453
+ constructor(body, loc) {
184
454
  super();
185
- Object.defineProperty(this, "test", {
186
- enumerable: true,
187
- configurable: true,
188
- writable: true,
189
- value: test
190
- });
191
455
  Object.defineProperty(this, "body", {
192
456
  enumerable: true,
193
457
  configurable: true,
@@ -200,23 +464,24 @@ class ElseIfNode extends Traversal {
200
464
  writable: true,
201
465
  value: loc
202
466
  });
203
- Object.defineProperty(this, "strip", {
204
- enumerable: true,
205
- configurable: true,
206
- writable: true,
207
- value: strip
208
- });
209
467
  Object.defineProperty(this, "type", {
210
468
  enumerable: true,
211
469
  configurable: true,
212
470
  writable: true,
213
- value: NodeType.ELSE_IF
471
+ value: 'TEMPLATE'
214
472
  });
215
473
  }
216
474
  }
217
- class ElseNode extends Traversal {
218
- constructor(body, loc, strip) {
475
+
476
+ class BlockNode extends Traversal {
477
+ constructor(val, body, loc, strip) {
219
478
  super();
479
+ Object.defineProperty(this, "val", {
480
+ enumerable: true,
481
+ configurable: true,
482
+ writable: true,
483
+ value: val
484
+ });
220
485
  Object.defineProperty(this, "body", {
221
486
  enumerable: true,
222
487
  configurable: true,
@@ -239,24 +504,18 @@ class ElseNode extends Traversal {
239
504
  enumerable: true,
240
505
  configurable: true,
241
506
  writable: true,
242
- value: NodeType.ELSE
507
+ value: 'BLOCK'
243
508
  });
244
509
  }
245
510
  }
246
- class ForNode extends Traversal {
247
- constructor(loop, body, loc, strip) {
511
+ class SuperNode extends Traversal {
512
+ constructor(val, loc, strip) {
248
513
  super();
249
- Object.defineProperty(this, "loop", {
250
- enumerable: true,
251
- configurable: true,
252
- writable: true,
253
- value: loop
254
- });
255
- Object.defineProperty(this, "body", {
514
+ Object.defineProperty(this, "val", {
256
515
  enumerable: true,
257
516
  configurable: true,
258
517
  writable: true,
259
- value: body
518
+ value: val
260
519
  });
261
520
  Object.defineProperty(this, "loc", {
262
521
  enumerable: true,
@@ -274,41 +533,194 @@ class ForNode extends Traversal {
274
533
  enumerable: true,
275
534
  configurable: true,
276
535
  writable: true,
277
- value: NodeType.FOR
536
+ value: 'SUPER'
278
537
  });
279
538
  }
280
539
  }
281
- class BreakNode extends Traversal {
282
- constructor(val, loc, strip) {
283
- super();
284
- Object.defineProperty(this, "val", {
285
- enumerable: true,
286
- configurable: true,
287
- writable: true,
288
- value: val
289
- });
290
- Object.defineProperty(this, "loc", {
291
- enumerable: true,
292
- configurable: true,
293
- writable: true,
294
- value: loc
295
- });
296
- Object.defineProperty(this, "strip", {
540
+
541
+ async function* parseBlock(token, parser) {
542
+ if (!token.expression) {
543
+ parser.emitExpErr(token);
544
+ return;
545
+ }
546
+ yield 'NEXT';
547
+ const body = await parser.parseUntil(['endblock']);
548
+ if (parser.match(['endblock'])) {
549
+ yield 'NEXT';
550
+ }
551
+ else {
552
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
553
+ }
554
+ yield new BlockNode(parser.parseExp(token.expression), body, token.loc, token.strip);
555
+ }
556
+ async function* parseSuper(token, parser) {
557
+ if (token.expression) {
558
+ parser.emitExpErr(token, false);
559
+ return;
560
+ }
561
+ yield 'NEXT';
562
+ yield new SuperNode(token.val, token.loc, token.strip);
563
+ }
564
+ const parsers$c = {
565
+ block: parseBlock,
566
+ super: parseSuper,
567
+ endblock: 'unexpected',
568
+ };
569
+
570
+ const plugin$c = {
571
+ compilers: compilers$c,
572
+ parsers: parsers$c,
573
+ };
574
+
575
+ const expTokenOperators = {
576
+ AND: '&&',
577
+ OR: '||',
578
+ IS: '',
579
+ NOT: '!',
580
+ EQ: '===',
581
+ NE: '!==',
582
+ GT: '>',
583
+ LT: '<',
584
+ GE: '>=',
585
+ LE: '<=',
586
+ IN: ' in ',
587
+ NI: ' in ',
588
+ OF: ' of ',
589
+ ADD: '+',
590
+ SUB: '-',
591
+ MUL: '*',
592
+ DIV: '/',
593
+ MOD: '%',
594
+ PIPE: '',
595
+ ASSIGN: '=',
596
+ LP: '(',
597
+ RP: ')',
598
+ COMMA: ',',
599
+ DOT: '.',
600
+ ID: '',
601
+ LIT: '',
602
+ IF: '',
603
+ ELSE: '',
604
+ };
605
+ class ExpCompiler {
606
+ constructor() {
607
+ Object.defineProperty(this, "context", {
297
608
  enumerable: true,
298
609
  configurable: true,
299
610
  writable: true,
300
- value: strip
611
+ value: void 0
301
612
  });
302
- Object.defineProperty(this, "type", {
613
+ Object.defineProperty(this, "filters", {
303
614
  enumerable: true,
304
615
  configurable: true,
305
616
  writable: true,
306
- value: NodeType.BREAK
617
+ value: void 0
307
618
  });
308
619
  }
620
+ compile(expression, context = CONTEXT, filters = FILTERS) {
621
+ this.context = context;
622
+ this.filters = filters;
623
+ return expression ? this.compileExp(expression) : '""';
624
+ }
625
+ compileExp(expression) {
626
+ switch (expression.type) {
627
+ case 'NOT':
628
+ return this.compileNot(expression);
629
+ case 'ID':
630
+ return this.compileId(expression);
631
+ case 'LIT':
632
+ return this.compileLit(expression);
633
+ case 'PIPE':
634
+ return this.compilePipe(expression);
635
+ case 'OF':
636
+ return this.compileOf(expression);
637
+ case 'ASSIGN':
638
+ return this.compileAssign(expression);
639
+ case 'IS':
640
+ return this.compileIs(expression);
641
+ case 'AND':
642
+ case 'OR':
643
+ case 'EQ':
644
+ case 'NE':
645
+ case 'GT':
646
+ case 'LT':
647
+ case 'GE':
648
+ case 'LE':
649
+ case 'IN':
650
+ case 'NI':
651
+ case 'ADD':
652
+ case 'SUB':
653
+ case 'MUL':
654
+ case 'DIV':
655
+ case 'MOD':
656
+ return this.compileBinary(expression);
657
+ case 'IF':
658
+ return this.compileTernary(expression);
659
+ case 'SEQ':
660
+ return this.compileSeq(expression);
661
+ // no default
662
+ }
663
+ }
664
+ compileNot({ argument }) {
665
+ return `!${this.compileExp(argument)}`;
666
+ }
667
+ compileId({ value, path, args }) {
668
+ let s = `${this.context}.${value}`;
669
+ if (path) {
670
+ s += path.map((p) => `.${p.value}`).join('');
671
+ }
672
+ if (args) {
673
+ s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
674
+ }
675
+ return s;
676
+ }
677
+ compileLit({ value }) {
678
+ return value === undefined ? 'undefined' : JSON.stringify(value);
679
+ }
680
+ compileSeq({ elements }) {
681
+ return elements.map((element) => this.compileExp(element)).toString();
682
+ }
683
+ compilePipe({ left, right }) {
684
+ const { value: name, args = [] } = right;
685
+ return `(await ${this.filters}.${name}.call(${[this.context, this.compileExp(left), ...args.map((arg) => (arg.type === 'ASSIGN' ? `${this.context}.${arg.left.value}=${this.compileExp(arg.right)}` : this.compileExp(arg)))].join(',')}))`;
686
+ }
687
+ compileOf({ left, right }) {
688
+ // destructuring
689
+ if (left.type === 'SEQ') {
690
+ return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
691
+ }
692
+ return `const ${left.value} of ${this.compileExp(right)}`;
693
+ }
694
+ compileAssign({ left, right }) {
695
+ if (left.type === 'ID') {
696
+ return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
697
+ }
698
+ // destructuring
699
+ return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
700
+ }
701
+ compileIs({ left, right }) {
702
+ return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
703
+ }
704
+ compileBinary({ type, left, right }) {
705
+ const ret = `${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)}`;
706
+ return type === 'NI' ? `!${ret}` : ret;
707
+ }
708
+ compileTernary({ test, consequent, alternative }) {
709
+ return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
710
+ }
309
711
  }
310
- class ContinueNode extends Traversal {
311
- constructor(val, loc, strip) {
712
+
713
+ async function compileCall({ val, body, loc }, compiler) {
714
+ compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
715
+ await compiler.compileNodes(body);
716
+ compiler.pushRaw(null, '});');
717
+ }
718
+ const compilers$b = {
719
+ CALL: compileCall,
720
+ };
721
+
722
+ class CallNode extends Traversal {
723
+ constructor(val, body, loc, strip) {
312
724
  super();
313
725
  Object.defineProperty(this, "val", {
314
726
  enumerable: true,
@@ -316,6 +728,12 @@ class ContinueNode extends Traversal {
316
728
  writable: true,
317
729
  value: val
318
730
  });
731
+ Object.defineProperty(this, "body", {
732
+ enumerable: true,
733
+ configurable: true,
734
+ writable: true,
735
+ value: body
736
+ });
319
737
  Object.defineProperty(this, "loc", {
320
738
  enumerable: true,
321
739
  configurable: true,
@@ -332,24 +750,59 @@ class ContinueNode extends Traversal {
332
750
  enumerable: true,
333
751
  configurable: true,
334
752
  writable: true,
335
- value: NodeType.CONTINUE
753
+ value: 'CALL'
336
754
  });
337
755
  }
338
756
  }
339
- class UnknownDirectiveNode extends Traversal {
340
- constructor(name, val, loc, strip) {
757
+
758
+ async function* parseCall(token, parser) {
759
+ if (!token.expression) {
760
+ parser.emitExpErr(token);
761
+ return;
762
+ }
763
+ yield 'NEXT';
764
+ const body = await parser.parseUntil(['endcall']);
765
+ if (parser.match(['endcall'])) {
766
+ yield 'NEXT';
767
+ }
768
+ else {
769
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
770
+ }
771
+ yield new CallNode(parser.parseExp(token.expression), body, token.loc, token.strip);
772
+ }
773
+ const parsers$b = {
774
+ call: parseCall,
775
+ endcall: 'unexpected',
776
+ };
777
+
778
+ const plugin$b = {
779
+ compilers: compilers$b,
780
+ parsers: parsers$b,
781
+ };
782
+
783
+ async function compileCapture({ val, body, loc }, compiler) {
784
+ compiler.pushRaw(loc, `${compiler.context}.${val.value}=await(async(s)=>{`);
785
+ await compiler.compileNodes(body);
786
+ compiler.pushRaw(null, 'return s;})("");');
787
+ }
788
+ const compilers$a = {
789
+ CAPTURE: compileCapture,
790
+ };
791
+
792
+ class CaptureNode extends Traversal {
793
+ constructor(val, body, loc, strip) {
341
794
  super();
342
- Object.defineProperty(this, "name", {
795
+ Object.defineProperty(this, "val", {
343
796
  enumerable: true,
344
797
  configurable: true,
345
798
  writable: true,
346
- value: name
799
+ value: val
347
800
  });
348
- Object.defineProperty(this, "val", {
801
+ Object.defineProperty(this, "body", {
349
802
  enumerable: true,
350
803
  configurable: true,
351
804
  writable: true,
352
- value: val
805
+ value: body
353
806
  });
354
807
  Object.defineProperty(this, "loc", {
355
808
  enumerable: true,
@@ -367,19 +820,48 @@ class UnknownDirectiveNode extends Traversal {
367
820
  enumerable: true,
368
821
  configurable: true,
369
822
  writable: true,
370
- value: NodeType.UNKNOWN
823
+ value: 'CAPTURE'
371
824
  });
372
825
  }
373
826
  }
374
- class UnexpectedDirectiveNode extends Traversal {
375
- constructor(name, val, loc, strip) {
827
+
828
+ async function* parseCapture(token, parser) {
829
+ if (!token.expression) {
830
+ parser.emitExpErr(token);
831
+ return;
832
+ }
833
+ yield 'NEXT';
834
+ const body = await parser.parseUntil(['endcapture']);
835
+ if (parser.match(['endcapture'])) {
836
+ yield 'NEXT';
837
+ }
838
+ else {
839
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
840
+ }
841
+ yield new CaptureNode(parser.parseExp(token.expression), body, token.loc, token.strip);
842
+ }
843
+ const parsers$a = {
844
+ capture: parseCapture,
845
+ endcapture: 'unexpected',
846
+ };
847
+
848
+ const plugin$a = {
849
+ compilers: compilers$a,
850
+ parsers: parsers$a,
851
+ };
852
+
853
+ async function compileComment({ val, loc }, compiler) {
854
+ if (!compiler.options.stripComments) {
855
+ compiler.pushStr(loc, `<!--${val}-->`);
856
+ }
857
+ }
858
+ const compilers$9 = {
859
+ COMMENT: compileComment,
860
+ };
861
+
862
+ class CommentNode extends Traversal {
863
+ constructor(val, loc, strip) {
376
864
  super();
377
- Object.defineProperty(this, "name", {
378
- enumerable: true,
379
- configurable: true,
380
- writable: true,
381
- value: name
382
- });
383
865
  Object.defineProperty(this, "val", {
384
866
  enumerable: true,
385
867
  configurable: true,
@@ -402,18 +884,62 @@ class UnexpectedDirectiveNode extends Traversal {
402
884
  enumerable: true,
403
885
  configurable: true,
404
886
  writable: true,
405
- value: NodeType.UNEXPECTED
887
+ value: 'COMMENT'
406
888
  });
407
889
  }
408
890
  }
409
- class CommentNode extends Traversal {
410
- constructor(val, loc, strip) {
891
+
892
+ async function* parseComment({ val, loc, strip }) {
893
+ yield 'NEXT';
894
+ yield new CommentNode(val, loc, strip);
895
+ }
896
+ const parsers$9 = {
897
+ comment: parseComment,
898
+ };
899
+
900
+ const plugin$9 = {
901
+ compilers: compilers$9,
902
+ parsers: parsers$9,
903
+ };
904
+
905
+ async function compileFor({ loop, body }, compiler) {
906
+ const { context } = compiler;
907
+ if (loop.left.type === 'SEQ') {
908
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.elements.map(({ value }) => value).join(',')},`, '};');
909
+ }
910
+ else {
911
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, '};');
912
+ }
913
+ await compiler.compileNodes(body);
914
+ compiler.out();
915
+ compiler.pushRaw(null, '}');
916
+ }
917
+ function compileBreak({ loc }, compiler) {
918
+ compiler.pushRaw(loc, 'break;');
919
+ }
920
+ function compileContinue({ loc }, compiler) {
921
+ compiler.pushRaw(loc, 'continue;');
922
+ }
923
+ const compilers$8 = {
924
+ FOR: compileFor,
925
+ BREAK: compileBreak,
926
+ CONTINUE: compileContinue,
927
+ };
928
+
929
+ class ForNode extends Traversal {
930
+ constructor(loop, body, loc, strip) {
411
931
  super();
412
- Object.defineProperty(this, "val", {
932
+ Object.defineProperty(this, "loop", {
413
933
  enumerable: true,
414
934
  configurable: true,
415
935
  writable: true,
416
- value: val
936
+ value: loop
937
+ });
938
+ Object.defineProperty(this, "body", {
939
+ enumerable: true,
940
+ configurable: true,
941
+ writable: true,
942
+ value: body
417
943
  });
418
944
  Object.defineProperty(this, "loc", {
419
945
  enumerable: true,
@@ -431,11 +957,11 @@ class CommentNode extends Traversal {
431
957
  enumerable: true,
432
958
  configurable: true,
433
959
  writable: true,
434
- value: NodeType.COMMENT
960
+ value: 'FOR'
435
961
  });
436
962
  }
437
963
  }
438
- class IncludeNode extends Traversal {
964
+ class BreakNode extends Traversal {
439
965
  constructor(val, loc, strip) {
440
966
  super();
441
967
  Object.defineProperty(this, "val", {
@@ -460,12 +986,12 @@ class IncludeNode extends Traversal {
460
986
  enumerable: true,
461
987
  configurable: true,
462
988
  writable: true,
463
- value: NodeType.INCLUDE
989
+ value: 'BREAK'
464
990
  });
465
991
  }
466
992
  }
467
- class BlockNode extends Traversal {
468
- constructor(val, body, loc, strip) {
993
+ class ContinueNode extends Traversal {
994
+ constructor(val, loc, strip) {
469
995
  super();
470
996
  Object.defineProperty(this, "val", {
471
997
  enumerable: true,
@@ -473,12 +999,6 @@ class BlockNode extends Traversal {
473
999
  writable: true,
474
1000
  value: val
475
1001
  });
476
- Object.defineProperty(this, "body", {
477
- enumerable: true,
478
- configurable: true,
479
- writable: true,
480
- value: body
481
- });
482
1002
  Object.defineProperty(this, "loc", {
483
1003
  enumerable: true,
484
1004
  configurable: true,
@@ -495,18 +1015,104 @@ class BlockNode extends Traversal {
495
1015
  enumerable: true,
496
1016
  configurable: true,
497
1017
  writable: true,
498
- value: NodeType.BLOCK
1018
+ value: 'CONTINUE'
499
1019
  });
500
1020
  }
501
1021
  }
502
- class SuperNode extends Traversal {
503
- constructor(val, loc, strip) {
1022
+
1023
+ const wm$1 = new WeakMap();
1024
+ async function* parseFor(token, parser) {
1025
+ if (!token.expression) {
1026
+ parser.emitExpErr(token);
1027
+ return;
1028
+ }
1029
+ wm$1.set(parser, true);
1030
+ yield 'NEXT';
1031
+ const body = await parser.parseUntil(['endfor']);
1032
+ wm$1.set(parser, false);
1033
+ if (parser.match(['endfor'])) {
1034
+ yield 'NEXT';
1035
+ }
1036
+ else {
1037
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1038
+ }
1039
+ yield new ForNode(parser.parseExp(token.expression), body, token.loc, token.strip);
1040
+ }
1041
+ async function* parseBreak(token, parser) {
1042
+ if (token.expression) {
1043
+ parser.emitExpErr(token, false);
1044
+ return;
1045
+ }
1046
+ if (!wm$1.get(parser)) {
1047
+ parser.options.debug?.(new CompileError('"break" directive used outside of a loop', parser.template, token.loc));
1048
+ return;
1049
+ }
1050
+ yield 'NEXT';
1051
+ yield new BreakNode(token.val, token.loc, token.strip);
1052
+ }
1053
+ async function* parseContinue(token, parser) {
1054
+ if (token.expression) {
1055
+ parser.emitExpErr(token, false);
1056
+ return;
1057
+ }
1058
+ if (!wm$1.get(parser)) {
1059
+ parser.options.debug?.(new CompileError('"continue" directive used outside of a loop', parser.template, token.loc));
1060
+ return;
1061
+ }
1062
+ yield 'NEXT';
1063
+ yield new ContinueNode(token.val, token.loc, token.strip);
1064
+ }
1065
+ const parsers$8 = {
1066
+ for: parseFor,
1067
+ break: parseBreak,
1068
+ continue: parseContinue,
1069
+ endfor: 'unexpected',
1070
+ };
1071
+
1072
+ const plugin$8 = {
1073
+ compilers: compilers$8,
1074
+ parsers: parsers$8,
1075
+ };
1076
+
1077
+ async function compileIf({ test, body, alternatives }, compiler) {
1078
+ compiler.pushRaw(test.loc, `if(${new ExpCompiler().compile(test, compiler.context)}){`);
1079
+ await compiler.compileNodes(body);
1080
+ compiler.pushRaw(null, '}');
1081
+ for (const branch of alternatives) {
1082
+ if (branch.type === 'ELSE_IF') {
1083
+ compiler.pushRaw(branch.test.loc, `else if(${new ExpCompiler().compile(branch.test, compiler.context)}){`);
1084
+ }
1085
+ else {
1086
+ compiler.pushRaw(null, 'else{');
1087
+ }
1088
+ await compiler.compileNodes(branch.body);
1089
+ compiler.pushRaw(null, '}');
1090
+ }
1091
+ }
1092
+ const compilers$7 = {
1093
+ IF: compileIf,
1094
+ };
1095
+
1096
+ class IfNode extends Traversal {
1097
+ constructor(test, body, alternatives, loc, strip) {
504
1098
  super();
505
- Object.defineProperty(this, "val", {
1099
+ Object.defineProperty(this, "test", {
506
1100
  enumerable: true,
507
1101
  configurable: true,
508
1102
  writable: true,
509
- value: val
1103
+ value: test
1104
+ });
1105
+ Object.defineProperty(this, "body", {
1106
+ enumerable: true,
1107
+ configurable: true,
1108
+ writable: true,
1109
+ value: body
1110
+ });
1111
+ Object.defineProperty(this, "alternatives", {
1112
+ enumerable: true,
1113
+ configurable: true,
1114
+ writable: true,
1115
+ value: alternatives
510
1116
  });
511
1117
  Object.defineProperty(this, "loc", {
512
1118
  enumerable: true,
@@ -524,18 +1130,22 @@ class SuperNode extends Traversal {
524
1130
  enumerable: true,
525
1131
  configurable: true,
526
1132
  writable: true,
527
- value: NodeType.SUPER
1133
+ value: 'IF'
528
1134
  });
529
1135
  }
1136
+ traverse(cb) {
1137
+ this.body?.forEach(cb);
1138
+ this.alternatives?.forEach((node) => node.body?.forEach(cb));
1139
+ }
530
1140
  }
531
- class MacroNode extends Traversal {
532
- constructor(val, body, loc, strip) {
1141
+ class ElseIfNode extends Traversal {
1142
+ constructor(test, body, loc, strip) {
533
1143
  super();
534
- Object.defineProperty(this, "val", {
1144
+ Object.defineProperty(this, "test", {
535
1145
  enumerable: true,
536
1146
  configurable: true,
537
1147
  writable: true,
538
- value: val
1148
+ value: test
539
1149
  });
540
1150
  Object.defineProperty(this, "body", {
541
1151
  enumerable: true,
@@ -559,18 +1169,18 @@ class MacroNode extends Traversal {
559
1169
  enumerable: true,
560
1170
  configurable: true,
561
1171
  writable: true,
562
- value: NodeType.MACRO
1172
+ value: 'ELSE_IF'
563
1173
  });
564
1174
  }
565
1175
  }
566
- class CallerNode extends Traversal {
567
- constructor(val, loc, strip) {
1176
+ class ElseNode extends Traversal {
1177
+ constructor(body, loc, strip) {
568
1178
  super();
569
- Object.defineProperty(this, "val", {
1179
+ Object.defineProperty(this, "body", {
570
1180
  enumerable: true,
571
1181
  configurable: true,
572
1182
  writable: true,
573
- value: val
1183
+ value: body
574
1184
  });
575
1185
  Object.defineProperty(this, "loc", {
576
1186
  enumerable: true,
@@ -588,12 +1198,106 @@ class CallerNode extends Traversal {
588
1198
  enumerable: true,
589
1199
  configurable: true,
590
1200
  writable: true,
591
- value: NodeType.CALLER
1201
+ value: 'ELSE'
592
1202
  });
593
1203
  }
594
1204
  }
595
- class CallNode extends Traversal {
596
- constructor(val, body, loc, strip) {
1205
+
1206
+ async function* parseIf(token, parser) {
1207
+ if (!token.expression) {
1208
+ parser.emitExpErr(token);
1209
+ return;
1210
+ }
1211
+ yield 'NEXT';
1212
+ const body = await parser.parseUntil([
1213
+ 'else',
1214
+ 'elseif',
1215
+ 'elsif',
1216
+ 'elif',
1217
+ 'endif',
1218
+ ]);
1219
+ const alternatives = [];
1220
+ while (parser.match(['else', 'elseif', 'elsif', 'elif'])) {
1221
+ const branchToken = parser.peek();
1222
+ if (branchToken.name.toLowerCase() === 'else') {
1223
+ const g = parseElse(branchToken, parser);
1224
+ while (true) {
1225
+ const { value, done } = await g.next();
1226
+ if (done) {
1227
+ break;
1228
+ }
1229
+ if (value) {
1230
+ if (value === 'NEXT') {
1231
+ yield 'NEXT';
1232
+ continue;
1233
+ }
1234
+ alternatives.push(value);
1235
+ }
1236
+ }
1237
+ }
1238
+ else {
1239
+ const g = parseElseIf(branchToken, parser);
1240
+ while (true) {
1241
+ const { value, done } = await g.next();
1242
+ if (done) {
1243
+ break;
1244
+ }
1245
+ if (value) {
1246
+ if (value === 'NEXT') {
1247
+ yield 'NEXT';
1248
+ continue;
1249
+ }
1250
+ alternatives.push(value);
1251
+ }
1252
+ }
1253
+ }
1254
+ }
1255
+ if (parser.match(['endif'])) {
1256
+ yield 'NEXT';
1257
+ }
1258
+ else {
1259
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1260
+ }
1261
+ yield new IfNode(parser.parseExp(token.expression), body, alternatives, token.loc, token.strip);
1262
+ }
1263
+ async function* parseElseIf(token, parser) {
1264
+ if (!token.expression) {
1265
+ parser.emitExpErr(token);
1266
+ return;
1267
+ }
1268
+ yield 'NEXT';
1269
+ yield new ElseIfNode(parser.parseExp(token.expression), await parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']), token.loc, token.strip);
1270
+ }
1271
+ async function* parseElse(token, parser) {
1272
+ if (token.expression) {
1273
+ parser.emitExpErr(token, false);
1274
+ return;
1275
+ }
1276
+ yield 'NEXT';
1277
+ yield new ElseNode(await parser.parseUntil(['endif']), token.loc, token.strip);
1278
+ }
1279
+ const parsers$7 = {
1280
+ if: parseIf,
1281
+ elseif: 'unexpected',
1282
+ elsif: 'unexpected',
1283
+ elif: 'unexpected',
1284
+ endif: 'unexpected',
1285
+ };
1286
+
1287
+ const plugin$7 = {
1288
+ compilers: compilers$7,
1289
+ parsers: parsers$7,
1290
+ };
1291
+
1292
+ async function compileInclude({ val: { value }, loc }, compiler) {
1293
+ compiler.pushRaw(loc, `s+=await p["${value}"]?.()??"";`);
1294
+ }
1295
+ const compilers$6 = {
1296
+ INCLUDE: compileInclude,
1297
+ };
1298
+
1299
+ class IncludeNode extends Traversal {
1300
+ constructor(val, loc, strip) {
597
1301
  super();
598
1302
  Object.defineProperty(this, "val", {
599
1303
  enumerable: true,
@@ -601,12 +1305,6 @@ class CallNode extends Traversal {
601
1305
  writable: true,
602
1306
  value: val
603
1307
  });
604
- Object.defineProperty(this, "body", {
605
- enumerable: true,
606
- configurable: true,
607
- writable: true,
608
- value: body
609
- });
610
1308
  Object.defineProperty(this, "loc", {
611
1309
  enumerable: true,
612
1310
  configurable: true,
@@ -623,12 +1321,53 @@ class CallNode extends Traversal {
623
1321
  enumerable: true,
624
1322
  configurable: true,
625
1323
  writable: true,
626
- value: NodeType.CALL
1324
+ value: 'INCLUDE'
627
1325
  });
628
1326
  }
629
1327
  }
630
- class SetNode extends Traversal {
631
- constructor(val, loc, strip) {
1328
+
1329
+ async function* parseInclude(token, parser) {
1330
+ if (!token.expression) {
1331
+ parser.emitExpErr(token);
1332
+ return;
1333
+ }
1334
+ yield 'NEXT';
1335
+ yield new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
1336
+ }
1337
+ const parsers$6 = {
1338
+ include: parseInclude,
1339
+ };
1340
+
1341
+ const plugin$6 = {
1342
+ compilers: compilers$6,
1343
+ parsers: parsers$6,
1344
+ };
1345
+
1346
+ async function compileMacro({ val: { left, right }, loc, body }, compiler) {
1347
+ const { context } = compiler;
1348
+ const { elements } = right;
1349
+ const expCompiler = new ExpCompiler();
1350
+ compiler.pushRaw(loc, `${expCompiler.compile(left)}=(${elements
1351
+ .map((el) => el.type === 'ASSIGN'
1352
+ ? `${el.left.value}=${expCompiler.compile(el.right)}`
1353
+ : el.value)
1354
+ .join(',')})=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, elements
1355
+ .map((el) => el.type === 'ASSIGN' ? el.left.value : el.value)
1356
+ .join(','), '};');
1357
+ await compiler.compileNodes(body);
1358
+ compiler.out();
1359
+ compiler.pushRaw(null, '};');
1360
+ }
1361
+ function compileCaller({ loc }, compiler) {
1362
+ compiler.pushRaw(loc, 'await _c?.();');
1363
+ }
1364
+ const compilers$5 = {
1365
+ MACRO: compileMacro,
1366
+ CALLER: compileCaller,
1367
+ };
1368
+
1369
+ class MacroNode extends Traversal {
1370
+ constructor(val, body, loc, strip) {
632
1371
  super();
633
1372
  Object.defineProperty(this, "val", {
634
1373
  enumerable: true,
@@ -636,6 +1375,12 @@ class SetNode extends Traversal {
636
1375
  writable: true,
637
1376
  value: val
638
1377
  });
1378
+ Object.defineProperty(this, "body", {
1379
+ enumerable: true,
1380
+ configurable: true,
1381
+ writable: true,
1382
+ value: body
1383
+ });
639
1384
  Object.defineProperty(this, "loc", {
640
1385
  enumerable: true,
641
1386
  configurable: true,
@@ -652,12 +1397,12 @@ class SetNode extends Traversal {
652
1397
  enumerable: true,
653
1398
  configurable: true,
654
1399
  writable: true,
655
- value: NodeType.SET
1400
+ value: 'MACRO'
656
1401
  });
657
1402
  }
658
1403
  }
659
- class CaptureNode extends Traversal {
660
- constructor(val, body, loc, strip) {
1404
+ class CallerNode extends Traversal {
1405
+ constructor(val, loc, strip) {
661
1406
  super();
662
1407
  Object.defineProperty(this, "val", {
663
1408
  enumerable: true,
@@ -665,12 +1410,6 @@ class CaptureNode extends Traversal {
665
1410
  writable: true,
666
1411
  value: val
667
1412
  });
668
- Object.defineProperty(this, "body", {
669
- enumerable: true,
670
- configurable: true,
671
- writable: true,
672
- value: body
673
- });
674
1413
  Object.defineProperty(this, "loc", {
675
1414
  enumerable: true,
676
1415
  configurable: true,
@@ -687,729 +1426,160 @@ class CaptureNode extends Traversal {
687
1426
  enumerable: true,
688
1427
  configurable: true,
689
1428
  writable: true,
690
- value: NodeType.CAPTURE
1429
+ value: 'CALLER'
691
1430
  });
692
1431
  }
693
1432
  }
694
1433
 
695
- function highlightSource(message, source, { start: { line: l1, column: c1 }, end: { line: l2, column: c2 } }) {
696
- const output = [];
697
- const caretLines = new Set();
698
- const addCaretLine = (index) => {
699
- caretLines.add(index - 2);
700
- caretLines.add(index - 1);
701
- caretLines.add(index);
702
- caretLines.add(index + 1);
703
- caretLines.add(index + 2);
704
- };
705
- const lines = source.split('\n');
706
- const indentWidth = String(lines.length).length + 2;
707
- let caretLinesCount = 0;
708
- lines.forEach((line, index) => {
709
- if (!line) {
710
- return;
711
- }
712
- output.push(`${`${index + 1}| `.padStart(indentWidth, ' ')}${line}`);
713
- if (l1 === index + 1) {
714
- const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c1 - 1)}^${l1 === l2 && c2 > c1 + 1 ? `${' '.repeat(c2 - c1 - 2)}^` : ''}`;
715
- if (/\S/.test(caretLine)) {
716
- output.push(caretLine);
717
- }
718
- addCaretLine(++caretLinesCount + index);
719
- }
720
- if (l1 !== l2 && l2 === index + 1) {
721
- const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c2 - 1)}${'^'.repeat(1)}`;
722
- if (/\S/.test(caretLine)) {
723
- output.push(caretLine);
724
- }
725
- addCaretLine(++caretLinesCount + index);
726
- }
727
- });
728
- const emptyLine = `${' '.repeat(indentWidth)}...`;
729
- return `${message}
730
-
731
- ${output
732
- .map((line, index) => (caretLines.has(index) ? line : emptyLine))
733
- .reduce((acc, line) => line === emptyLine && acc.at(-1) === line ? acc : [...acc, line], [])
734
- .join('\n')}
735
- `;
736
- }
737
-
738
- class CompileError extends SyntaxError {
739
- constructor(message, src, loc) {
740
- super(message);
741
- Object.defineProperty(this, "src", {
742
- enumerable: true,
743
- configurable: true,
744
- writable: true,
745
- value: src
746
- });
747
- Object.defineProperty(this, "loc", {
748
- enumerable: true,
749
- configurable: true,
750
- writable: true,
751
- value: loc
752
- });
753
- this.name = 'CompileError';
754
- CompileError.captureStackTrace?.(this, this.constructor);
755
- }
756
- get details() {
757
- return this.loc
758
- ? highlightSource(this.message, this.src, this.loc)
759
- : this.message;
760
- }
761
- }
762
-
763
- const parseUnexpected = (token, parser) => parser.createUnexpectedDirective(token);
764
-
765
- function parseBlock(token, parser) {
766
- parser.requireExpression(token);
767
- const val = parser.parseExp(token.expression);
768
- parser.advance();
769
- const body = parser.parseUntil(['endblock']);
770
- if (parser.match(['endblock'])) {
771
- parser.advance();
772
- }
773
- else {
774
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
775
- }
776
- return new BlockNode(val, body, token.loc, token.strip);
777
- }
778
- function parseSuper(token, parser) {
779
- parser.requireNoExpression(token);
780
- parser.advance();
781
- return new SuperNode(token.val, token.loc, token.strip);
782
- }
783
- const parsers$8 = {
784
- block: parseBlock,
785
- super: parseSuper,
786
- endblock: parseUnexpected,
787
- };
788
-
789
- function parseCall(token, parser) {
790
- parser.requireExpression(token);
791
- const val = parser.parseExp(token.expression);
792
- parser.advance();
793
- const body = parser.parseUntil(['endcall']);
794
- if (parser.match(['endcall'])) {
795
- parser.advance();
796
- }
797
- else {
798
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
799
- }
800
- return new CallNode(val, body, token.loc, token.strip);
801
- }
802
- const parsers$7 = {
803
- call: parseCall,
804
- endcall: parseUnexpected,
805
- };
806
-
807
- function parseCapture(token, parser) {
808
- parser.requireExpression(token);
809
- const val = parser.parseExp(token.expression);
810
- parser.advance();
811
- const body = parser.parseUntil(['endcapture']);
812
- if (parser.match(['endcapture'])) {
813
- parser.advance();
814
- }
815
- else {
816
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
817
- }
818
- return new CaptureNode(val, body, token.loc, token.strip);
819
- }
820
- const parsers$6 = {
821
- capture: parseCapture,
822
- endcapture: parseUnexpected,
823
- };
824
-
825
- function parseFor(token, parser) {
826
- parser.requireExpression(token);
827
- const loop = parser.parseExp(token.expression);
828
- parser.advance();
829
- const body = parser.parseUntil(['endfor']);
830
- if (parser.match(['endfor'])) {
831
- parser.advance();
832
- }
833
- else {
834
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
835
- }
836
- return new ForNode(loop, body, token.loc, token.strip);
837
- }
838
- function parseBreak(token, parser) {
839
- parser.requireNoExpression(token);
840
- parser.advance();
841
- return new BreakNode(token.val, token.loc, token.strip);
842
- }
843
- function parseContinue(token, parser) {
844
- parser.requireNoExpression(token);
845
- parser.advance();
846
- return new ContinueNode(token.val, token.loc, token.strip);
847
- }
848
- const parsers$5 = {
849
- for: parseFor,
850
- break: parseBreak,
851
- continue: parseContinue,
852
- endfor: parseUnexpected,
853
- };
854
-
855
- function parseIf(token, parser) {
856
- parser.requireExpression(token);
857
- parser.advance();
858
- const body = parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']);
859
- const alternatives = [];
860
- while (parser.match(['else', 'elseif', 'elsif', 'elif'])) {
861
- const branchToken = parser.peek();
862
- alternatives.push(branchToken.name.toLowerCase() === 'else'
863
- ? parseElse(branchToken, parser)
864
- : parseElseIf(branchToken, parser));
865
- }
866
- if (parser.match(['endif'])) {
867
- parser.advance();
868
- }
869
- else {
870
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
871
- }
872
- return new IfNode(parser.parseExp(token.expression), body, alternatives, token.loc, token.strip);
873
- }
874
- function parseElseIf(token, parser) {
875
- parser.requireExpression(token);
876
- parser.advance();
877
- const body = parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']);
878
- return new ElseIfNode(parser.parseExp(token.expression), body, token.loc, token.strip);
879
- }
880
- function parseElse(token, parser) {
881
- parser.requireNoExpression(token);
882
- parser.advance();
883
- const body = parser.parseUntil(['endif']);
884
- return new ElseNode(body, token.loc, token.strip);
885
- }
886
- const parsers$4 = {
887
- if: parseIf,
888
- elseif: parseUnexpected,
889
- elsif: parseUnexpected,
890
- elif: parseUnexpected,
891
- endif: parseUnexpected,
892
- };
893
-
894
- function parseInclude(token, parser) {
895
- parser.requireExpression(token);
896
- const val = parser.parseExp(token.expression);
897
- parser.advance();
898
- return new IncludeNode(val, token.loc, token.strip);
899
- }
900
- const parsers$3 = {
901
- include: parseInclude,
902
- };
903
-
904
- function parseMacro(token, parser) {
905
- parser.requireExpression(token);
906
- const name = parser.parseExp(token.expression);
907
- parser.advance();
908
- const body = parser.parseUntil(['endmacro']);
909
- if (parser.match(['endmacro'])) {
910
- parser.advance();
911
- }
912
- else {
913
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
914
- }
915
- return new MacroNode(name, body, token.loc, token.strip);
916
- }
917
- function parseCaller(token, parser) {
918
- parser.requireNoExpression(token);
919
- parser.advance();
920
- return new CallerNode(token.val, token.loc, token.strip);
921
- }
922
- const parsers$2 = {
923
- macro: parseMacro,
924
- caller: parseCaller,
925
- endmacro: parseUnexpected,
926
- };
927
-
928
- function parseSet(token, parser) {
929
- parser.requireExpression(token);
930
- const val = parser.parseExp(token.expression);
931
- parser.advance();
932
- return new SetNode(val, token.loc, token.strip);
933
- }
934
- const parsers$1 = {
935
- set: parseSet,
936
- };
937
-
938
- const parsers = {
939
- ...parsers$4,
940
- ...parsers$5,
941
- ...parsers$3,
942
- ...parsers$8,
943
- ...parsers$2,
944
- ...parsers$7,
945
- ...parsers$1,
946
- ...parsers$6,
947
- };
948
-
949
- class Safe extends String {
950
- constructor(value) {
951
- super(`${value}`);
952
- }
953
- }
954
-
955
- function escape(v) {
956
- return `${v}`
957
- .replace(/&/g, '&amp;')
958
- .replace(/"/g, '&#34;')
959
- .replace(/'/g, '&#39;')
960
- .replace(/</g, '&lt;')
961
- .replace(/>/g, '&gt;');
962
- }
963
-
964
- function abs(value = 0) {
965
- return Math.abs(value);
966
- }
967
- function add(value = 0, addend = 0) {
968
- return value + addend;
969
- }
970
- function capitalize(value = '') {
971
- return value.replace(/\b\w/g, (match) => match.toUpperCase());
972
- }
973
- function ceil(value = 0) {
974
- return Math.ceil(value);
975
- }
976
- function compact(value = []) {
977
- return value.filter((v) => v != null);
978
- }
979
- function div(value = 0, divisor = 1) {
980
- return value / divisor;
981
- }
982
- function entries(value = {}) {
983
- return Object.entries(value);
984
- }
985
- function even(value = 0) {
986
- return +value % 2 === 0;
987
- }
988
- function fallback(value, defaultValue, anyFalsy = false) {
989
- return anyFalsy ? value || defaultValue : (value ?? defaultValue);
990
- }
991
- function first(value = []) {
992
- return [...value][0];
993
- }
994
- function get(value, ...path) {
995
- return path.reduce((acc, cur) => acc && typeof acc === 'object' && cur in acc ? acc[cur] : undefined, value);
996
- }
997
- function groupby(value = [], key) {
998
- return value.reduce((o, v) => {
999
- const k = v[key];
1000
- return {
1001
- ...o,
1002
- [k]: [...(o[k] || []), v],
1003
- };
1004
- }, {});
1005
- }
1006
- function join(value = [], separator = '') {
1007
- return [...value].join(separator);
1008
- }
1009
- function json(value = null, indent = 0) {
1010
- return new Safe(JSON.stringify(value, null, indent));
1011
- }
1012
- function keys(value = {}) {
1013
- return Object.keys(value);
1014
- }
1015
- function last(value = []) {
1016
- return [...value].reverse()[0];
1017
- }
1018
- function length(value = '') {
1019
- return value.length;
1020
- }
1021
- function lower(value = '') {
1022
- return value.toLowerCase();
1023
- }
1024
- function map(value = [], key, defaultValue) {
1025
- return value.map((o) => o[key] ?? defaultValue);
1026
- }
1027
- function max(value = 0, ...rest) {
1028
- return Math.max(value, ...rest);
1029
- }
1030
- function min(value = 0, ...rest) {
1031
- return Math.min(value, ...rest);
1032
- }
1033
- function mul(value = 0, multiplier = 1) {
1034
- return value * multiplier;
1035
- }
1036
- function odd(value = 0) {
1037
- return +value % 2 === 1;
1038
- }
1039
- function omit(value = {}, ...omitKeys) {
1040
- return Object.entries(value).reduce((o, [k, v]) => (omitKeys.includes(k) ? o : { ...o, [k]: v }), {});
1041
- }
1042
- function pick(value = {}, ...pickKeys) {
1043
- return pickKeys.reduce((o, k) => ({ ...o, [k]: value[k] }), {});
1044
- }
1045
- function repeat(value = '', count = 0) {
1046
- return value.repeat(count);
1047
- }
1048
- function replace(value = '', search, replacement) {
1049
- return value.replace(new RegExp(search, 'g'), replacement);
1050
- }
1051
- function reverse(value = []) {
1052
- return Array.isArray(value) ? value.reverse() : [...value].reverse().join('');
1053
- }
1054
- function safe(value = '') {
1055
- return new Safe(value);
1056
- }
1057
- function slice(value = '', start = 0, end) {
1058
- return value.slice(start, end);
1059
- }
1060
- function sort(value = []) {
1061
- return Array.isArray(value) ? value.sort() : [...value].sort().join('');
1062
- }
1063
- function split(value = '', separator = '') {
1064
- return value.split(separator);
1065
- }
1066
- function sub(value = 0, subtrahend = 0) {
1067
- return value - subtrahend;
1068
- }
1069
- function sum(value = []) {
1070
- return value.reduce((a, b) => a + b, 0);
1071
- }
1072
- function trim(value = '') {
1073
- return value.trim();
1074
- }
1075
- function truncate(value = '', maxLength = 0, truncateStr = '...') {
1076
- return (value.slice(0, maxLength) + (value.length > maxLength ? truncateStr : ''));
1077
- }
1078
- function unique(value = '') {
1079
- return Array.isArray(value)
1080
- ? Array.from(new Set(value))
1081
- : Array.from(new Set(value)).join('');
1082
- }
1083
- function upper(value = '') {
1084
- return value.toUpperCase();
1085
- }
1086
- function urldecode(value = '') {
1087
- return decodeURIComponent(value);
1088
- }
1089
- function urlencode(value = '') {
1090
- return encodeURIComponent(value);
1091
- }
1092
- function values(value = {}) {
1093
- return Object.values(value);
1094
- }
1095
-
1096
- var _filters = /*#__PURE__*/Object.freeze({
1097
- __proto__: null,
1098
- abs: abs,
1099
- add: add,
1100
- capitalize: capitalize,
1101
- ceil: ceil,
1102
- compact: compact,
1103
- div: div,
1104
- entries: entries,
1105
- escape: escape,
1106
- even: even,
1107
- fallback: fallback,
1108
- first: first,
1109
- get: get,
1110
- groupby: groupby,
1111
- join: join,
1112
- json: json,
1113
- keys: keys,
1114
- last: last,
1115
- length: length,
1116
- lower: lower,
1117
- map: map,
1118
- max: max,
1119
- min: min,
1120
- mul: mul,
1121
- odd: odd,
1122
- omit: omit,
1123
- pick: pick,
1124
- repeat: repeat,
1125
- replace: replace,
1126
- reverse: reverse,
1127
- safe: safe,
1128
- slice: slice,
1129
- sort: sort,
1130
- split: split,
1131
- sub: sub,
1132
- sum: sum,
1133
- trim: trim,
1134
- truncate: truncate,
1135
- unique: unique,
1136
- upper: upper,
1137
- urldecode: urldecode,
1138
- urlencode: urlencode,
1139
- values: values
1140
- });
1141
-
1142
- async function compileBlock({ val: { value }, loc }, compiler) {
1143
- compiler.pushRaw(loc, `if(b["${value}"]&&!(b["${value}"].u++)){`, `s+=await b["${value}"].s?.pop()?.()??"";`, '}');
1144
- }
1145
- async function compileSuper({ loc }, compiler) {
1146
- if (!compiler.state.block) {
1147
- compiler.options.debug?.(new CompileError('"super" should be used inside a block', compiler.template, loc));
1148
- return;
1149
- }
1150
- compiler.pushRaw(loc, `s+=await b["${compiler.state.block}"]?.s?.pop()?.()??"";`);
1151
- }
1152
- const compilers$b = {
1153
- [NodeType.BLOCK]: compileBlock,
1154
- [NodeType.SUPER]: compileSuper,
1155
- };
1156
-
1157
- const expTokenOperators = {
1158
- AND: '&&',
1159
- OR: '||',
1160
- IS: '',
1161
- NOT: '!',
1162
- EQ: '===',
1163
- NE: '!==',
1164
- GT: '>',
1165
- LT: '<',
1166
- GE: '>=',
1167
- LE: '<=',
1168
- IN: ' in ',
1169
- NI: ' in ',
1170
- OF: ' of ',
1171
- ADD: '+',
1172
- SUB: '-',
1173
- MUL: '*',
1174
- DIV: '/',
1175
- MOD: '%',
1176
- PIPE: '',
1177
- SET: '=',
1178
- LP: '(',
1179
- RP: ')',
1180
- COMMA: ',',
1181
- DOT: '.',
1182
- ID: '',
1183
- LIT: '',
1184
- IF: '',
1185
- ELSE: '',
1186
- };
1187
-
1188
- const CONTEXT = 'c';
1189
- const ESCAPE = 'e';
1190
- const FILTERS = 'f';
1191
-
1192
- class ExpCompiler {
1193
- constructor() {
1194
- Object.defineProperty(this, "context", {
1195
- enumerable: true,
1196
- configurable: true,
1197
- writable: true,
1198
- value: void 0
1199
- });
1200
- Object.defineProperty(this, "filters", {
1201
- enumerable: true,
1202
- configurable: true,
1203
- writable: true,
1204
- value: void 0
1205
- });
1206
- }
1207
- compile(expression, context = CONTEXT, filters = FILTERS) {
1208
- this.context = context;
1209
- this.filters = filters;
1210
- return expression ? this.compileExp(expression) : '""';
1211
- }
1212
- compileExp(expression) {
1213
- switch (expression.type) {
1214
- case 'NOT':
1215
- return this.compileNot(expression);
1216
- case 'ID':
1217
- return this.compileId(expression);
1218
- case 'LIT':
1219
- return this.compileLit(expression);
1220
- case 'PIPE':
1221
- return this.compilePipe(expression);
1222
- case 'OF':
1223
- return this.compileOf(expression);
1224
- case 'SET':
1225
- return this.compileSet(expression);
1226
- case 'IS':
1227
- return this.compileIs(expression);
1228
- case 'AND':
1229
- case 'OR':
1230
- case 'EQ':
1231
- case 'NE':
1232
- case 'GT':
1233
- case 'LT':
1234
- case 'GE':
1235
- case 'LE':
1236
- case 'IN':
1237
- case 'NI':
1238
- case 'ADD':
1239
- case 'SUB':
1240
- case 'MUL':
1241
- case 'DIV':
1242
- case 'MOD':
1243
- return this.compileBinary(expression);
1244
- case 'IF':
1245
- return this.compileTernary(expression);
1246
- case 'SEQ':
1247
- return this.compileSeq(expression);
1248
- default:
1249
- return '';
1250
- }
1251
- }
1252
- compileNot({ argument }) {
1253
- return `!${this.compileExp(argument)}`;
1254
- }
1255
- compileId({ value, path, args }) {
1256
- let s = `${this.context}.${value}`;
1257
- if (path) {
1258
- s += path.map((p) => `.${p.value}`).join('');
1259
- }
1260
- if (args) {
1261
- s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
1262
- }
1263
- return s;
1264
- }
1265
- compileLit({ value }) {
1266
- return value === undefined ? 'undefined' : JSON.stringify(value);
1267
- }
1268
- compileSeq({ elements }) {
1269
- return elements.map((element) => this.compileExp(element)).toString();
1270
- }
1271
- compilePipe({ left, right }) {
1272
- const { value: name, args = [] } = right;
1273
- return `(await ${this.filters}.${name}.call(${[this.context, this.compileExp(left), ...args.map((arg) => (arg.type === 'SET' ? `${this.context}.${arg.left.value}=${this.compileExp(arg.right)}` : this.compileExp(arg)))].join(',')}))`;
1274
- }
1275
- compileOf({ left, right }) {
1276
- // destructuring
1277
- if (left.type === 'SEQ') {
1278
- return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
1279
- }
1280
- return `const ${left.value} of ${this.compileExp(right)}`;
1281
- }
1282
- compileSet({ left, right }) {
1283
- if (left.type === 'ID') {
1284
- return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
1285
- }
1286
- // destructuring
1287
- return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
1288
- }
1289
- compileIs({ left, right }) {
1290
- return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
1291
- }
1292
- compileBinary({ type, left, right }) {
1293
- const ret = `${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)}`;
1294
- return type === 'NI' ? `!${ret}` : ret;
1295
- }
1296
- compileTernary({ test, consequent, alternative }) {
1297
- return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
1298
- }
1299
- }
1300
-
1301
- async function compileCall({ val, body, loc }, compiler) {
1302
- compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
1303
- await compiler.compileNodes(body);
1304
- compiler.pushRaw(null, '});');
1305
- }
1306
- const compilers$a = {
1307
- [NodeType.CALL]: compileCall,
1308
- };
1309
-
1310
- async function compileCapture({ val, body, loc }, compiler) {
1311
- compiler.pushRaw(loc, `${compiler.context}.${val.value}=await(async(s)=>{`);
1312
- await compiler.compileNodes(body);
1313
- compiler.pushRaw(null, 'return s;})("");');
1314
- }
1315
- const compilers$9 = {
1316
- [NodeType.CAPTURE]: compileCapture,
1317
- };
1318
-
1319
- async function compileComment({ val, loc }, compiler) {
1320
- if (!compiler.options.stripComments) {
1321
- compiler.pushStr(loc, `<!--${val}-->`);
1322
- }
1323
- }
1324
- const compilers$8 = {
1325
- [NodeType.COMMENT]: compileComment,
1326
- };
1327
-
1328
- async function compileFor({ loop, body }, compiler) {
1329
- const { context } = compiler;
1330
- if (loop.left.type === 'SEQ') {
1331
- compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.elements.map(({ value }) => value).join(',')},`, '};');
1434
+ const wm = new WeakMap();
1435
+ async function* parseMacro(token, parser) {
1436
+ if (!token.expression) {
1437
+ parser.emitExpErr(token);
1438
+ return;
1439
+ }
1440
+ wm.set(parser, true);
1441
+ yield 'NEXT';
1442
+ const body = await parser.parseUntil(['endmacro']);
1443
+ wm.set(parser, false);
1444
+ if (parser.match(['endmacro'])) {
1445
+ yield 'NEXT';
1332
1446
  }
1333
1447
  else {
1334
- compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, '};');
1448
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1335
1449
  }
1336
- await compiler.compileNodes(body);
1337
- compiler.out();
1338
- compiler.pushRaw(null, '}');
1450
+ yield new MacroNode(parser.parseExp(token.expression), body, token.loc, token.strip);
1339
1451
  }
1340
- function compileBreak({ loc }, compiler) {
1341
- compiler.pushRaw(loc, 'break;');
1342
- }
1343
- function compileContinue({ loc }, compiler) {
1344
- compiler.pushRaw(loc, 'continue;');
1452
+ async function* parseCaller(token, parser) {
1453
+ if (token.expression) {
1454
+ parser.emitExpErr(token, false);
1455
+ return;
1456
+ }
1457
+ if (!wm.get(parser)) {
1458
+ parser.options.debug?.(new CompileError('"caller" directive used outside of a macro', parser.template, token.loc));
1459
+ return;
1460
+ }
1461
+ yield 'NEXT';
1462
+ yield new CallerNode(token.val, token.loc, token.strip);
1345
1463
  }
1346
- const compilers$7 = {
1347
- [NodeType.FOR]: compileFor,
1348
- [NodeType.BREAK]: compileBreak,
1349
- [NodeType.CONTINUE]: compileContinue,
1464
+ const parsers$5 = {
1465
+ macro: parseMacro,
1466
+ caller: parseCaller,
1467
+ endmacro: 'unexpected',
1350
1468
  };
1351
1469
 
1352
- async function compileIf({ test, body, alternatives }, compiler) {
1353
- compiler.pushRaw(test.loc, `if(${new ExpCompiler().compile(test, compiler.context)}){`);
1354
- await compiler.compileNodes(body);
1355
- compiler.pushRaw(null, '}');
1356
- for (const branch of alternatives) {
1357
- if (branch.type === NodeType.ELSE_IF) {
1358
- compiler.pushRaw(branch.test.loc, `else if(${new ExpCompiler().compile(branch.test, compiler.context)}){`);
1359
- }
1360
- else {
1361
- compiler.pushRaw(null, 'else{');
1362
- }
1363
- await compiler.compileNodes(branch.body);
1364
- compiler.pushRaw(null, '}');
1365
- }
1366
- }
1367
- const compilers$6 = {
1368
- [NodeType.IF]: compileIf,
1470
+ const plugin$5 = {
1471
+ compilers: compilers$5,
1472
+ parsers: parsers$5,
1369
1473
  };
1370
1474
 
1371
- async function compileInclude({ val: { value }, loc }, compiler) {
1372
- compiler.pushRaw(loc, `s+=await p["${value}"]?.()??"";`);
1475
+ async function compileOutput({ exp }, compiler) {
1476
+ compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1373
1477
  }
1374
- const compilers$5 = {
1375
- [NodeType.INCLUDE]: compileInclude,
1478
+ const compilers$4 = {
1479
+ OUTPUT: compileOutput,
1376
1480
  };
1377
1481
 
1378
- async function compileMacro({ val: { left, right }, loc, body }, compiler) {
1379
- const { context } = compiler;
1380
- const { elements } = right;
1381
- const expCompiler = new ExpCompiler();
1382
- compiler.pushRaw(loc, `${expCompiler.compile(left)}=(${elements
1383
- .map((el) => el.type === 'SET'
1384
- ? `${el.left.value}=${expCompiler.compile(el.right)}`
1385
- : el.value)
1386
- .join(',')})=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, elements
1387
- .map((el) => el.type === 'SET' ? el.left.value : el.value)
1388
- .join(','), '};');
1389
- await compiler.compileNodes(body);
1390
- compiler.out();
1391
- compiler.pushRaw(null, '};');
1482
+ class OutputNode extends Traversal {
1483
+ constructor(val, loc, strip, exp) {
1484
+ super();
1485
+ Object.defineProperty(this, "val", {
1486
+ enumerable: true,
1487
+ configurable: true,
1488
+ writable: true,
1489
+ value: val
1490
+ });
1491
+ Object.defineProperty(this, "loc", {
1492
+ enumerable: true,
1493
+ configurable: true,
1494
+ writable: true,
1495
+ value: loc
1496
+ });
1497
+ Object.defineProperty(this, "strip", {
1498
+ enumerable: true,
1499
+ configurable: true,
1500
+ writable: true,
1501
+ value: strip
1502
+ });
1503
+ Object.defineProperty(this, "exp", {
1504
+ enumerable: true,
1505
+ configurable: true,
1506
+ writable: true,
1507
+ value: exp
1508
+ });
1509
+ Object.defineProperty(this, "type", {
1510
+ enumerable: true,
1511
+ configurable: true,
1512
+ writable: true,
1513
+ value: 'OUTPUT'
1514
+ });
1515
+ }
1392
1516
  }
1393
- function compileCaller({ loc }, compiler) {
1394
- compiler.pushRaw(loc, 'await _c?.();');
1517
+
1518
+ async function* parseOutput(token, parser) {
1519
+ yield 'NEXT';
1520
+ yield new OutputNode(token.val, token.loc, token.strip, parser.parseExp(token));
1395
1521
  }
1396
- const compilers$4 = {
1397
- [NodeType.MACRO]: compileMacro,
1398
- [NodeType.CALLER]: compileCaller,
1522
+ const parsers$4 = {
1523
+ output: parseOutput,
1399
1524
  };
1400
1525
 
1401
- async function compileOutput({ exp }, compiler) {
1402
- compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1403
- }
1404
- const compilers$3 = {
1405
- [NodeType.OUTPUT]: compileOutput,
1526
+ const plugin$4 = {
1527
+ compilers: compilers$4,
1528
+ parsers: parsers$4,
1406
1529
  };
1407
1530
 
1408
1531
  async function compileSet({ val, loc }, compiler) {
1409
1532
  compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
1410
1533
  }
1411
- const compilers$2 = {
1412
- [NodeType.SET]: compileSet,
1534
+ const compilers$3 = {
1535
+ SET: compileSet,
1536
+ };
1537
+
1538
+ class SetNode extends Traversal {
1539
+ constructor(val, loc, strip) {
1540
+ super();
1541
+ Object.defineProperty(this, "val", {
1542
+ enumerable: true,
1543
+ configurable: true,
1544
+ writable: true,
1545
+ value: val
1546
+ });
1547
+ Object.defineProperty(this, "loc", {
1548
+ enumerable: true,
1549
+ configurable: true,
1550
+ writable: true,
1551
+ value: loc
1552
+ });
1553
+ Object.defineProperty(this, "strip", {
1554
+ enumerable: true,
1555
+ configurable: true,
1556
+ writable: true,
1557
+ value: strip
1558
+ });
1559
+ Object.defineProperty(this, "type", {
1560
+ enumerable: true,
1561
+ configurable: true,
1562
+ writable: true,
1563
+ value: 'SET'
1564
+ });
1565
+ }
1566
+ }
1567
+
1568
+ async function* parseSet(token, parser) {
1569
+ if (!token.expression) {
1570
+ parser.emitExpErr(token);
1571
+ return;
1572
+ }
1573
+ yield 'NEXT';
1574
+ yield new SetNode(parser.parseExp(token.expression), token.loc, token.strip);
1575
+ }
1576
+ const parsers$3 = {
1577
+ set: parseSet,
1578
+ };
1579
+
1580
+ const plugin$3 = {
1581
+ compilers: compilers$3,
1582
+ parsers: parsers$3,
1413
1583
  };
1414
1584
 
1415
1585
  async function compileText({ val, loc, strip: { start, end } }, compiler) {
@@ -1421,226 +1591,246 @@ async function compileText({ val, loc, strip: { start, end } }, compiler) {
1421
1591
  }
1422
1592
  compiler.pushStr(loc, val);
1423
1593
  }
1424
- const compilers$1 = {
1425
- [NodeType.TEXT]: compileText,
1594
+ const compilers$2 = {
1595
+ TEXT: compileText,
1426
1596
  };
1427
1597
 
1428
- const compilers = {
1429
- ...compilers$6,
1430
- ...compilers$7,
1431
- ...compilers$5,
1432
- ...compilers$b,
1433
- ...compilers$1,
1434
- ...compilers$3,
1435
- ...compilers$8,
1436
- ...compilers$4,
1437
- ...compilers$a,
1438
- ...compilers$2,
1439
- ...compilers$9,
1440
- };
1598
+ class TextNode extends Traversal {
1599
+ constructor(val, loc, strip) {
1600
+ super();
1601
+ Object.defineProperty(this, "val", {
1602
+ enumerable: true,
1603
+ configurable: true,
1604
+ writable: true,
1605
+ value: val
1606
+ });
1607
+ Object.defineProperty(this, "loc", {
1608
+ enumerable: true,
1609
+ configurable: true,
1610
+ writable: true,
1611
+ value: loc
1612
+ });
1613
+ Object.defineProperty(this, "strip", {
1614
+ enumerable: true,
1615
+ configurable: true,
1616
+ writable: true,
1617
+ value: strip
1618
+ });
1619
+ Object.defineProperty(this, "type", {
1620
+ enumerable: true,
1621
+ configurable: true,
1622
+ writable: true,
1623
+ value: 'TEXT'
1624
+ });
1625
+ }
1626
+ }
1441
1627
 
1442
- const parserOptions = {
1443
- commentOpen: '{{#',
1444
- commentClose: '}}',
1445
- directiveOpen: '{{',
1446
- directiveClose: '}}',
1447
- outputOpen: '{{=',
1448
- outputClose: '}}',
1449
- parsers,
1450
- debug: () => { },
1628
+ async function* parseText(token) {
1629
+ yield 'NEXT';
1630
+ yield new TextNode(token.val, token.loc, token.strip);
1631
+ }
1632
+ const parsers$2 = {
1633
+ text: parseText,
1451
1634
  };
1452
- const compilerOptions = {
1453
- ...parserOptions,
1454
- trimWhitespace: false,
1455
- stripComments: false,
1456
- compilers,
1457
- loader: async () => '',
1635
+
1636
+ const plugin$2 = {
1637
+ compilers: compilers$2,
1638
+ parsers: parsers$2,
1458
1639
  };
1459
- const renderOptions = {
1460
- ...compilerOptions,
1461
- globals: {},
1462
- filters: _filters,
1463
- autoEscape: true,
1464
- plugins: [],
1640
+
1641
+ async function compileUnexpected$1({ name, val, loc }, compiler) {
1642
+ compiler.pushRaw(loc, `<!-- unexpected "${name}" with value "${val}" -->`);
1643
+ }
1644
+ const compilers$1 = {
1645
+ UNEXPECTED: compileUnexpected$1,
1465
1646
  };
1466
1647
 
1467
- /**
1468
- * Contains the source map information.
1469
- * @example
1470
- * - template:
1471
- * {{ foo }}
1472
- *
1473
- * - compiled:
1474
- * s+=e(foo);
1475
- *
1476
- * - sourceMap:
1477
- * Mapping {
1478
- * source: {
1479
- * start: {
1480
- * line: 2,
1481
- * column: 4,
1482
- * },
1483
- * end: {
1484
- * line: 3,
1485
- * column: 5,
1486
- * },
1487
- * },
1488
- * target: {
1489
- * start: {
1490
- * line: 2,
1491
- * column: 3,
1492
- * },
1493
- * end: {
1494
- * line: 3,
1495
- * column: 8,
1496
- * },
1497
- * }
1498
- * }
1499
- */
1500
- class SourceMap {
1501
- constructor() {
1502
- Object.defineProperty(this, "mappings", {
1648
+ class UnexpectedNode extends Traversal {
1649
+ constructor(name, val, loc, strip) {
1650
+ super();
1651
+ Object.defineProperty(this, "name", {
1503
1652
  enumerable: true,
1504
1653
  configurable: true,
1505
1654
  writable: true,
1506
- value: []
1655
+ value: name
1507
1656
  });
1508
- }
1509
- addMapping(source, target) {
1510
- this.mappings.push({
1511
- source,
1512
- target,
1657
+ Object.defineProperty(this, "val", {
1658
+ enumerable: true,
1659
+ configurable: true,
1660
+ writable: true,
1661
+ value: val
1662
+ });
1663
+ Object.defineProperty(this, "loc", {
1664
+ enumerable: true,
1665
+ configurable: true,
1666
+ writable: true,
1667
+ value: loc
1668
+ });
1669
+ Object.defineProperty(this, "strip", {
1670
+ enumerable: true,
1671
+ configurable: true,
1672
+ writable: true,
1673
+ value: strip
1674
+ });
1675
+ Object.defineProperty(this, "type", {
1676
+ enumerable: true,
1677
+ configurable: true,
1678
+ writable: true,
1679
+ value: 'unexpected'
1513
1680
  });
1514
- }
1515
- getSourceLoc({ line, column }) {
1516
- return this.mappings
1517
- .filter(({ target: { start, end } }) => start.line <= line &&
1518
- end.line >= line &&
1519
- (start.line < line || start.column <= column) &&
1520
- (end.line > line || end.column >= column))
1521
- .map(({ source }) => source);
1522
1681
  }
1523
1682
  }
1524
1683
 
1525
- class OutScript extends SourceMap {
1526
- constructor() {
1527
- super(...arguments);
1528
- Object.defineProperty(this, "code", {
1684
+ async function* parseUnexpected(token, parser) {
1685
+ const name = token.name ?? token.type;
1686
+ parser.options.debug?.(new CompileError(`Unexpected "${name}" node`, parser.template, token.loc));
1687
+ yield 'NEXT';
1688
+ yield new UnexpectedNode(name, token.val, token.loc, token.strip);
1689
+ }
1690
+ const parsers$1 = {
1691
+ unexpected: parseUnexpected,
1692
+ };
1693
+
1694
+ const plugin$1 = {
1695
+ compilers: compilers$1,
1696
+ parsers: parsers$1,
1697
+ };
1698
+
1699
+ async function compileUnexpected({ name, val, loc }, compiler) {
1700
+ compiler.pushRaw(loc, `<!-- unexpected "${name}" with value "${val}" -->`);
1701
+ }
1702
+ const compilers = {
1703
+ UNEXPECTED: compileUnexpected,
1704
+ };
1705
+
1706
+ class UnknownNode extends Traversal {
1707
+ constructor(name, val, loc, strip) {
1708
+ super();
1709
+ Object.defineProperty(this, "name", {
1529
1710
  enumerable: true,
1530
1711
  configurable: true,
1531
1712
  writable: true,
1532
- value: ''
1713
+ value: name
1533
1714
  });
1534
- }
1535
- get script() {
1536
- // eslint-disable-next-line no-new-func
1537
- return new Function(CONTEXT, ESCAPE, FILTERS, this.code);
1538
- }
1539
- start() {
1540
- this.pushRaw(null, 'return(async()=>{', 'let s="";');
1541
- }
1542
- end() {
1543
- this.pushRaw(null, 'return s;', '})();');
1544
- }
1545
- pushRaw(loc, ...lines) {
1546
- const start = this.code.length;
1547
- for (const line of lines) {
1548
- this.code += line;
1549
- }
1550
- if (!loc) {
1551
- return;
1552
- }
1553
- this.addMapping(loc, {
1554
- start: {
1555
- line: 1,
1556
- column: start,
1557
- },
1558
- end: {
1559
- line: 1,
1560
- column: this.code.length,
1561
- },
1715
+ Object.defineProperty(this, "val", {
1716
+ enumerable: true,
1717
+ configurable: true,
1718
+ writable: true,
1719
+ value: val
1562
1720
  });
1563
- }
1564
- pushStr(loc, s) {
1565
- if (s) {
1566
- this.pushRaw(loc, `s+="${s
1567
- .replace(/\\/g, '\\\\')
1568
- .replace(/"/g, '\\"')
1569
- .replace(/[\n\r]/g, '\\n')}";`);
1570
- }
1571
- }
1572
- pushVar(loc, v) {
1573
- this.pushRaw(loc, `s+=${ESCAPE}(${v});`);
1574
- }
1575
- }
1576
-
1577
- class Context extends OutScript {
1578
- constructor() {
1579
- super(...arguments);
1580
- Object.defineProperty(this, "context", {
1721
+ Object.defineProperty(this, "loc", {
1581
1722
  enumerable: true,
1582
1723
  configurable: true,
1583
1724
  writable: true,
1584
- value: CONTEXT
1725
+ value: loc
1585
1726
  });
1586
- Object.defineProperty(this, "contexts", {
1727
+ Object.defineProperty(this, "strip", {
1587
1728
  enumerable: true,
1588
1729
  configurable: true,
1589
1730
  writable: true,
1590
- value: [CONTEXT]
1731
+ value: strip
1591
1732
  });
1592
- Object.defineProperty(this, "index", {
1733
+ Object.defineProperty(this, "type", {
1593
1734
  enumerable: true,
1594
1735
  configurable: true,
1595
1736
  writable: true,
1596
- value: 0
1737
+ value: 'UNKNOWN'
1597
1738
  });
1598
1739
  }
1599
- in() {
1600
- this.context = `${this.context}_${this.index++}`;
1601
- this.contexts.push(this.context);
1602
- return this.context;
1603
- }
1604
- out() {
1605
- if (this.context === CONTEXT) {
1606
- return;
1607
- }
1608
- this.contexts.pop();
1609
- this.context = this.contexts.at(-1);
1610
- }
1611
1740
  }
1612
1741
 
1613
- const expTokenPrecedences = {
1614
- COMMA: 5,
1615
- IF: 10,
1616
- ELSE: 10,
1617
- SET: 15,
1618
- LP: 20,
1619
- RP: 20,
1620
- OR: 25,
1621
- AND: 30,
1622
- IS: 40,
1623
- EQ: 40,
1624
- NE: 40,
1625
- GT: 40,
1626
- LT: 40,
1627
- GE: 40,
1628
- LE: 40,
1629
- IN: 40,
1630
- NI: 40,
1631
- OF: 40,
1632
- ADD: 50,
1633
- SUB: 50,
1634
- MUL: 60,
1635
- DIV: 60,
1636
- MOD: 60,
1637
- NOT: 70,
1638
- PIPE: 80,
1639
- DOT: 90,
1640
- ID: 90,
1641
- LIT: 90,
1742
+ async function* parseUnknown(token, parser) {
1743
+ const name = token.name ?? token.type;
1744
+ parser.options.debug?.(new CompileError(`Unknown "${name}" node`, parser.template, token.loc));
1745
+ yield 'NEXT';
1746
+ yield new UnknownNode(name, token.val, token.loc, token.strip);
1747
+ }
1748
+ const parsers = {
1749
+ unknown: parseUnknown,
1750
+ };
1751
+
1752
+ const plugin = {
1753
+ compilers,
1754
+ parsers,
1755
+ };
1756
+
1757
+ const plugins = [
1758
+ plugin$c,
1759
+ plugin$b,
1760
+ plugin$9,
1761
+ plugin$a,
1762
+ plugin$8,
1763
+ plugin$7,
1764
+ plugin$6,
1765
+ plugin$5,
1766
+ plugin$3,
1767
+ plugin$2,
1768
+ plugin$4,
1769
+ plugin$1,
1770
+ plugin,
1771
+ ];
1772
+
1773
+ const baseOptions = {
1774
+ filters: _filters,
1775
+ parsers: {},
1776
+ compilers: {},
1777
+ plugins,
1778
+ debug: () => { },
1779
+ };
1780
+ const parserOptions = {
1781
+ ...baseOptions,
1782
+ commentOpen: '{{#',
1783
+ commentClose: '}}',
1784
+ directiveOpen: '{{',
1785
+ directiveClose: '}}',
1786
+ outputOpen: '{{=',
1787
+ outputClose: '}}',
1788
+ };
1789
+ const compilerOptions = {
1790
+ ...parserOptions,
1791
+ trimWhitespace: false,
1792
+ stripComments: false,
1793
+ loader: async () => '',
1794
+ };
1795
+ const renderOptions = {
1796
+ ...compilerOptions,
1797
+ globals: {},
1798
+ autoEscape: true,
1799
+ };
1800
+ const mergeOptions = (defaultOptions, options) => {
1801
+ const mergedOptions = {
1802
+ ...defaultOptions,
1803
+ ...options,
1804
+ };
1805
+ defaultOptions.plugins?.forEach((plugin) => {
1806
+ Object.assign(mergedOptions.filters, plugin.filters ?? {});
1807
+ Object.assign(mergedOptions.parsers, plugin.parsers ?? {});
1808
+ Object.assign(mergedOptions.compilers, plugin.compilers ?? {});
1809
+ });
1810
+ options?.plugins?.forEach((plugin) => {
1811
+ Object.assign(mergedOptions.filters, plugin.filters ?? {});
1812
+ Object.assign(mergedOptions.parsers, plugin.parsers ?? {});
1813
+ Object.assign(mergedOptions.compilers, plugin.compilers ?? {});
1814
+ });
1815
+ return mergedOptions;
1642
1816
  };
1643
1817
 
1818
+ function updatePosition(str, pos) {
1819
+ const newlines = (str.match(/\n/g) || []).length;
1820
+ if (newlines > 0) {
1821
+ pos.line += newlines;
1822
+ const lastNewline = str.lastIndexOf('\n');
1823
+ pos.column = str.length - lastNewline;
1824
+ }
1825
+ else {
1826
+ pos.column += str.length;
1827
+ }
1828
+ return {
1829
+ line: pos.line,
1830
+ column: pos.column,
1831
+ };
1832
+ }
1833
+
1644
1834
  const expTokenTypes = {
1645
1835
  and: 'AND',
1646
1836
  or: 'OR',
@@ -1667,33 +1857,12 @@ const expTokenTypes = {
1667
1857
  null: 'LIT',
1668
1858
  undefined: 'LIT',
1669
1859
  '|': 'PIPE',
1670
- '=': 'SET',
1860
+ '=': 'ASSIGN',
1671
1861
  '(': 'LP',
1672
1862
  ')': 'RP',
1673
1863
  ',': 'COMMA',
1674
1864
  '.': 'DOT',
1675
1865
  };
1676
-
1677
- /**
1678
- * Update position by a given string, and return a new position with the
1679
- * updated values.
1680
- */
1681
- function updatePosition(str, pos) {
1682
- const newlines = (str.match(/\n/g) || []).length;
1683
- if (newlines > 0) {
1684
- pos.line += newlines;
1685
- const lastNewline = str.lastIndexOf('\n');
1686
- pos.column = str.length - lastNewline;
1687
- }
1688
- else {
1689
- pos.column += str.length;
1690
- }
1691
- return {
1692
- line: pos.line,
1693
- column: pos.column,
1694
- };
1695
- }
1696
-
1697
1866
  class ExpTokenizer {
1698
1867
  constructor(template) {
1699
1868
  Object.defineProperty(this, "template", {
@@ -1904,6 +2073,36 @@ function isIdentifierChar(char) {
1904
2073
  return /[\w$]/.test(char);
1905
2074
  }
1906
2075
 
2076
+ const expTokenPrecedences = {
2077
+ COMMA: 5,
2078
+ IF: 10,
2079
+ ELSE: 10,
2080
+ ASSIGN: 15,
2081
+ LP: 20,
2082
+ RP: 20,
2083
+ OR: 25,
2084
+ AND: 30,
2085
+ IS: 40,
2086
+ EQ: 40,
2087
+ NE: 40,
2088
+ GT: 40,
2089
+ LT: 40,
2090
+ GE: 40,
2091
+ LE: 40,
2092
+ IN: 40,
2093
+ NI: 40,
2094
+ OF: 40,
2095
+ ADD: 50,
2096
+ SUB: 50,
2097
+ MUL: 60,
2098
+ DIV: 60,
2099
+ MOD: 60,
2100
+ NOT: 70,
2101
+ PIPE: 80,
2102
+ DOT: 90,
2103
+ ID: 90,
2104
+ LIT: 90,
2105
+ };
1907
2106
  class ExpParser {
1908
2107
  constructor(template) {
1909
2108
  Object.defineProperty(this, "template", {
@@ -2003,7 +2202,7 @@ class ExpParser {
2003
2202
  type: 'ID',
2004
2203
  value: token.value,
2005
2204
  };
2006
- if (this.check('DOT')) {
2205
+ if (this.match('DOT')) {
2007
2206
  left.path = this.parsePath();
2008
2207
  }
2009
2208
  const lp = this.consume('LP');
@@ -2060,7 +2259,7 @@ class ExpParser {
2060
2259
  token.type === 'MUL' ||
2061
2260
  token.type === 'DIV' ||
2062
2261
  token.type === 'MOD' ||
2063
- token.type === 'SET') {
2262
+ token.type === 'ASSIGN') {
2064
2263
  if (!left) {
2065
2264
  throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
2066
2265
  }
@@ -2080,7 +2279,7 @@ class ExpParser {
2080
2279
  if (!left) {
2081
2280
  throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
2082
2281
  }
2083
- if (!this.check('ID')) {
2282
+ if (!this.match('ID')) {
2084
2283
  throw new CompileError('expected "ID" after "PIPE"', this.template, token.loc);
2085
2284
  }
2086
2285
  left = {
@@ -2120,7 +2319,7 @@ class ExpParser {
2120
2319
  }
2121
2320
  parseSequence() {
2122
2321
  const elements = [];
2123
- while (!this.check('RP')) {
2322
+ while (!this.match('RP')) {
2124
2323
  const element = this.parseExp((t) => t.type === 'COMMA' ? 'BREAK' : undefined);
2125
2324
  if (element) {
2126
2325
  elements.push(element);
@@ -2159,11 +2358,11 @@ class ExpParser {
2159
2358
  peek() {
2160
2359
  return this.tokens.at(this.index) ?? null;
2161
2360
  }
2162
- check(type) {
2361
+ match(type) {
2163
2362
  return this.peek()?.type === type;
2164
2363
  }
2165
2364
  consume(type) {
2166
- if (this.check(type)) {
2365
+ if (this.match(type)) {
2167
2366
  return this.next();
2168
2367
  }
2169
2368
  }
@@ -2234,10 +2433,7 @@ class Tokenizer {
2234
2433
  writable: true,
2235
2434
  value: 1
2236
2435
  });
2237
- this.options = {
2238
- ...parserOptions,
2239
- ...options,
2240
- };
2436
+ this.options = mergeOptions(parserOptions, options);
2241
2437
  const { commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = this.options;
2242
2438
  this.tokenPatterns = [
2243
2439
  [TokenType.COMMENT, commentOpen, commentClose],
@@ -2376,15 +2572,15 @@ class Parser extends Tokenizer {
2376
2572
  value: void 0
2377
2573
  });
2378
2574
  }
2379
- parse(template) {
2575
+ async parse(template) {
2380
2576
  this.tokenize(template);
2381
2577
  const start = this.tokens[0]?.loc.start ?? { line: 1, column: 1 };
2382
2578
  const end = this.tokens.at(-1)?.loc.end ?? { line: 1, column: 1 };
2383
2579
  this.expParser = new ExpParser(template);
2384
2580
  this.cursor = 0;
2385
- return new RootNode(this.parseUntil(), { start, end });
2581
+ return new RootNode(await this.parseUntil(), { start, end });
2386
2582
  }
2387
- parseUntil(names) {
2583
+ async parseUntil(names) {
2388
2584
  const nodes = [];
2389
2585
  let prevToken = null;
2390
2586
  while (true) {
@@ -2401,50 +2597,33 @@ class Parser extends Tokenizer {
2401
2597
  if (token.strip?.before && prevToken?.type === TokenType.TEXT) {
2402
2598
  prevToken.strip.end = true;
2403
2599
  }
2404
- switch (token.type) {
2405
- case TokenType.COMMENT:
2406
- nodes.push(this.createComment(token));
2407
- break;
2408
- case TokenType.DIRECTIVE:
2409
- nodes.push(this.createDirective(token));
2410
- break;
2411
- case TokenType.OUTPUT:
2412
- nodes.push(this.createOutput(token));
2413
- break;
2414
- case TokenType.TEXT:
2415
- nodes.push(this.createText(token));
2416
- break;
2600
+ let parser = this.options.parsers[token.name?.toLowerCase() ??
2601
+ token.type?.toLowerCase()];
2602
+ if (parser === 'unexpected') {
2603
+ parser = this.options.parsers['unexpected'];
2604
+ }
2605
+ if (!parser) {
2606
+ parser = this.options.parsers['unknown'];
2607
+ }
2608
+ const ag = parser?.(token, this);
2609
+ if (ag) {
2610
+ while (true) {
2611
+ const { value, done } = await ag.next();
2612
+ if (done) {
2613
+ break;
2614
+ }
2615
+ if (value === 'NEXT') {
2616
+ this.advance();
2617
+ }
2618
+ else if (value) {
2619
+ nodes.push(value);
2620
+ }
2621
+ }
2417
2622
  }
2418
2623
  prevToken = token;
2419
2624
  }
2420
2625
  return nodes;
2421
2626
  }
2422
- createComment({ val, loc, strip }) {
2423
- this.advance();
2424
- return new CommentNode(val, loc, strip);
2425
- }
2426
- createOutput({ val, loc, strip }) {
2427
- this.advance();
2428
- return new OutputNode(val, loc, strip, this.parseExp({ val, loc }));
2429
- }
2430
- createText({ val, loc, strip }) {
2431
- this.advance();
2432
- return new TextNode(val, loc, strip);
2433
- }
2434
- createDirective(token) {
2435
- return (this.options.parsers[token.name.toLowerCase()]?.(token, this) ??
2436
- this.createUnknownDirective(token));
2437
- }
2438
- createUnexpectedDirective(token) {
2439
- this.options.debug?.(new CompileError(`Unexpected "${token.name}" directive`, this.template, token.loc));
2440
- this.advance();
2441
- return new UnexpectedDirectiveNode(token.name, token.val, token.loc, token.strip);
2442
- }
2443
- createUnknownDirective(token) {
2444
- this.options.debug?.(new CompileError(`Unknown "${token.name}" directive`, this.template, token.loc));
2445
- this.advance();
2446
- return new UnknownDirectiveNode(token.name, token.val, token.loc, token.strip);
2447
- }
2448
2627
  parseExp({ val, loc }) {
2449
2628
  return this.expParser.parse(val, loc);
2450
2629
  }
@@ -2457,15 +2636,10 @@ class Parser extends Tokenizer {
2457
2636
  match(names, token = this.peek()) {
2458
2637
  return names.includes(token?.name);
2459
2638
  }
2460
- requireExpression({ expression, name, loc }) {
2461
- if (!expression) {
2462
- throw this.options.debug?.(new CompileError(`"${name}" requires expression`, this.template, loc));
2463
- }
2464
- }
2465
- requireNoExpression({ expression, name, loc }) {
2466
- if (expression) {
2467
- throw this.options.debug?.(new CompileError(`"${name}" should not have expression`, this.template, loc));
2468
- }
2639
+ emitExpErr({ name, loc }, required = true) {
2640
+ this.options.debug?.(new CompileError(required
2641
+ ? `"${name}" requires expression`
2642
+ : `"${name}" should not have expression`, this.template, loc));
2469
2643
  }
2470
2644
  }
2471
2645
 
@@ -2514,17 +2688,14 @@ class Compiler extends Context {
2514
2688
  writable: true,
2515
2689
  value: void 0
2516
2690
  });
2517
- this.options = {
2518
- ...compilerOptions,
2519
- ...options,
2520
- };
2691
+ this.options = mergeOptions(compilerOptions, options);
2521
2692
  }
2522
2693
  async compile(template, root = true, partials = new Map(), blocks = new Map()) {
2523
2694
  this.template = template;
2524
2695
  this.isRoot = root;
2525
2696
  this.partials = partials;
2526
2697
  this.blocks = blocks;
2527
- this.rootNode = new Parser(this.options).parse(template);
2698
+ this.rootNode = await new Parser(this.options).parse(template);
2528
2699
  this.state = {};
2529
2700
  this.start();
2530
2701
  await this.parseTemplates();
@@ -2585,12 +2756,12 @@ class Compiler extends Context {
2585
2756
  const partials = new Map();
2586
2757
  const blocks = [];
2587
2758
  const traverse = (node) => {
2588
- if (node.type === NodeType.INCLUDE) {
2759
+ if (node.type === 'INCLUDE') {
2589
2760
  if (!partials.has(node.val.value)) {
2590
2761
  partials.set(node.val.value, node);
2591
2762
  }
2592
2763
  }
2593
- if (node.type === NodeType.BLOCK) {
2764
+ if (node.type === 'BLOCK') {
2594
2765
  blocks.push(node);
2595
2766
  }
2596
2767
  node.traverse(traverse);
@@ -2602,15 +2773,16 @@ class Compiler extends Context {
2602
2773
  };
2603
2774
  }
2604
2775
  async compileNode(node) {
2605
- if (node.type === NodeType.TEMPLATE) {
2776
+ if (node.type === 'TEMPLATE') {
2606
2777
  await this.compileNodes(node.body);
2607
2778
  return;
2608
2779
  }
2609
- if (this.options.compilers[node.type]) {
2610
- await this.options.compilers[node.type](node, this);
2780
+ const compiler = this.options.compilers[node.type];
2781
+ if (compiler) {
2782
+ await compiler(node, this);
2611
2783
  return;
2612
2784
  }
2613
- this.options.debug?.(new CompileError(`Unknown "${node.name}" directive`, this.template, node.loc));
2785
+ this.options.debug?.(new CompileError(`Unknown "${node.name}" node`, this.template, node.loc));
2614
2786
  }
2615
2787
  async compileNodes(nodes) {
2616
2788
  for (const child of nodes) {
@@ -2653,23 +2825,14 @@ class RenderError extends CompileError {
2653
2825
  }
2654
2826
 
2655
2827
  class Renderer {
2656
- constructor({ globals, filters, parsers, compilers, plugins, ...options } = {}) {
2828
+ constructor(options) {
2657
2829
  Object.defineProperty(this, "options", {
2658
2830
  enumerable: true,
2659
2831
  configurable: true,
2660
2832
  writable: true,
2661
2833
  value: void 0
2662
2834
  });
2663
- this.options = { ...renderOptions, ...options };
2664
- Object.assign(this.options.globals, globals);
2665
- Object.assign(this.options.filters, filters);
2666
- Object.assign(this.options.parsers, parsers);
2667
- Object.assign(this.options.compilers, compilers);
2668
- plugins?.forEach((plugin) => {
2669
- Object.assign(this.options.filters, plugin.filters);
2670
- Object.assign(this.options.parsers, plugin.parsers);
2671
- Object.assign(this.options.compilers, plugin.compilers);
2672
- });
2835
+ this.options = mergeOptions(renderOptions, options);
2673
2836
  }
2674
2837
  async render(template, globals) {
2675
2838
  const compiler = new Compiler(this.options);