janja 2.1.0 → 2.1.1

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,198 +1,493 @@
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", {
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$a = {
423
+ BLOCK: compileBlock,
424
+ SUPER: compileSuper,
425
+ };
426
+
427
+ const createUnexpected = (token, parser) => parser.createUnexpectedNode(token);
428
+
429
+ class Traversal {
430
+ constructor() {
431
+ Object.defineProperty(this, "type", {
147
432
  enumerable: true,
148
433
  configurable: true,
149
434
  writable: true,
150
- value: body
435
+ value: null
151
436
  });
152
- Object.defineProperty(this, "alternatives", {
437
+ Object.defineProperty(this, "loc", {
153
438
  enumerable: true,
154
439
  configurable: true,
155
440
  writable: true,
156
- value: alternatives
441
+ value: null
157
442
  });
158
- Object.defineProperty(this, "loc", {
443
+ Object.defineProperty(this, "body", {
159
444
  enumerable: true,
160
445
  configurable: true,
161
446
  writable: true,
162
- value: loc
447
+ value: void 0
163
448
  });
164
- Object.defineProperty(this, "strip", {
449
+ }
450
+ traverse(cb) {
451
+ this.body?.forEach(cb);
452
+ }
453
+ }
454
+ class RootNode extends Traversal {
455
+ constructor(body, loc) {
456
+ super();
457
+ Object.defineProperty(this, "body", {
165
458
  enumerable: true,
166
459
  configurable: true,
167
460
  writable: true,
168
- value: strip
461
+ value: body
462
+ });
463
+ Object.defineProperty(this, "loc", {
464
+ enumerable: true,
465
+ configurable: true,
466
+ writable: true,
467
+ value: loc
169
468
  });
170
469
  Object.defineProperty(this, "type", {
171
470
  enumerable: true,
172
471
  configurable: true,
173
472
  writable: true,
174
- value: NodeType.IF
473
+ value: 'TEMPLATE'
175
474
  });
176
475
  }
177
- traverse(cb) {
178
- this.body?.forEach(cb);
179
- this.alternatives?.forEach((node) => node.body?.forEach(cb));
180
- }
181
476
  }
182
- class ElseIfNode extends Traversal {
183
- constructor(test, body, loc, strip) {
477
+ class UnknownNode extends Traversal {
478
+ constructor(name, val, loc, strip) {
184
479
  super();
185
- Object.defineProperty(this, "test", {
480
+ Object.defineProperty(this, "name", {
186
481
  enumerable: true,
187
482
  configurable: true,
188
483
  writable: true,
189
- value: test
484
+ value: name
190
485
  });
191
- Object.defineProperty(this, "body", {
486
+ Object.defineProperty(this, "val", {
192
487
  enumerable: true,
193
488
  configurable: true,
194
489
  writable: true,
195
- value: body
490
+ value: val
196
491
  });
197
492
  Object.defineProperty(this, "loc", {
198
493
  enumerable: true,
@@ -210,18 +505,24 @@ class ElseIfNode extends Traversal {
210
505
  enumerable: true,
211
506
  configurable: true,
212
507
  writable: true,
213
- value: NodeType.ELSE_IF
508
+ value: 'UNKNOWN'
214
509
  });
215
510
  }
216
511
  }
217
- class ElseNode extends Traversal {
218
- constructor(body, loc, strip) {
512
+ class UnexpectedNode extends Traversal {
513
+ constructor(name, val, loc, strip) {
219
514
  super();
220
- Object.defineProperty(this, "body", {
515
+ Object.defineProperty(this, "name", {
221
516
  enumerable: true,
222
517
  configurable: true,
223
518
  writable: true,
224
- value: body
519
+ value: name
520
+ });
521
+ Object.defineProperty(this, "val", {
522
+ enumerable: true,
523
+ configurable: true,
524
+ writable: true,
525
+ value: val
225
526
  });
226
527
  Object.defineProperty(this, "loc", {
227
528
  enumerable: true,
@@ -239,18 +540,19 @@ class ElseNode extends Traversal {
239
540
  enumerable: true,
240
541
  configurable: true,
241
542
  writable: true,
242
- value: NodeType.ELSE
543
+ value: 'UNEXPECTED'
243
544
  });
244
545
  }
245
546
  }
246
- class ForNode extends Traversal {
247
- constructor(loop, body, loc, strip) {
547
+
548
+ class BlockNode extends Traversal {
549
+ constructor(val, body, loc, strip) {
248
550
  super();
249
- Object.defineProperty(this, "loop", {
551
+ Object.defineProperty(this, "val", {
250
552
  enumerable: true,
251
553
  configurable: true,
252
554
  writable: true,
253
- value: loop
555
+ value: val
254
556
  });
255
557
  Object.defineProperty(this, "body", {
256
558
  enumerable: true,
@@ -274,11 +576,11 @@ class ForNode extends Traversal {
274
576
  enumerable: true,
275
577
  configurable: true,
276
578
  writable: true,
277
- value: NodeType.FOR
579
+ value: 'BLOCK'
278
580
  });
279
581
  }
280
582
  }
281
- class BreakNode extends Traversal {
583
+ class SuperNode extends Traversal {
282
584
  constructor(val, loc, strip) {
283
585
  super();
284
586
  Object.defineProperty(this, "val", {
@@ -303,53 +605,206 @@ class BreakNode extends Traversal {
303
605
  enumerable: true,
304
606
  configurable: true,
305
607
  writable: true,
306
- value: NodeType.BREAK
608
+ value: 'SUPER'
307
609
  });
308
610
  }
309
611
  }
310
- class ContinueNode extends Traversal {
311
- constructor(val, loc, strip) {
312
- super();
313
- Object.defineProperty(this, "val", {
314
- enumerable: true,
315
- configurable: true,
316
- writable: true,
317
- value: val
318
- });
319
- Object.defineProperty(this, "loc", {
320
- enumerable: true,
321
- configurable: true,
322
- writable: true,
323
- value: loc
324
- });
325
- Object.defineProperty(this, "strip", {
612
+
613
+ function parseBlock(token, parser) {
614
+ if (!token.expression) {
615
+ parser.emitExpErr(token);
616
+ return;
617
+ }
618
+ parser.advance();
619
+ const body = parser.parseUntil(['endblock']);
620
+ if (parser.match(['endblock'])) {
621
+ parser.advance();
622
+ }
623
+ else {
624
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
625
+ }
626
+ return new BlockNode(parser.parseExp(token.expression), body, token.loc, token.strip);
627
+ }
628
+ function parseSuper(token, parser) {
629
+ if (token.expression) {
630
+ parser.emitExpErr(token, false);
631
+ return;
632
+ }
633
+ parser.advance();
634
+ return new SuperNode(token.val, token.loc, token.strip);
635
+ }
636
+ const parsers$a = {
637
+ block: parseBlock,
638
+ super: parseSuper,
639
+ endblock: createUnexpected,
640
+ };
641
+
642
+ const plugin$a = {
643
+ compilers: compilers$a,
644
+ parsers: parsers$a,
645
+ };
646
+
647
+ const expTokenOperators = {
648
+ AND: '&&',
649
+ OR: '||',
650
+ IS: '',
651
+ NOT: '!',
652
+ EQ: '===',
653
+ NE: '!==',
654
+ GT: '>',
655
+ LT: '<',
656
+ GE: '>=',
657
+ LE: '<=',
658
+ IN: ' in ',
659
+ NI: ' in ',
660
+ OF: ' of ',
661
+ ADD: '+',
662
+ SUB: '-',
663
+ MUL: '*',
664
+ DIV: '/',
665
+ MOD: '%',
666
+ PIPE: '',
667
+ ASSIGN: '=',
668
+ LP: '(',
669
+ RP: ')',
670
+ COMMA: ',',
671
+ DOT: '.',
672
+ ID: '',
673
+ LIT: '',
674
+ IF: '',
675
+ ELSE: '',
676
+ };
677
+ class ExpCompiler {
678
+ constructor() {
679
+ Object.defineProperty(this, "context", {
326
680
  enumerable: true,
327
681
  configurable: true,
328
682
  writable: true,
329
- value: strip
683
+ value: void 0
330
684
  });
331
- Object.defineProperty(this, "type", {
685
+ Object.defineProperty(this, "filters", {
332
686
  enumerable: true,
333
687
  configurable: true,
334
688
  writable: true,
335
- value: NodeType.CONTINUE
689
+ value: void 0
336
690
  });
337
691
  }
692
+ compile(expression, context = CONTEXT, filters = FILTERS) {
693
+ this.context = context;
694
+ this.filters = filters;
695
+ return expression ? this.compileExp(expression) : '""';
696
+ }
697
+ compileExp(expression) {
698
+ switch (expression.type) {
699
+ case 'NOT':
700
+ return this.compileNot(expression);
701
+ case 'ID':
702
+ return this.compileId(expression);
703
+ case 'LIT':
704
+ return this.compileLit(expression);
705
+ case 'PIPE':
706
+ return this.compilePipe(expression);
707
+ case 'OF':
708
+ return this.compileOf(expression);
709
+ case 'ASSIGN':
710
+ return this.compileAssign(expression);
711
+ case 'IS':
712
+ return this.compileIs(expression);
713
+ case 'AND':
714
+ case 'OR':
715
+ case 'EQ':
716
+ case 'NE':
717
+ case 'GT':
718
+ case 'LT':
719
+ case 'GE':
720
+ case 'LE':
721
+ case 'IN':
722
+ case 'NI':
723
+ case 'ADD':
724
+ case 'SUB':
725
+ case 'MUL':
726
+ case 'DIV':
727
+ case 'MOD':
728
+ return this.compileBinary(expression);
729
+ case 'IF':
730
+ return this.compileTernary(expression);
731
+ case 'SEQ':
732
+ return this.compileSeq(expression);
733
+ // no default
734
+ }
735
+ }
736
+ compileNot({ argument }) {
737
+ return `!${this.compileExp(argument)}`;
738
+ }
739
+ compileId({ value, path, args }) {
740
+ let s = `${this.context}.${value}`;
741
+ if (path) {
742
+ s += path.map((p) => `.${p.value}`).join('');
743
+ }
744
+ if (args) {
745
+ s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
746
+ }
747
+ return s;
748
+ }
749
+ compileLit({ value }) {
750
+ return value === undefined ? 'undefined' : JSON.stringify(value);
751
+ }
752
+ compileSeq({ elements }) {
753
+ return elements.map((element) => this.compileExp(element)).toString();
754
+ }
755
+ compilePipe({ left, right }) {
756
+ const { value: name, args = [] } = right;
757
+ 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(',')}))`;
758
+ }
759
+ compileOf({ left, right }) {
760
+ // destructuring
761
+ if (left.type === 'SEQ') {
762
+ return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
763
+ }
764
+ return `const ${left.value} of ${this.compileExp(right)}`;
765
+ }
766
+ compileAssign({ left, right }) {
767
+ if (left.type === 'ID') {
768
+ return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
769
+ }
770
+ // destructuring
771
+ return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
772
+ }
773
+ compileIs({ left, right }) {
774
+ return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
775
+ }
776
+ compileBinary({ type, left, right }) {
777
+ const ret = `${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)}`;
778
+ return type === 'NI' ? `!${ret}` : ret;
779
+ }
780
+ compileTernary({ test, consequent, alternative }) {
781
+ return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
782
+ }
338
783
  }
339
- class UnknownDirectiveNode extends Traversal {
340
- constructor(name, val, loc, strip) {
784
+
785
+ async function compileCall({ val, body, loc }, compiler) {
786
+ compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
787
+ await compiler.compileNodes(body);
788
+ compiler.pushRaw(null, '});');
789
+ }
790
+ const compilers$9 = {
791
+ CALL: compileCall,
792
+ };
793
+
794
+ class CallNode extends Traversal {
795
+ constructor(val, body, loc, strip) {
341
796
  super();
342
- Object.defineProperty(this, "name", {
797
+ Object.defineProperty(this, "val", {
343
798
  enumerable: true,
344
799
  configurable: true,
345
800
  writable: true,
346
- value: name
801
+ value: val
347
802
  });
348
- Object.defineProperty(this, "val", {
803
+ Object.defineProperty(this, "body", {
349
804
  enumerable: true,
350
805
  configurable: true,
351
806
  writable: true,
352
- value: val
807
+ value: body
353
808
  });
354
809
  Object.defineProperty(this, "loc", {
355
810
  enumerable: true,
@@ -367,24 +822,59 @@ class UnknownDirectiveNode extends Traversal {
367
822
  enumerable: true,
368
823
  configurable: true,
369
824
  writable: true,
370
- value: NodeType.UNKNOWN
825
+ value: 'CALL'
371
826
  });
372
827
  }
373
828
  }
374
- class UnexpectedDirectiveNode extends Traversal {
375
- constructor(name, val, loc, strip) {
829
+
830
+ function parseCall(token, parser) {
831
+ if (!token.expression) {
832
+ parser.emitExpErr(token);
833
+ return;
834
+ }
835
+ parser.advance();
836
+ const body = parser.parseUntil(['endcall']);
837
+ if (parser.match(['endcall'])) {
838
+ parser.advance();
839
+ }
840
+ else {
841
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
842
+ }
843
+ return new CallNode(parser.parseExp(token.expression), body, token.loc, token.strip);
844
+ }
845
+ const parsers$9 = {
846
+ call: parseCall,
847
+ endcall: createUnexpected,
848
+ };
849
+
850
+ const plugin$9 = {
851
+ compilers: compilers$9,
852
+ parsers: parsers$9,
853
+ };
854
+
855
+ async function compileCapture({ val, body, loc }, compiler) {
856
+ compiler.pushRaw(loc, `${compiler.context}.${val.value}=await(async(s)=>{`);
857
+ await compiler.compileNodes(body);
858
+ compiler.pushRaw(null, 'return s;})("");');
859
+ }
860
+ const compilers$8 = {
861
+ CAPTURE: compileCapture,
862
+ };
863
+
864
+ class CaptureNode extends Traversal {
865
+ constructor(val, body, loc, strip) {
376
866
  super();
377
- Object.defineProperty(this, "name", {
867
+ Object.defineProperty(this, "val", {
378
868
  enumerable: true,
379
869
  configurable: true,
380
870
  writable: true,
381
- value: name
871
+ value: val
382
872
  });
383
- Object.defineProperty(this, "val", {
873
+ Object.defineProperty(this, "body", {
384
874
  enumerable: true,
385
875
  configurable: true,
386
876
  writable: true,
387
- value: val
877
+ value: body
388
878
  });
389
879
  Object.defineProperty(this, "loc", {
390
880
  enumerable: true,
@@ -402,40 +892,46 @@ class UnexpectedDirectiveNode extends Traversal {
402
892
  enumerable: true,
403
893
  configurable: true,
404
894
  writable: true,
405
- value: NodeType.UNEXPECTED
895
+ value: 'CAPTURE'
406
896
  });
407
897
  }
408
898
  }
409
- class CommentNode extends Traversal {
410
- constructor(val, loc, strip) {
411
- super();
412
- Object.defineProperty(this, "val", {
413
- enumerable: true,
414
- configurable: true,
415
- writable: true,
416
- value: val
417
- });
418
- Object.defineProperty(this, "loc", {
419
- enumerable: true,
420
- configurable: true,
421
- writable: true,
422
- value: loc
423
- });
424
- Object.defineProperty(this, "strip", {
425
- enumerable: true,
426
- configurable: true,
427
- writable: true,
428
- value: strip
429
- });
430
- Object.defineProperty(this, "type", {
431
- enumerable: true,
432
- configurable: true,
433
- writable: true,
434
- value: NodeType.COMMENT
435
- });
899
+
900
+ function parseCapture(token, parser) {
901
+ if (!token.expression) {
902
+ parser.emitExpErr(token);
903
+ return;
436
904
  }
905
+ parser.advance();
906
+ const body = parser.parseUntil(['endcapture']);
907
+ if (parser.match(['endcapture'])) {
908
+ parser.advance();
909
+ }
910
+ else {
911
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
912
+ }
913
+ return new CaptureNode(parser.parseExp(token.expression), body, token.loc, token.strip);
437
914
  }
438
- class IncludeNode extends Traversal {
915
+ const parsers$8 = {
916
+ capture: parseCapture,
917
+ endcapture: createUnexpected,
918
+ };
919
+
920
+ const plugin$8 = {
921
+ compilers: compilers$8,
922
+ parsers: parsers$8,
923
+ };
924
+
925
+ async function compileComment({ val, loc }, compiler) {
926
+ if (!compiler.options.stripComments) {
927
+ compiler.pushStr(loc, `<!--${val}-->`);
928
+ }
929
+ }
930
+ const compilers$7 = {
931
+ COMMENT: compileComment,
932
+ };
933
+
934
+ class CommentNode extends Traversal {
439
935
  constructor(val, loc, strip) {
440
936
  super();
441
937
  Object.defineProperty(this, "val", {
@@ -460,18 +956,56 @@ class IncludeNode extends Traversal {
460
956
  enumerable: true,
461
957
  configurable: true,
462
958
  writable: true,
463
- value: NodeType.INCLUDE
959
+ value: 'COMMENT'
464
960
  });
465
961
  }
466
962
  }
467
- class BlockNode extends Traversal {
468
- constructor(val, body, loc, strip) {
963
+
964
+ function parseComment({ val, loc, strip }, parser) {
965
+ parser.advance();
966
+ return new CommentNode(val, loc, strip);
967
+ }
968
+ const parsers$7 = {
969
+ comment: parseComment,
970
+ };
971
+
972
+ const plugin$7 = {
973
+ compilers: compilers$7,
974
+ parsers: parsers$7,
975
+ };
976
+
977
+ async function compileFor({ loop, body }, compiler) {
978
+ const { context } = compiler;
979
+ if (loop.left.type === 'SEQ') {
980
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.elements.map(({ value }) => value).join(',')},`, '};');
981
+ }
982
+ else {
983
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, '};');
984
+ }
985
+ await compiler.compileNodes(body);
986
+ compiler.out();
987
+ compiler.pushRaw(null, '}');
988
+ }
989
+ function compileBreak({ loc }, compiler) {
990
+ compiler.pushRaw(loc, 'break;');
991
+ }
992
+ function compileContinue({ loc }, compiler) {
993
+ compiler.pushRaw(loc, 'continue;');
994
+ }
995
+ const compilers$6 = {
996
+ FOR: compileFor,
997
+ BREAK: compileBreak,
998
+ CONTINUE: compileContinue,
999
+ };
1000
+
1001
+ class ForNode extends Traversal {
1002
+ constructor(loop, body, loc, strip) {
469
1003
  super();
470
- Object.defineProperty(this, "val", {
1004
+ Object.defineProperty(this, "loop", {
471
1005
  enumerable: true,
472
1006
  configurable: true,
473
1007
  writable: true,
474
- value: val
1008
+ value: loop
475
1009
  });
476
1010
  Object.defineProperty(this, "body", {
477
1011
  enumerable: true,
@@ -495,11 +1029,11 @@ class BlockNode extends Traversal {
495
1029
  enumerable: true,
496
1030
  configurable: true,
497
1031
  writable: true,
498
- value: NodeType.BLOCK
1032
+ value: 'FOR'
499
1033
  });
500
1034
  }
501
1035
  }
502
- class SuperNode extends Traversal {
1036
+ class BreakNode extends Traversal {
503
1037
  constructor(val, loc, strip) {
504
1038
  super();
505
1039
  Object.defineProperty(this, "val", {
@@ -524,12 +1058,12 @@ class SuperNode extends Traversal {
524
1058
  enumerable: true,
525
1059
  configurable: true,
526
1060
  writable: true,
527
- value: NodeType.SUPER
1061
+ value: 'BREAK'
528
1062
  });
529
1063
  }
530
1064
  }
531
- class MacroNode extends Traversal {
532
- constructor(val, body, loc, strip) {
1065
+ class ContinueNode extends Traversal {
1066
+ constructor(val, loc, strip) {
533
1067
  super();
534
1068
  Object.defineProperty(this, "val", {
535
1069
  enumerable: true,
@@ -537,12 +1071,6 @@ class MacroNode extends Traversal {
537
1071
  writable: true,
538
1072
  value: val
539
1073
  });
540
- Object.defineProperty(this, "body", {
541
- enumerable: true,
542
- configurable: true,
543
- writable: true,
544
- value: body
545
- });
546
1074
  Object.defineProperty(this, "loc", {
547
1075
  enumerable: true,
548
1076
  configurable: true,
@@ -559,18 +1087,104 @@ class MacroNode extends Traversal {
559
1087
  enumerable: true,
560
1088
  configurable: true,
561
1089
  writable: true,
562
- value: NodeType.MACRO
1090
+ value: 'CONTINUE'
563
1091
  });
564
1092
  }
565
1093
  }
566
- class CallerNode extends Traversal {
567
- constructor(val, loc, strip) {
1094
+
1095
+ const wm$1 = new WeakMap();
1096
+ function parseFor(token, parser) {
1097
+ if (!token.expression) {
1098
+ parser.emitExpErr(token);
1099
+ return;
1100
+ }
1101
+ wm$1.set(parser, true);
1102
+ parser.advance();
1103
+ const body = parser.parseUntil(['endfor']);
1104
+ wm$1.set(parser, false);
1105
+ if (parser.match(['endfor'])) {
1106
+ parser.advance();
1107
+ }
1108
+ else {
1109
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1110
+ }
1111
+ return new ForNode(parser.parseExp(token.expression), body, token.loc, token.strip);
1112
+ }
1113
+ function parseBreak(token, parser) {
1114
+ if (token.expression) {
1115
+ parser.emitExpErr(token, false);
1116
+ return;
1117
+ }
1118
+ if (!wm$1.get(parser)) {
1119
+ parser.options.debug?.(new CompileError('"break" directive used outside of a loop', parser.template, token.loc));
1120
+ return;
1121
+ }
1122
+ parser.advance();
1123
+ return new BreakNode(token.val, token.loc, token.strip);
1124
+ }
1125
+ function parseContinue(token, parser) {
1126
+ if (token.expression) {
1127
+ parser.emitExpErr(token, false);
1128
+ return;
1129
+ }
1130
+ if (!wm$1.get(parser)) {
1131
+ parser.options.debug?.(new CompileError('"continue" directive used outside of a loop', parser.template, token.loc));
1132
+ return;
1133
+ }
1134
+ parser.advance();
1135
+ return new ContinueNode(token.val, token.loc, token.strip);
1136
+ }
1137
+ const parsers$6 = {
1138
+ for: parseFor,
1139
+ break: parseBreak,
1140
+ continue: parseContinue,
1141
+ endfor: createUnexpected,
1142
+ };
1143
+
1144
+ const plugin$6 = {
1145
+ compilers: compilers$6,
1146
+ parsers: parsers$6,
1147
+ };
1148
+
1149
+ async function compileIf({ test, body, alternatives }, compiler) {
1150
+ compiler.pushRaw(test.loc, `if(${new ExpCompiler().compile(test, compiler.context)}){`);
1151
+ await compiler.compileNodes(body);
1152
+ compiler.pushRaw(null, '}');
1153
+ for (const branch of alternatives) {
1154
+ if (branch.type === 'ELSE_IF') {
1155
+ compiler.pushRaw(branch.test.loc, `else if(${new ExpCompiler().compile(branch.test, compiler.context)}){`);
1156
+ }
1157
+ else {
1158
+ compiler.pushRaw(null, 'else{');
1159
+ }
1160
+ await compiler.compileNodes(branch.body);
1161
+ compiler.pushRaw(null, '}');
1162
+ }
1163
+ }
1164
+ const compilers$5 = {
1165
+ IF: compileIf,
1166
+ };
1167
+
1168
+ class IfNode extends Traversal {
1169
+ constructor(test, body, alternatives, loc, strip) {
568
1170
  super();
569
- Object.defineProperty(this, "val", {
1171
+ Object.defineProperty(this, "test", {
570
1172
  enumerable: true,
571
1173
  configurable: true,
572
1174
  writable: true,
573
- value: val
1175
+ value: test
1176
+ });
1177
+ Object.defineProperty(this, "body", {
1178
+ enumerable: true,
1179
+ configurable: true,
1180
+ writable: true,
1181
+ value: body
1182
+ });
1183
+ Object.defineProperty(this, "alternatives", {
1184
+ enumerable: true,
1185
+ configurable: true,
1186
+ writable: true,
1187
+ value: alternatives
574
1188
  });
575
1189
  Object.defineProperty(this, "loc", {
576
1190
  enumerable: true,
@@ -588,18 +1202,22 @@ class CallerNode extends Traversal {
588
1202
  enumerable: true,
589
1203
  configurable: true,
590
1204
  writable: true,
591
- value: NodeType.CALLER
1205
+ value: 'IF'
592
1206
  });
593
1207
  }
1208
+ traverse(cb) {
1209
+ this.body?.forEach(cb);
1210
+ this.alternatives?.forEach((node) => node.body?.forEach(cb));
1211
+ }
594
1212
  }
595
- class CallNode extends Traversal {
596
- constructor(val, body, loc, strip) {
1213
+ class ElseIfNode extends Traversal {
1214
+ constructor(test, body, loc, strip) {
597
1215
  super();
598
- Object.defineProperty(this, "val", {
1216
+ Object.defineProperty(this, "test", {
599
1217
  enumerable: true,
600
1218
  configurable: true,
601
1219
  writable: true,
602
- value: val
1220
+ value: test
603
1221
  });
604
1222
  Object.defineProperty(this, "body", {
605
1223
  enumerable: true,
@@ -623,18 +1241,18 @@ class CallNode extends Traversal {
623
1241
  enumerable: true,
624
1242
  configurable: true,
625
1243
  writable: true,
626
- value: NodeType.CALL
1244
+ value: 'ELSE_IF'
627
1245
  });
628
1246
  }
629
1247
  }
630
- class SetNode extends Traversal {
631
- constructor(val, loc, strip) {
1248
+ class ElseNode extends Traversal {
1249
+ constructor(body, loc, strip) {
632
1250
  super();
633
- Object.defineProperty(this, "val", {
1251
+ Object.defineProperty(this, "body", {
634
1252
  enumerable: true,
635
1253
  configurable: true,
636
1254
  writable: true,
637
- value: val
1255
+ value: body
638
1256
  });
639
1257
  Object.defineProperty(this, "loc", {
640
1258
  enumerable: true,
@@ -652,12 +1270,80 @@ class SetNode extends Traversal {
652
1270
  enumerable: true,
653
1271
  configurable: true,
654
1272
  writable: true,
655
- value: NodeType.SET
1273
+ value: 'ELSE'
656
1274
  });
657
1275
  }
658
1276
  }
659
- class CaptureNode extends Traversal {
660
- constructor(val, body, loc, strip) {
1277
+
1278
+ function parseIf(token, parser) {
1279
+ if (!token.expression) {
1280
+ parser.emitExpErr(token);
1281
+ return;
1282
+ }
1283
+ parser.advance();
1284
+ const body = parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']);
1285
+ const alternatives = [];
1286
+ while (parser.match(['else', 'elseif', 'elsif', 'elif'])) {
1287
+ const branchToken = parser.peek();
1288
+ if (branchToken.name.toLowerCase() === 'else') {
1289
+ const elseNode = parseElse(branchToken, parser);
1290
+ if (elseNode) {
1291
+ alternatives.push(elseNode);
1292
+ }
1293
+ }
1294
+ else {
1295
+ const elseIfNode = parseElseIf(branchToken, parser);
1296
+ if (elseIfNode) {
1297
+ alternatives.push(elseIfNode);
1298
+ }
1299
+ }
1300
+ }
1301
+ if (parser.match(['endif'])) {
1302
+ parser.advance();
1303
+ }
1304
+ else {
1305
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1306
+ }
1307
+ return new IfNode(parser.parseExp(token.expression), body, alternatives, token.loc, token.strip);
1308
+ }
1309
+ function parseElseIf(token, parser) {
1310
+ if (!token.expression) {
1311
+ parser.emitExpErr(token);
1312
+ return;
1313
+ }
1314
+ parser.advance();
1315
+ return new ElseIfNode(parser.parseExp(token.expression), parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']), token.loc, token.strip);
1316
+ }
1317
+ function parseElse(token, parser) {
1318
+ if (token.expression) {
1319
+ parser.emitExpErr(token, false);
1320
+ return;
1321
+ }
1322
+ parser.advance();
1323
+ return new ElseNode(parser.parseUntil(['endif']), token.loc, token.strip);
1324
+ }
1325
+ const parsers$5 = {
1326
+ if: parseIf,
1327
+ elseif: createUnexpected,
1328
+ elsif: createUnexpected,
1329
+ elif: createUnexpected,
1330
+ endif: createUnexpected,
1331
+ };
1332
+
1333
+ const plugin$5 = {
1334
+ compilers: compilers$5,
1335
+ parsers: parsers$5,
1336
+ };
1337
+
1338
+ async function compileInclude({ val: { value }, loc }, compiler) {
1339
+ compiler.pushRaw(loc, `s+=await p["${value}"]?.()??"";`);
1340
+ }
1341
+ const compilers$4 = {
1342
+ INCLUDE: compileInclude,
1343
+ };
1344
+
1345
+ class IncludeNode extends Traversal {
1346
+ constructor(val, loc, strip) {
661
1347
  super();
662
1348
  Object.defineProperty(this, "val", {
663
1349
  enumerable: true,
@@ -665,12 +1351,6 @@ class CaptureNode extends Traversal {
665
1351
  writable: true,
666
1352
  value: val
667
1353
  });
668
- Object.defineProperty(this, "body", {
669
- enumerable: true,
670
- configurable: true,
671
- writable: true,
672
- value: body
673
- });
674
1354
  Object.defineProperty(this, "loc", {
675
1355
  enumerable: true,
676
1356
  configurable: true,
@@ -681,698 +1361,32 @@ class CaptureNode extends Traversal {
681
1361
  enumerable: true,
682
1362
  configurable: true,
683
1363
  writable: true,
684
- value: strip
685
- });
686
- Object.defineProperty(this, "type", {
687
- enumerable: true,
688
- configurable: true,
689
- writable: true,
690
- value: NodeType.CAPTURE
691
- });
692
- }
693
- }
694
-
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(',')},`, '};');
1332
- }
1333
- else {
1334
- compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, '};');
1335
- }
1336
- await compiler.compileNodes(body);
1337
- compiler.out();
1338
- compiler.pushRaw(null, '}');
1339
- }
1340
- function compileBreak({ loc }, compiler) {
1341
- compiler.pushRaw(loc, 'break;');
1342
- }
1343
- function compileContinue({ loc }, compiler) {
1344
- compiler.pushRaw(loc, 'continue;');
1364
+ value: strip
1365
+ });
1366
+ Object.defineProperty(this, "type", {
1367
+ enumerable: true,
1368
+ configurable: true,
1369
+ writable: true,
1370
+ value: 'INCLUDE'
1371
+ });
1372
+ }
1345
1373
  }
1346
- const compilers$7 = {
1347
- [NodeType.FOR]: compileFor,
1348
- [NodeType.BREAK]: compileBreak,
1349
- [NodeType.CONTINUE]: compileContinue,
1350
- };
1351
1374
 
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, '}');
1375
+ function parseInclude(token, parser) {
1376
+ if (!token.expression) {
1377
+ parser.emitExpErr(token);
1378
+ return;
1365
1379
  }
1380
+ parser.advance();
1381
+ return new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
1366
1382
  }
1367
- const compilers$6 = {
1368
- [NodeType.IF]: compileIf,
1383
+ const parsers$4 = {
1384
+ include: parseInclude,
1369
1385
  };
1370
1386
 
1371
- async function compileInclude({ val: { value }, loc }, compiler) {
1372
- compiler.pushRaw(loc, `s+=await p["${value}"]?.()??"";`);
1373
- }
1374
- const compilers$5 = {
1375
- [NodeType.INCLUDE]: compileInclude,
1387
+ const plugin$4 = {
1388
+ compilers: compilers$4,
1389
+ parsers: parsers$4,
1376
1390
  };
1377
1391
 
1378
1392
  async function compileMacro({ val: { left, right }, loc, body }, compiler) {
@@ -1380,11 +1394,11 @@ async function compileMacro({ val: { left, right }, loc, body }, compiler) {
1380
1394
  const { elements } = right;
1381
1395
  const expCompiler = new ExpCompiler();
1382
1396
  compiler.pushRaw(loc, `${expCompiler.compile(left)}=(${elements
1383
- .map((el) => el.type === 'SET'
1397
+ .map((el) => el.type === 'ASSIGN'
1384
1398
  ? `${el.left.value}=${expCompiler.compile(el.right)}`
1385
1399
  : el.value)
1386
1400
  .join(',')})=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, elements
1387
- .map((el) => el.type === 'SET' ? el.left.value : el.value)
1401
+ .map((el) => el.type === 'ASSIGN' ? el.left.value : el.value)
1388
1402
  .join(','), '};');
1389
1403
  await compiler.compileNodes(body);
1390
1404
  compiler.out();
@@ -1393,254 +1407,358 @@ async function compileMacro({ val: { left, right }, loc, body }, compiler) {
1393
1407
  function compileCaller({ loc }, compiler) {
1394
1408
  compiler.pushRaw(loc, 'await _c?.();');
1395
1409
  }
1396
- const compilers$4 = {
1397
- [NodeType.MACRO]: compileMacro,
1398
- [NodeType.CALLER]: compileCaller,
1410
+ const compilers$3 = {
1411
+ MACRO: compileMacro,
1412
+ CALLER: compileCaller,
1399
1413
  };
1400
1414
 
1401
- async function compileOutput({ exp }, compiler) {
1402
- compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1415
+ class MacroNode extends Traversal {
1416
+ constructor(val, body, loc, strip) {
1417
+ super();
1418
+ Object.defineProperty(this, "val", {
1419
+ enumerable: true,
1420
+ configurable: true,
1421
+ writable: true,
1422
+ value: val
1423
+ });
1424
+ Object.defineProperty(this, "body", {
1425
+ enumerable: true,
1426
+ configurable: true,
1427
+ writable: true,
1428
+ value: body
1429
+ });
1430
+ Object.defineProperty(this, "loc", {
1431
+ enumerable: true,
1432
+ configurable: true,
1433
+ writable: true,
1434
+ value: loc
1435
+ });
1436
+ Object.defineProperty(this, "strip", {
1437
+ enumerable: true,
1438
+ configurable: true,
1439
+ writable: true,
1440
+ value: strip
1441
+ });
1442
+ Object.defineProperty(this, "type", {
1443
+ enumerable: true,
1444
+ configurable: true,
1445
+ writable: true,
1446
+ value: 'MACRO'
1447
+ });
1448
+ }
1403
1449
  }
1404
- const compilers$3 = {
1405
- [NodeType.OUTPUT]: compileOutput,
1450
+ class CallerNode extends Traversal {
1451
+ constructor(val, loc, strip) {
1452
+ super();
1453
+ Object.defineProperty(this, "val", {
1454
+ enumerable: true,
1455
+ configurable: true,
1456
+ writable: true,
1457
+ value: val
1458
+ });
1459
+ Object.defineProperty(this, "loc", {
1460
+ enumerable: true,
1461
+ configurable: true,
1462
+ writable: true,
1463
+ value: loc
1464
+ });
1465
+ Object.defineProperty(this, "strip", {
1466
+ enumerable: true,
1467
+ configurable: true,
1468
+ writable: true,
1469
+ value: strip
1470
+ });
1471
+ Object.defineProperty(this, "type", {
1472
+ enumerable: true,
1473
+ configurable: true,
1474
+ writable: true,
1475
+ value: 'CALLER'
1476
+ });
1477
+ }
1478
+ }
1479
+
1480
+ const wm = new WeakMap();
1481
+ function parseMacro(token, parser) {
1482
+ if (!token.expression) {
1483
+ parser.emitExpErr(token);
1484
+ return;
1485
+ }
1486
+ wm.set(parser, true);
1487
+ parser.advance();
1488
+ const body = parser.parseUntil(['endmacro']);
1489
+ wm.set(parser, false);
1490
+ if (parser.match(['endmacro'])) {
1491
+ parser.advance();
1492
+ }
1493
+ else {
1494
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1495
+ }
1496
+ return new MacroNode(parser.parseExp(token.expression), body, token.loc, token.strip);
1497
+ }
1498
+ function parseCaller(token, parser) {
1499
+ if (token.expression) {
1500
+ parser.emitExpErr(token, false);
1501
+ return;
1502
+ }
1503
+ if (!wm.get(parser)) {
1504
+ parser.options.debug?.(new CompileError('"caller" directive used outside of a macro', parser.template, token.loc));
1505
+ return;
1506
+ }
1507
+ parser.advance();
1508
+ return new CallerNode(token.val, token.loc, token.strip);
1509
+ }
1510
+ const parsers$3 = {
1511
+ macro: parseMacro,
1512
+ caller: parseCaller,
1513
+ endmacro: createUnexpected,
1406
1514
  };
1407
1515
 
1408
- async function compileSet({ val, loc }, compiler) {
1409
- compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
1516
+ const plugin$3 = {
1517
+ compilers: compilers$3,
1518
+ parsers: parsers$3,
1519
+ };
1520
+
1521
+ async function compileOutput({ exp }, compiler) {
1522
+ compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1410
1523
  }
1411
1524
  const compilers$2 = {
1412
- [NodeType.SET]: compileSet,
1525
+ OUTPUT: compileOutput,
1413
1526
  };
1414
1527
 
1415
- async function compileText({ val, loc, strip: { start, end } }, compiler) {
1416
- if (start || compiler.options.trimWhitespace) {
1417
- val = val.replace(/^\s+/, '');
1418
- }
1419
- if (end || compiler.options.trimWhitespace) {
1420
- val = val.replace(/\s+$/, '');
1528
+ class OutputNode extends Traversal {
1529
+ constructor(val, loc, strip, exp) {
1530
+ super();
1531
+ Object.defineProperty(this, "val", {
1532
+ enumerable: true,
1533
+ configurable: true,
1534
+ writable: true,
1535
+ value: val
1536
+ });
1537
+ Object.defineProperty(this, "loc", {
1538
+ enumerable: true,
1539
+ configurable: true,
1540
+ writable: true,
1541
+ value: loc
1542
+ });
1543
+ Object.defineProperty(this, "strip", {
1544
+ enumerable: true,
1545
+ configurable: true,
1546
+ writable: true,
1547
+ value: strip
1548
+ });
1549
+ Object.defineProperty(this, "exp", {
1550
+ enumerable: true,
1551
+ configurable: true,
1552
+ writable: true,
1553
+ value: exp
1554
+ });
1555
+ Object.defineProperty(this, "type", {
1556
+ enumerable: true,
1557
+ configurable: true,
1558
+ writable: true,
1559
+ value: 'OUTPUT'
1560
+ });
1421
1561
  }
1422
- compiler.pushStr(loc, val);
1423
1562
  }
1424
- const compilers$1 = {
1425
- [NodeType.TEXT]: compileText,
1426
- };
1427
1563
 
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,
1564
+ function parseOutput(token, parser) {
1565
+ parser.advance();
1566
+ return new OutputNode(token.val, token.loc, token.strip, parser.parseExp(token));
1567
+ }
1568
+ const parsers$2 = {
1569
+ output: parseOutput,
1440
1570
  };
1441
1571
 
1442
- const parserOptions = {
1443
- commentOpen: '{{#',
1444
- commentClose: '}}',
1445
- directiveOpen: '{{',
1446
- directiveClose: '}}',
1447
- outputOpen: '{{=',
1448
- outputClose: '}}',
1449
- parsers,
1450
- debug: () => { },
1451
- };
1452
- const compilerOptions = {
1453
- ...parserOptions,
1454
- trimWhitespace: false,
1455
- stripComments: false,
1456
- compilers,
1457
- loader: async () => '',
1572
+ const plugin$2 = {
1573
+ compilers: compilers$2,
1574
+ parsers: parsers$2,
1458
1575
  };
1459
- const renderOptions = {
1460
- ...compilerOptions,
1461
- globals: {},
1462
- filters: _filters,
1463
- autoEscape: true,
1464
- plugins: [],
1576
+
1577
+ async function compileSet({ val, loc }, compiler) {
1578
+ compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
1579
+ }
1580
+ const compilers$1 = {
1581
+ SET: compileSet,
1465
1582
  };
1466
1583
 
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", {
1584
+ class SetNode extends Traversal {
1585
+ constructor(val, loc, strip) {
1586
+ super();
1587
+ Object.defineProperty(this, "val", {
1588
+ enumerable: true,
1589
+ configurable: true,
1590
+ writable: true,
1591
+ value: val
1592
+ });
1593
+ Object.defineProperty(this, "loc", {
1594
+ enumerable: true,
1595
+ configurable: true,
1596
+ writable: true,
1597
+ value: loc
1598
+ });
1599
+ Object.defineProperty(this, "strip", {
1600
+ enumerable: true,
1601
+ configurable: true,
1602
+ writable: true,
1603
+ value: strip
1604
+ });
1605
+ Object.defineProperty(this, "type", {
1503
1606
  enumerable: true,
1504
1607
  configurable: true,
1505
1608
  writable: true,
1506
- value: []
1609
+ value: 'SET'
1507
1610
  });
1508
1611
  }
1509
- addMapping(source, target) {
1510
- this.mappings.push({
1511
- source,
1512
- target,
1513
- });
1612
+ }
1613
+
1614
+ function parseSet(token, parser) {
1615
+ if (!token.expression) {
1616
+ parser.emitExpErr(token);
1617
+ return;
1514
1618
  }
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);
1619
+ parser.advance();
1620
+ return new SetNode(parser.parseExp(token.expression), token.loc, token.strip);
1621
+ }
1622
+ const parsers$1 = {
1623
+ set: parseSet,
1624
+ };
1625
+
1626
+ const plugin$1 = {
1627
+ compilers: compilers$1,
1628
+ parsers: parsers$1,
1629
+ };
1630
+
1631
+ async function compileText({ val, loc, strip: { start, end } }, compiler) {
1632
+ if (start || compiler.options.trimWhitespace) {
1633
+ val = val.replace(/^\s+/, '');
1634
+ }
1635
+ if (end || compiler.options.trimWhitespace) {
1636
+ val = val.replace(/\s+$/, '');
1522
1637
  }
1638
+ compiler.pushStr(loc, val);
1523
1639
  }
1640
+ const compilers = {
1641
+ TEXT: compileText,
1642
+ };
1524
1643
 
1525
- class OutScript extends SourceMap {
1526
- constructor() {
1527
- super(...arguments);
1528
- Object.defineProperty(this, "code", {
1644
+ class TextNode extends Traversal {
1645
+ constructor(val, loc, strip) {
1646
+ super();
1647
+ Object.defineProperty(this, "val", {
1529
1648
  enumerable: true,
1530
1649
  configurable: true,
1531
1650
  writable: true,
1532
- value: ''
1533
- });
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
- },
1651
+ value: val
1562
1652
  });
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", {
1653
+ Object.defineProperty(this, "loc", {
1581
1654
  enumerable: true,
1582
1655
  configurable: true,
1583
1656
  writable: true,
1584
- value: CONTEXT
1657
+ value: loc
1585
1658
  });
1586
- Object.defineProperty(this, "contexts", {
1659
+ Object.defineProperty(this, "strip", {
1587
1660
  enumerable: true,
1588
1661
  configurable: true,
1589
1662
  writable: true,
1590
- value: [CONTEXT]
1663
+ value: strip
1591
1664
  });
1592
- Object.defineProperty(this, "index", {
1665
+ Object.defineProperty(this, "type", {
1593
1666
  enumerable: true,
1594
1667
  configurable: true,
1595
1668
  writable: true,
1596
- value: 0
1669
+ value: 'TEXT'
1597
1670
  });
1598
1671
  }
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
1672
  }
1612
1673
 
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,
1674
+ function parseText(token, parser) {
1675
+ parser.advance();
1676
+ return new TextNode(token.val, token.loc, token.strip);
1677
+ }
1678
+ const parsers = {
1679
+ text: parseText,
1680
+ };
1681
+
1682
+ const plugin = {
1683
+ compilers,
1684
+ parsers,
1685
+ };
1686
+
1687
+ const plugins = [
1688
+ plugin$a,
1689
+ plugin$9,
1690
+ plugin$7,
1691
+ plugin$8,
1692
+ plugin$6,
1693
+ plugin$5,
1694
+ plugin$4,
1695
+ plugin$3,
1696
+ plugin$1,
1697
+ plugin,
1698
+ plugin$2,
1699
+ ];
1700
+
1701
+ const baseOptions = {
1702
+ filters: _filters,
1703
+ parsers: {},
1704
+ compilers: {},
1705
+ plugins,
1706
+ debug: () => { },
1707
+ };
1708
+ const parserOptions = {
1709
+ ...baseOptions,
1710
+ commentOpen: '{{#',
1711
+ commentClose: '}}',
1712
+ directiveOpen: '{{',
1713
+ directiveClose: '}}',
1714
+ outputOpen: '{{=',
1715
+ outputClose: '}}',
1716
+ };
1717
+ const compilerOptions = {
1718
+ ...parserOptions,
1719
+ trimWhitespace: false,
1720
+ stripComments: false,
1721
+ loader: async () => '',
1722
+ };
1723
+ const renderOptions = {
1724
+ ...compilerOptions,
1725
+ globals: {},
1726
+ autoEscape: true,
1727
+ };
1728
+ const mergeOptions = (defaultOptions, options) => {
1729
+ const mergedOptions = {
1730
+ ...defaultOptions,
1731
+ ...options,
1732
+ };
1733
+ defaultOptions.plugins?.forEach((plugin) => {
1734
+ Object.assign(mergedOptions.filters, plugin.filters ?? {});
1735
+ Object.assign(mergedOptions.parsers, plugin.parsers ?? {});
1736
+ Object.assign(mergedOptions.compilers, plugin.compilers ?? {});
1737
+ });
1738
+ options?.plugins?.forEach((plugin) => {
1739
+ Object.assign(mergedOptions.filters, plugin.filters ?? {});
1740
+ Object.assign(mergedOptions.parsers, plugin.parsers ?? {});
1741
+ Object.assign(mergedOptions.compilers, plugin.compilers ?? {});
1742
+ });
1743
+ return mergedOptions;
1642
1744
  };
1643
1745
 
1746
+ function updatePosition(str, pos) {
1747
+ const newlines = (str.match(/\n/g) || []).length;
1748
+ if (newlines > 0) {
1749
+ pos.line += newlines;
1750
+ const lastNewline = str.lastIndexOf('\n');
1751
+ pos.column = str.length - lastNewline;
1752
+ }
1753
+ else {
1754
+ pos.column += str.length;
1755
+ }
1756
+ return {
1757
+ line: pos.line,
1758
+ column: pos.column,
1759
+ };
1760
+ }
1761
+
1644
1762
  const expTokenTypes = {
1645
1763
  and: 'AND',
1646
1764
  or: 'OR',
@@ -1667,33 +1785,12 @@ const expTokenTypes = {
1667
1785
  null: 'LIT',
1668
1786
  undefined: 'LIT',
1669
1787
  '|': 'PIPE',
1670
- '=': 'SET',
1788
+ '=': 'ASSIGN',
1671
1789
  '(': 'LP',
1672
1790
  ')': 'RP',
1673
1791
  ',': 'COMMA',
1674
1792
  '.': 'DOT',
1675
1793
  };
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
1794
  class ExpTokenizer {
1698
1795
  constructor(template) {
1699
1796
  Object.defineProperty(this, "template", {
@@ -1904,6 +2001,36 @@ function isIdentifierChar(char) {
1904
2001
  return /[\w$]/.test(char);
1905
2002
  }
1906
2003
 
2004
+ const expTokenPrecedences = {
2005
+ COMMA: 5,
2006
+ IF: 10,
2007
+ ELSE: 10,
2008
+ ASSIGN: 15,
2009
+ LP: 20,
2010
+ RP: 20,
2011
+ OR: 25,
2012
+ AND: 30,
2013
+ IS: 40,
2014
+ EQ: 40,
2015
+ NE: 40,
2016
+ GT: 40,
2017
+ LT: 40,
2018
+ GE: 40,
2019
+ LE: 40,
2020
+ IN: 40,
2021
+ NI: 40,
2022
+ OF: 40,
2023
+ ADD: 50,
2024
+ SUB: 50,
2025
+ MUL: 60,
2026
+ DIV: 60,
2027
+ MOD: 60,
2028
+ NOT: 70,
2029
+ PIPE: 80,
2030
+ DOT: 90,
2031
+ ID: 90,
2032
+ LIT: 90,
2033
+ };
1907
2034
  class ExpParser {
1908
2035
  constructor(template) {
1909
2036
  Object.defineProperty(this, "template", {
@@ -2003,7 +2130,7 @@ class ExpParser {
2003
2130
  type: 'ID',
2004
2131
  value: token.value,
2005
2132
  };
2006
- if (this.check('DOT')) {
2133
+ if (this.match('DOT')) {
2007
2134
  left.path = this.parsePath();
2008
2135
  }
2009
2136
  const lp = this.consume('LP');
@@ -2060,7 +2187,7 @@ class ExpParser {
2060
2187
  token.type === 'MUL' ||
2061
2188
  token.type === 'DIV' ||
2062
2189
  token.type === 'MOD' ||
2063
- token.type === 'SET') {
2190
+ token.type === 'ASSIGN') {
2064
2191
  if (!left) {
2065
2192
  throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
2066
2193
  }
@@ -2080,7 +2207,7 @@ class ExpParser {
2080
2207
  if (!left) {
2081
2208
  throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
2082
2209
  }
2083
- if (!this.check('ID')) {
2210
+ if (!this.match('ID')) {
2084
2211
  throw new CompileError('expected "ID" after "PIPE"', this.template, token.loc);
2085
2212
  }
2086
2213
  left = {
@@ -2120,7 +2247,7 @@ class ExpParser {
2120
2247
  }
2121
2248
  parseSequence() {
2122
2249
  const elements = [];
2123
- while (!this.check('RP')) {
2250
+ while (!this.match('RP')) {
2124
2251
  const element = this.parseExp((t) => t.type === 'COMMA' ? 'BREAK' : undefined);
2125
2252
  if (element) {
2126
2253
  elements.push(element);
@@ -2159,11 +2286,11 @@ class ExpParser {
2159
2286
  peek() {
2160
2287
  return this.tokens.at(this.index) ?? null;
2161
2288
  }
2162
- check(type) {
2289
+ match(type) {
2163
2290
  return this.peek()?.type === type;
2164
2291
  }
2165
2292
  consume(type) {
2166
- if (this.check(type)) {
2293
+ if (this.match(type)) {
2167
2294
  return this.next();
2168
2295
  }
2169
2296
  }
@@ -2234,10 +2361,7 @@ class Tokenizer {
2234
2361
  writable: true,
2235
2362
  value: 1
2236
2363
  });
2237
- this.options = {
2238
- ...parserOptions,
2239
- ...options,
2240
- };
2364
+ this.options = mergeOptions(parserOptions, options);
2241
2365
  const { commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = this.options;
2242
2366
  this.tokenPatterns = [
2243
2367
  [TokenType.COMMENT, commentOpen, commentClose],
@@ -2401,49 +2525,23 @@ class Parser extends Tokenizer {
2401
2525
  if (token.strip?.before && prevToken?.type === TokenType.TEXT) {
2402
2526
  prevToken.strip.end = true;
2403
2527
  }
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;
2417
- }
2528
+ nodes.push(this.options.parsers[token.name?.toLowerCase() ??
2529
+ token.type?.toLowerCase()]?.(token, this) ?? this.createUnknownNode(token));
2418
2530
  prevToken = token;
2419
2531
  }
2420
2532
  return nodes;
2421
2533
  }
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));
2534
+ createUnexpectedNode(token) {
2535
+ const name = token.name ?? token.type;
2536
+ this.options.debug?.(new CompileError(`Unexpected "${name}" directive`, this.template, token.loc));
2440
2537
  this.advance();
2441
- return new UnexpectedDirectiveNode(token.name, token.val, token.loc, token.strip);
2538
+ return new UnexpectedNode(name, token.val, token.loc, token.strip);
2442
2539
  }
2443
- createUnknownDirective(token) {
2444
- this.options.debug?.(new CompileError(`Unknown "${token.name}" directive`, this.template, token.loc));
2540
+ createUnknownNode(token) {
2541
+ const name = token.name ?? token.type;
2542
+ this.options.debug?.(new CompileError(`Unknown "${name}" node`, this.template, token.loc));
2445
2543
  this.advance();
2446
- return new UnknownDirectiveNode(token.name, token.val, token.loc, token.strip);
2544
+ return new UnknownNode(name, token.val, token.loc, token.strip);
2447
2545
  }
2448
2546
  parseExp({ val, loc }) {
2449
2547
  return this.expParser.parse(val, loc);
@@ -2457,15 +2555,10 @@ class Parser extends Tokenizer {
2457
2555
  match(names, token = this.peek()) {
2458
2556
  return names.includes(token?.name);
2459
2557
  }
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
- }
2558
+ emitExpErr({ name, loc }, required = true) {
2559
+ this.options.debug?.(new CompileError(required
2560
+ ? `"${name}" requires expression`
2561
+ : `"${name}" should not have expression`, this.template, loc));
2469
2562
  }
2470
2563
  }
2471
2564
 
@@ -2514,10 +2607,7 @@ class Compiler extends Context {
2514
2607
  writable: true,
2515
2608
  value: void 0
2516
2609
  });
2517
- this.options = {
2518
- ...compilerOptions,
2519
- ...options,
2520
- };
2610
+ this.options = mergeOptions(compilerOptions, options);
2521
2611
  }
2522
2612
  async compile(template, root = true, partials = new Map(), blocks = new Map()) {
2523
2613
  this.template = template;
@@ -2585,12 +2675,12 @@ class Compiler extends Context {
2585
2675
  const partials = new Map();
2586
2676
  const blocks = [];
2587
2677
  const traverse = (node) => {
2588
- if (node.type === NodeType.INCLUDE) {
2678
+ if (node.type === 'INCLUDE') {
2589
2679
  if (!partials.has(node.val.value)) {
2590
2680
  partials.set(node.val.value, node);
2591
2681
  }
2592
2682
  }
2593
- if (node.type === NodeType.BLOCK) {
2683
+ if (node.type === 'BLOCK') {
2594
2684
  blocks.push(node);
2595
2685
  }
2596
2686
  node.traverse(traverse);
@@ -2602,7 +2692,7 @@ class Compiler extends Context {
2602
2692
  };
2603
2693
  }
2604
2694
  async compileNode(node) {
2605
- if (node.type === NodeType.TEMPLATE) {
2695
+ if (node.type === 'TEMPLATE') {
2606
2696
  await this.compileNodes(node.body);
2607
2697
  return;
2608
2698
  }
@@ -2610,7 +2700,7 @@ class Compiler extends Context {
2610
2700
  await this.options.compilers[node.type](node, this);
2611
2701
  return;
2612
2702
  }
2613
- this.options.debug?.(new CompileError(`Unknown "${node.name}" directive`, this.template, node.loc));
2703
+ this.options.debug?.(new CompileError(`Unknown "${node.name}" node`, this.template, node.loc));
2614
2704
  }
2615
2705
  async compileNodes(nodes) {
2616
2706
  for (const child of nodes) {
@@ -2653,23 +2743,14 @@ class RenderError extends CompileError {
2653
2743
  }
2654
2744
 
2655
2745
  class Renderer {
2656
- constructor({ globals, filters, parsers, compilers, plugins, ...options } = {}) {
2746
+ constructor(options) {
2657
2747
  Object.defineProperty(this, "options", {
2658
2748
  enumerable: true,
2659
2749
  configurable: true,
2660
2750
  writable: true,
2661
2751
  value: void 0
2662
2752
  });
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
- });
2753
+ this.options = mergeOptions(renderOptions, options);
2673
2754
  }
2674
2755
  async render(template, globals) {
2675
2756
  const compiler = new Compiler(this.options);