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