janja 1.1.0 → 2.0.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,335 +1,953 @@
1
1
  (function (exports) {
2
2
  'use strict';
3
3
 
4
- function highlightSource(message, source, ranges) {
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
- // Copy to avoid mutation
17
- ranges = [...ranges];
18
- let cursor = 0;
19
- let caretLinesCount = 0;
20
- lines.forEach((line, index) => {
21
- if (!line) {
22
- return;
23
- }
24
- output.push(`${`${index + 1}: `.padStart(indentWidth, ' ')}${line}`);
25
- ranges.forEach((tag) => {
26
- if (tag.start < cursor) {
27
- ranges.splice(ranges.indexOf(tag), 1);
28
- return;
29
- }
30
- if (tag.start >= cursor + line.length + 1) {
31
- return;
32
- }
33
- const offset = tag.start - cursor + indentWidth;
34
- const end = Math.min(tag.end, cursor + line.length);
35
- const count = end - tag.start;
36
- const caretLine = `${' '.repeat(offset)}${'^'.repeat(count)}`;
37
- if (/\S/.test(caretLine)) {
38
- output.push(caretLine);
39
- }
40
- if (end < tag.end) {
41
- tag.start += count + 1;
42
- }
43
- addCaretLine(++caretLinesCount + index);
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", {
31
+ enumerable: true,
32
+ configurable: true,
33
+ writable: true,
34
+ value: null
44
35
  });
45
- cursor += line.length + 1;
46
- });
47
- const emptyLine = `${' '.repeat(indentWidth)}...`;
48
- return `${message}
49
-
50
- ${output
51
- .map((line, index) => (caretLines.has(index) ? line : emptyLine))
52
- .reduce((acc, line) => line === emptyLine && acc.at(-1) === line ? acc : [...acc, line], [])
53
- .join('\n')}
54
- `;
36
+ Object.defineProperty(this, "loc", {
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true,
40
+ value: null
41
+ });
42
+ Object.defineProperty(this, "body", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: void 0
47
+ });
48
+ }
49
+ traverse(cb) {
50
+ this.body?.forEach(cb);
51
+ }
55
52
  }
56
-
57
- class CompileError extends Error {
58
- constructor(message, token, filepath) {
59
- super(filepath ? `${message} at ${filepath}` : message);
60
- Object.defineProperty(this, "token", {
53
+ class RootNode extends Traversal {
54
+ constructor(body, loc) {
55
+ super();
56
+ Object.defineProperty(this, "body", {
61
57
  enumerable: true,
62
58
  configurable: true,
63
59
  writable: true,
64
- value: token
60
+ value: body
61
+ });
62
+ Object.defineProperty(this, "loc", {
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true,
66
+ value: loc
67
+ });
68
+ Object.defineProperty(this, "type", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: NodeType.TEMPLATE
65
73
  });
66
- this.name = 'CompileError';
67
- Error.captureStackTrace?.(this, this.constructor);
68
74
  }
69
- get details() {
70
- return highlightSource(this.message, this.token.raw, [this.token]);
75
+ }
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", {
98
+ enumerable: true,
99
+ configurable: true,
100
+ writable: true,
101
+ value: exp
102
+ });
103
+ Object.defineProperty(this, "type", {
104
+ enumerable: true,
105
+ configurable: true,
106
+ writable: true,
107
+ value: NodeType.OUTPUT
108
+ });
71
109
  }
72
110
  }
73
-
74
- const CONTEXT = 'c';
75
- const FILTERS = 'f'; // Filters can be async
76
- const ESCAPE = 'e';
77
- const RAW$1 = 'raw';
78
- const LAYOUT = 'layout';
79
- const INCLUDE = 'include';
80
- const BLOCK = 'block';
81
- const SUPER = 'super';
82
- const ENDBLOCK = 'endblock';
83
-
84
- class Context {
85
- constructor(options) {
86
- Object.defineProperty(this, "options", {
111
+ class TextNode extends Traversal {
112
+ constructor(val, loc, strip) {
113
+ super();
114
+ Object.defineProperty(this, "val", {
87
115
  enumerable: true,
88
116
  configurable: true,
89
117
  writable: true,
90
- value: options
118
+ value: val
91
119
  });
92
- Object.defineProperty(this, "context", {
120
+ Object.defineProperty(this, "loc", {
93
121
  enumerable: true,
94
122
  configurable: true,
95
123
  writable: true,
96
- value: CONTEXT
124
+ value: loc
97
125
  });
98
- Object.defineProperty(this, "index", {
126
+ Object.defineProperty(this, "strip", {
99
127
  enumerable: true,
100
128
  configurable: true,
101
129
  writable: true,
102
- value: 0
130
+ value: strip
103
131
  });
104
- Object.defineProperty(this, "contexts", {
132
+ Object.defineProperty(this, "type", {
105
133
  enumerable: true,
106
134
  configurable: true,
107
135
  writable: true,
108
- value: [CONTEXT]
136
+ value: NodeType.TEXT
109
137
  });
110
- Object.defineProperty(this, "expected", {
138
+ }
139
+ }
140
+ class IfNode extends Traversal {
141
+ constructor(test, body, alternatives, loc, strip) {
142
+ super();
143
+ Object.defineProperty(this, "test", {
111
144
  enumerable: true,
112
145
  configurable: true,
113
146
  writable: true,
114
- value: []
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", {
162
+ enumerable: true,
163
+ configurable: true,
164
+ writable: true,
165
+ value: loc
166
+ });
167
+ Object.defineProperty(this, "strip", {
168
+ enumerable: true,
169
+ configurable: true,
170
+ writable: true,
171
+ value: strip
172
+ });
173
+ Object.defineProperty(this, "type", {
174
+ enumerable: true,
175
+ configurable: true,
176
+ writable: true,
177
+ value: NodeType.IF
115
178
  });
116
179
  }
117
- in() {
118
- this.context = `${this.context}_${this.index++}`;
119
- this.contexts.push(this.context);
120
- return this.context;
180
+ traverse(cb) {
181
+ this.body?.forEach(cb);
182
+ this.alternatives?.forEach(node => node.body?.forEach(cb));
121
183
  }
122
- out() {
123
- if (this.context === CONTEXT) {
124
- return;
125
- }
126
- this.contexts.pop();
127
- this.context = this.contexts.at(-1) ?? CONTEXT;
184
+ }
185
+ class ElseIfNode extends Traversal {
186
+ constructor(test, body, loc, strip) {
187
+ super();
188
+ Object.defineProperty(this, "test", {
189
+ enumerable: true,
190
+ configurable: true,
191
+ writable: true,
192
+ value: test
193
+ });
194
+ Object.defineProperty(this, "body", {
195
+ enumerable: true,
196
+ configurable: true,
197
+ writable: true,
198
+ value: body
199
+ });
200
+ Object.defineProperty(this, "loc", {
201
+ enumerable: true,
202
+ configurable: true,
203
+ writable: true,
204
+ value: loc
205
+ });
206
+ Object.defineProperty(this, "strip", {
207
+ enumerable: true,
208
+ configurable: true,
209
+ writable: true,
210
+ value: strip
211
+ });
212
+ Object.defineProperty(this, "type", {
213
+ enumerable: true,
214
+ configurable: true,
215
+ writable: true,
216
+ value: NodeType.ELSE_IF
217
+ });
128
218
  }
129
- expect(name) {
130
- this.expected.push(name);
219
+ }
220
+ class ElseNode extends Traversal {
221
+ constructor(body, loc, strip) {
222
+ super();
223
+ Object.defineProperty(this, "body", {
224
+ enumerable: true,
225
+ configurable: true,
226
+ writable: true,
227
+ value: body
228
+ });
229
+ Object.defineProperty(this, "loc", {
230
+ enumerable: true,
231
+ configurable: true,
232
+ writable: true,
233
+ value: loc
234
+ });
235
+ Object.defineProperty(this, "strip", {
236
+ enumerable: true,
237
+ configurable: true,
238
+ writable: true,
239
+ value: strip
240
+ });
241
+ Object.defineProperty(this, "type", {
242
+ enumerable: true,
243
+ configurable: true,
244
+ writable: true,
245
+ value: NodeType.ELSE
246
+ });
131
247
  }
132
- matchAny(name) {
133
- return this.expected.includes(name);
248
+ }
249
+ class ForNode extends Traversal {
250
+ constructor(loop, body, loc, strip) {
251
+ super();
252
+ Object.defineProperty(this, "loop", {
253
+ enumerable: true,
254
+ configurable: true,
255
+ writable: true,
256
+ value: loop
257
+ });
258
+ Object.defineProperty(this, "body", {
259
+ enumerable: true,
260
+ configurable: true,
261
+ writable: true,
262
+ value: body
263
+ });
264
+ Object.defineProperty(this, "loc", {
265
+ enumerable: true,
266
+ configurable: true,
267
+ writable: true,
268
+ value: loc
269
+ });
270
+ Object.defineProperty(this, "strip", {
271
+ enumerable: true,
272
+ configurable: true,
273
+ writable: true,
274
+ value: strip
275
+ });
276
+ Object.defineProperty(this, "type", {
277
+ enumerable: true,
278
+ configurable: true,
279
+ writable: true,
280
+ value: NodeType.FOR
281
+ });
134
282
  }
135
- match(name) {
136
- return this.expected.at(-1) === name;
283
+ }
284
+ class BreakNode extends Traversal {
285
+ constructor(val, loc, strip) {
286
+ super();
287
+ Object.defineProperty(this, "val", {
288
+ enumerable: true,
289
+ configurable: true,
290
+ writable: true,
291
+ value: val
292
+ });
293
+ Object.defineProperty(this, "loc", {
294
+ enumerable: true,
295
+ configurable: true,
296
+ writable: true,
297
+ value: loc
298
+ });
299
+ Object.defineProperty(this, "strip", {
300
+ enumerable: true,
301
+ configurable: true,
302
+ writable: true,
303
+ value: strip
304
+ });
305
+ Object.defineProperty(this, "type", {
306
+ enumerable: true,
307
+ configurable: true,
308
+ writable: true,
309
+ value: NodeType.BREAK
310
+ });
137
311
  }
138
- consume(name) {
139
- if (this.match(name)) {
140
- this.expected.pop();
141
- return true;
142
- }
143
- return false;
312
+ }
313
+ class ContinueNode extends Traversal {
314
+ constructor(val, loc, strip) {
315
+ super();
316
+ Object.defineProperty(this, "val", {
317
+ enumerable: true,
318
+ configurable: true,
319
+ writable: true,
320
+ value: val
321
+ });
322
+ Object.defineProperty(this, "loc", {
323
+ enumerable: true,
324
+ configurable: true,
325
+ writable: true,
326
+ value: loc
327
+ });
328
+ Object.defineProperty(this, "strip", {
329
+ enumerable: true,
330
+ configurable: true,
331
+ writable: true,
332
+ value: strip
333
+ });
334
+ Object.defineProperty(this, "type", {
335
+ enumerable: true,
336
+ configurable: true,
337
+ writable: true,
338
+ value: NodeType.CONTINUE
339
+ });
144
340
  }
145
- validate() {
146
- if (this.expected.length) {
147
- throw new Error(`expected tokens "${this.expected.join(', ')}", but got nothing`);
148
- }
341
+ }
342
+ class UnknownDirectiveNode extends Traversal {
343
+ constructor(name, val, loc, strip) {
344
+ super();
345
+ Object.defineProperty(this, "name", {
346
+ enumerable: true,
347
+ configurable: true,
348
+ writable: true,
349
+ value: name
350
+ });
351
+ Object.defineProperty(this, "val", {
352
+ enumerable: true,
353
+ configurable: true,
354
+ writable: true,
355
+ value: val
356
+ });
357
+ Object.defineProperty(this, "loc", {
358
+ enumerable: true,
359
+ configurable: true,
360
+ writable: true,
361
+ value: loc
362
+ });
363
+ Object.defineProperty(this, "strip", {
364
+ enumerable: true,
365
+ configurable: true,
366
+ writable: true,
367
+ value: strip
368
+ });
369
+ Object.defineProperty(this, "type", {
370
+ enumerable: true,
371
+ configurable: true,
372
+ writable: true,
373
+ value: NodeType.UNKNOWN
374
+ });
149
375
  }
150
376
  }
151
-
152
- class OutScript {
153
- constructor(options) {
154
- Object.defineProperty(this, "options", {
377
+ class UnexpectedDirectiveNode extends Traversal {
378
+ constructor(name, val, loc, strip) {
379
+ super();
380
+ Object.defineProperty(this, "name", {
381
+ enumerable: true,
382
+ configurable: true,
383
+ writable: true,
384
+ value: name
385
+ });
386
+ Object.defineProperty(this, "val", {
387
+ enumerable: true,
388
+ configurable: true,
389
+ writable: true,
390
+ value: val
391
+ });
392
+ Object.defineProperty(this, "loc", {
393
+ enumerable: true,
394
+ configurable: true,
395
+ writable: true,
396
+ value: loc
397
+ });
398
+ Object.defineProperty(this, "strip", {
399
+ enumerable: true,
400
+ configurable: true,
401
+ writable: true,
402
+ value: strip
403
+ });
404
+ Object.defineProperty(this, "type", {
405
+ enumerable: true,
406
+ configurable: true,
407
+ writable: true,
408
+ value: NodeType.UNEXPECTED
409
+ });
410
+ }
411
+ }
412
+ class CommentNode extends Traversal {
413
+ constructor(val, loc, strip) {
414
+ super();
415
+ Object.defineProperty(this, "val", {
416
+ enumerable: true,
417
+ configurable: true,
418
+ writable: true,
419
+ value: val
420
+ });
421
+ Object.defineProperty(this, "loc", {
422
+ enumerable: true,
423
+ configurable: true,
424
+ writable: true,
425
+ value: loc
426
+ });
427
+ Object.defineProperty(this, "strip", {
428
+ enumerable: true,
429
+ configurable: true,
430
+ writable: true,
431
+ value: strip
432
+ });
433
+ Object.defineProperty(this, "type", {
434
+ enumerable: true,
435
+ configurable: true,
436
+ writable: true,
437
+ value: NodeType.COMMENT
438
+ });
439
+ }
440
+ }
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
455
+ });
456
+ Object.defineProperty(this, "strip", {
457
+ enumerable: true,
458
+ configurable: true,
459
+ writable: true,
460
+ value: strip
461
+ });
462
+ Object.defineProperty(this, "type", {
463
+ enumerable: true,
464
+ configurable: true,
465
+ writable: true,
466
+ value: NodeType.INCLUDE
467
+ });
468
+ }
469
+ }
470
+ class BlockNode extends Traversal {
471
+ constructor(val, body, loc, strip) {
472
+ super();
473
+ Object.defineProperty(this, "val", {
474
+ enumerable: true,
475
+ configurable: true,
476
+ writable: true,
477
+ value: val
478
+ });
479
+ Object.defineProperty(this, "body", {
480
+ enumerable: true,
481
+ configurable: true,
482
+ writable: true,
483
+ value: body
484
+ });
485
+ Object.defineProperty(this, "loc", {
486
+ enumerable: true,
487
+ configurable: true,
488
+ writable: true,
489
+ value: loc
490
+ });
491
+ Object.defineProperty(this, "strip", {
492
+ enumerable: true,
493
+ configurable: true,
494
+ writable: true,
495
+ value: strip
496
+ });
497
+ Object.defineProperty(this, "type", {
498
+ enumerable: true,
499
+ configurable: true,
500
+ writable: true,
501
+ value: NodeType.BLOCK
502
+ });
503
+ }
504
+ }
505
+ class SuperNode extends Traversal {
506
+ constructor(val, loc, strip) {
507
+ super();
508
+ Object.defineProperty(this, "val", {
509
+ enumerable: true,
510
+ configurable: true,
511
+ writable: true,
512
+ value: val
513
+ });
514
+ Object.defineProperty(this, "loc", {
515
+ enumerable: true,
516
+ configurable: true,
517
+ writable: true,
518
+ value: loc
519
+ });
520
+ Object.defineProperty(this, "strip", {
521
+ enumerable: true,
522
+ configurable: true,
523
+ writable: true,
524
+ value: strip
525
+ });
526
+ Object.defineProperty(this, "type", {
527
+ enumerable: true,
528
+ configurable: true,
529
+ writable: true,
530
+ value: NodeType.SUPER
531
+ });
532
+ }
533
+ }
534
+ class MacroNode extends Traversal {
535
+ constructor(val, body, loc, strip) {
536
+ super();
537
+ Object.defineProperty(this, "val", {
538
+ enumerable: true,
539
+ configurable: true,
540
+ writable: true,
541
+ value: val
542
+ });
543
+ Object.defineProperty(this, "body", {
544
+ enumerable: true,
545
+ configurable: true,
546
+ writable: true,
547
+ value: body
548
+ });
549
+ Object.defineProperty(this, "loc", {
550
+ enumerable: true,
551
+ configurable: true,
552
+ writable: true,
553
+ value: loc
554
+ });
555
+ Object.defineProperty(this, "strip", {
556
+ enumerable: true,
557
+ configurable: true,
558
+ writable: true,
559
+ value: strip
560
+ });
561
+ Object.defineProperty(this, "type", {
562
+ enumerable: true,
563
+ configurable: true,
564
+ writable: true,
565
+ value: NodeType.MACRO
566
+ });
567
+ }
568
+ }
569
+ class CallerNode extends Traversal {
570
+ constructor(val, loc, strip) {
571
+ super();
572
+ Object.defineProperty(this, "val", {
573
+ enumerable: true,
574
+ configurable: true,
575
+ writable: true,
576
+ value: val
577
+ });
578
+ Object.defineProperty(this, "loc", {
579
+ enumerable: true,
580
+ configurable: true,
581
+ writable: true,
582
+ value: loc
583
+ });
584
+ Object.defineProperty(this, "strip", {
585
+ enumerable: true,
586
+ configurable: true,
587
+ writable: true,
588
+ value: strip
589
+ });
590
+ Object.defineProperty(this, "type", {
591
+ enumerable: true,
592
+ configurable: true,
593
+ writable: true,
594
+ value: NodeType.CALLER
595
+ });
596
+ }
597
+ }
598
+ class CallNode extends Traversal {
599
+ constructor(val, body, loc, strip) {
600
+ super();
601
+ Object.defineProperty(this, "val", {
602
+ enumerable: true,
603
+ configurable: true,
604
+ writable: true,
605
+ value: val
606
+ });
607
+ Object.defineProperty(this, "body", {
608
+ enumerable: true,
609
+ configurable: true,
610
+ writable: true,
611
+ value: body
612
+ });
613
+ Object.defineProperty(this, "loc", {
614
+ enumerable: true,
615
+ configurable: true,
616
+ writable: true,
617
+ value: loc
618
+ });
619
+ Object.defineProperty(this, "strip", {
620
+ enumerable: true,
621
+ configurable: true,
622
+ writable: true,
623
+ value: strip
624
+ });
625
+ Object.defineProperty(this, "type", {
626
+ enumerable: true,
627
+ configurable: true,
628
+ writable: true,
629
+ value: NodeType.CALL
630
+ });
631
+ }
632
+ }
633
+ class SetNode extends Traversal {
634
+ constructor(val, loc, strip) {
635
+ super();
636
+ Object.defineProperty(this, "val", {
637
+ enumerable: true,
638
+ configurable: true,
639
+ writable: true,
640
+ value: val
641
+ });
642
+ Object.defineProperty(this, "loc", {
643
+ enumerable: true,
644
+ configurable: true,
645
+ writable: true,
646
+ value: loc
647
+ });
648
+ Object.defineProperty(this, "strip", {
649
+ enumerable: true,
650
+ configurable: true,
651
+ writable: true,
652
+ value: strip
653
+ });
654
+ Object.defineProperty(this, "type", {
655
+ enumerable: true,
656
+ configurable: true,
657
+ writable: true,
658
+ value: NodeType.SET
659
+ });
660
+ }
661
+ }
662
+ class CaptureNode extends Traversal {
663
+ constructor(val, body, loc, strip) {
664
+ super();
665
+ Object.defineProperty(this, "val", {
155
666
  enumerable: true,
156
667
  configurable: true,
157
668
  writable: true,
158
- value: options
669
+ value: val
159
670
  });
160
- Object.defineProperty(this, "content", {
671
+ Object.defineProperty(this, "body", {
161
672
  enumerable: true,
162
673
  configurable: true,
163
674
  writable: true,
164
- value: ''
675
+ value: body
165
676
  });
166
- Object.defineProperty(this, "strOffset", {
677
+ Object.defineProperty(this, "loc", {
167
678
  enumerable: true,
168
679
  configurable: true,
169
680
  writable: true,
170
- value: 's+="'.length
681
+ value: loc
171
682
  });
172
- Object.defineProperty(this, "varOffset", {
683
+ Object.defineProperty(this, "strip", {
173
684
  enumerable: true,
174
685
  configurable: true,
175
686
  writable: true,
176
- value: `s+=${ESCAPE}(`.length
687
+ value: strip
688
+ });
689
+ Object.defineProperty(this, "type", {
690
+ enumerable: true,
691
+ configurable: true,
692
+ writable: true,
693
+ value: NodeType.CAPTURE
177
694
  });
178
695
  }
179
- get value() {
180
- return this.content;
181
- }
182
- get script() {
183
- // eslint-disable-next-line no-new-func
184
- return new Function(CONTEXT, FILTERS, ESCAPE, this.value);
185
- }
186
- start() {
187
- if (this.options.strictMode) {
188
- this.pushLine('"use strict";');
189
- }
190
- this.pushLine('return(async()=>{', 'let s="";');
191
- }
192
- end() {
193
- this.pushLine('return s;', '})();');
194
- }
195
- pushLine(...lines) {
196
- const start = this.content.length;
197
- for (const line of lines) {
198
- this.content += line;
696
+ }
697
+
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;
199
714
  }
200
- return {
201
- start,
202
- end: this.content.length,
203
- };
204
- }
205
- pushStr(s, o) {
206
- if (s) {
207
- if (o?.trimStart || this.options.trimWhitespace) {
208
- s = s.trimStart();
209
- }
210
- if (o?.trimEnd || this.options.trimWhitespace) {
211
- s = s.trimEnd();
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);
212
720
  }
721
+ addCaretLine(++caretLinesCount + index);
213
722
  }
214
- if (s) {
215
- this.pushLine(`s+="${s.replace(/\\/g, '\\\\')
216
- .replace(/"/g, '\\"')
217
- .replace(/[\n\r]/g, '\\n')}";`);
218
- return {
219
- start: this.content.length + this.strOffset,
220
- end: this.content.length - 2,
221
- };
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);
222
729
  }
223
- }
224
- pushVar(v) {
225
- const start = this.content.length + this.varOffset;
226
- this.pushLine(`s+=${ESCAPE}(${v});`);
227
- return {
228
- start,
229
- end: start + v.length,
230
- };
231
- }
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
+ `;
232
739
  }
233
740
 
234
- /**
235
- * Contains the source map information.
236
- * @example
237
- * - template:
238
- * {{ foo }}
239
- *
240
- * - compiled:
241
- * s+=e(foo);
242
- *
243
- * - sourceMap:
244
- * Mapping {
245
- * source: {
246
- * start: 3,
247
- * end: 6,
248
- * },
249
- * target: {
250
- * start: 3,
251
- * end: 8,
252
- * }
253
- * }
254
- */
255
- class SourceMap {
256
- constructor(options) {
257
- Object.defineProperty(this, "options", {
741
+ class CompileError extends SyntaxError {
742
+ constructor(message, src, loc) {
743
+ super(message);
744
+ Object.defineProperty(this, "src", {
258
745
  enumerable: true,
259
746
  configurable: true,
260
747
  writable: true,
261
- value: options
748
+ value: src
262
749
  });
263
- Object.defineProperty(this, "mappings", {
750
+ Object.defineProperty(this, "loc", {
264
751
  enumerable: true,
265
752
  configurable: true,
266
753
  writable: true,
267
- value: []
268
- });
269
- }
270
- addMapping(source, target) {
271
- this.mappings.push({
272
- source,
273
- target,
754
+ value: loc
274
755
  });
756
+ this.name = 'CompileError';
757
+ CompileError.captureStackTrace?.(this, this.constructor);
275
758
  }
276
- getRanges(offset) {
277
- return this.mappings
278
- .filter(({ target: { start, end } }) => start <= offset && end >= offset)
279
- .map(({ source }) => source);
759
+ get details() {
760
+ return this.loc
761
+ ? highlightSource(this.message, this.src, this.loc)
762
+ : this.message;
280
763
  }
281
764
  }
282
765
 
283
- class Compiler {
284
- constructor(options) {
285
- Object.defineProperty(this, "options", {
286
- enumerable: true,
287
- configurable: true,
288
- writable: true,
289
- value: options
290
- });
291
- }
292
- async compile(tag, filepath) {
293
- const ctx = new Context(this.options);
294
- const out = new OutScript(this.options);
295
- const sourcemap = new SourceMap(this.options);
296
- out.start();
297
- while (tag) {
298
- const compilers = (this.options.compilers[tag.name] ?? []);
299
- for (const compiler of compilers) {
300
- try {
301
- const r = await compiler.compile({
302
- tag,
303
- ctx,
304
- out,
305
- });
306
- if (r !== false) {
307
- if (r) {
308
- sourcemap.addMapping(tag, r);
309
- }
310
- break;
311
- }
312
- }
313
- catch (error) {
314
- throw new CompileError(error.message, tag, filepath);
315
- }
316
- }
317
- tag = tag.next;
318
- }
319
- try {
320
- ctx.validate();
321
- }
322
- catch (error) {
323
- throw new CompileError(error.message, {
324
- raw: '',
325
- start: 0,
326
- end: 0,
327
- }, filepath);
328
- }
329
- out.end();
330
- return { value: out.value, script: out.script, sourcemap };
331
- }
332
- }
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));
802
+ }
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);
813
+ parser.advance();
814
+ const body = parser.parseUntil(['endcapture']);
815
+ if (parser.match(['endcapture'])) {
816
+ parser.advance();
817
+ }
818
+ else {
819
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
820
+ }
821
+ return new CaptureNode(val, body, token.loc, token.strip);
822
+ }
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();
835
+ }
836
+ else {
837
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
838
+ }
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
+ parser.advance();
849
+ return new ContinueNode(token.val, token.loc, token.strip);
850
+ }
851
+ const parsers$5 = {
852
+ for: parseFor,
853
+ break: parseBreak,
854
+ continue: parseContinue,
855
+ endfor: parseUnexpected,
856
+ };
857
+
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,
895
+ };
896
+
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);
902
+ }
903
+ const parsers$3 = {
904
+ include: parseInclude,
905
+ };
906
+
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));
917
+ }
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
+ }
925
+ const parsers$2 = {
926
+ macro: parseMacro,
927
+ caller: parseCaller,
928
+ endmacro: parseUnexpected,
929
+ };
930
+
931
+ function parseSet(token, parser) {
932
+ parser.requireExpression(token);
933
+ const val = parser.parseExp(token.expression);
934
+ parser.advance();
935
+ return new SetNode(val, token.loc, token.strip);
936
+ }
937
+ const parsers$1 = {
938
+ set: parseSet,
939
+ };
940
+
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,
950
+ };
333
951
 
334
952
  class Safe extends String {
335
953
  constructor(value) {
@@ -524,6 +1142,21 @@ ${output
524
1142
  values: values
525
1143
  });
526
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
+
527
1160
  const expTokenOperators = {
528
1161
  AND: '&&',
529
1162
  OR: '||',
@@ -555,6 +1188,10 @@ ${output
555
1188
  ELSE: '',
556
1189
  };
557
1190
 
1191
+ const CONTEXT = 'c';
1192
+ const ESCAPE = 'e';
1193
+ const FILTERS = 'f';
1194
+
558
1195
  class ExpCompiler {
559
1196
  constructor() {
560
1197
  Object.defineProperty(this, "context", {
@@ -570,7 +1207,7 @@ ${output
570
1207
  value: void 0
571
1208
  });
572
1209
  }
573
- compile(expression, context, filters) {
1210
+ compile(expression, context = CONTEXT, filters = FILTERS) {
574
1211
  this.context = context;
575
1212
  this.filters = filters;
576
1213
  return expression ? this.compileExp(expression) : '""';
@@ -626,43 +1263,345 @@ ${output
626
1263
  }
627
1264
  return s;
628
1265
  }
629
- compileLit({ value }) {
630
- return value === undefined ? 'undefined' : JSON.stringify(value);
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", {
1499
+ enumerable: true,
1500
+ configurable: true,
1501
+ writable: true,
1502
+ value: []
1503
+ });
1504
+ }
1505
+ addMapping(source, target) {
1506
+ this.mappings.push({
1507
+ source,
1508
+ target,
1509
+ });
1510
+ }
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
+ }
1520
+
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
+ });
631
1530
  }
632
- compileSeq({ elements }) {
633
- return elements.map(element => this.compileExp(element)).toString();
1531
+ get script() {
1532
+ return new Function(CONTEXT, ESCAPE, FILTERS, this.code);
634
1533
  }
635
- compilePipe({ left, right }) {
636
- const { value: name, args = [] } = right;
637
- 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(',')}))`;
1534
+ start() {
1535
+ this.pushRaw(null, 'return(async()=>{', 'let s="";');
638
1536
  }
639
- compileOf({ left, right }) {
640
- // destructuring
641
- if (left.type === 'SEQ') {
642
- return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
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;
643
1544
  }
644
- return `const ${left.value} of ${this.compileExp(right)}`;
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
+ });
645
1558
  }
646
- compileSet({ left, right }) {
647
- if (left.type === 'ID') {
648
- // for macros
649
- if (right.type === 'SEQ') {
650
- return `${this.compileExp(left)}=(${(right.elements).map(el => el.type === 'SET' ? `${el.left.value}=${this.compileExp((el.right))}` : el.value).join(',')})`;
651
- }
652
- return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
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')}";`);
653
1565
  }
654
- // destructuring
655
- return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
656
1566
  }
657
- compileIs({ left, right }) {
658
- return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
1567
+ pushVar(loc, v) {
1568
+ this.pushRaw(loc, `s+=${ESCAPE}(${v});`);
659
1569
  }
660
- compileBinary({ type, left, right }) {
661
- const ret = `(${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)})`;
662
- return type === 'NI' ? `(!${ret})` : ret;
1570
+ }
1571
+
1572
+ class Context extends OutScript {
1573
+ constructor() {
1574
+ super();
1575
+ Object.defineProperty(this, "context", {
1576
+ enumerable: true,
1577
+ configurable: true,
1578
+ writable: true,
1579
+ value: CONTEXT
1580
+ });
1581
+ Object.defineProperty(this, "contexts", {
1582
+ enumerable: true,
1583
+ configurable: true,
1584
+ writable: true,
1585
+ value: [CONTEXT]
1586
+ });
1587
+ Object.defineProperty(this, "index", {
1588
+ enumerable: true,
1589
+ configurable: true,
1590
+ writable: true,
1591
+ value: 0
1592
+ });
663
1593
  }
664
- compileTernary({ test, consequent, alternative }) {
665
- return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
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;
666
1605
  }
667
1606
  }
668
1607
 
@@ -730,36 +1669,39 @@ ${output
730
1669
  '.': 'DOT',
731
1670
  };
732
1671
 
733
- class ParseError extends SyntaxError {
734
- constructor(message, options) {
735
- super(message);
736
- Object.defineProperty(this, "options", {
737
- enumerable: true,
738
- configurable: true,
739
- writable: true,
740
- value: options
741
- });
742
- this.name = 'ParseError';
743
- Error.captureStackTrace?.(this, this.constructor);
744
- }
745
- get details() {
746
- return highlightSource(this.message, this.options.source, [this.options.range]);
747
- }
1672
+ /**
1673
+ * Update position by a given string, and return a new position with the
1674
+ * updated values.
1675
+ */
1676
+ function updatePosition(str, pos) {
1677
+ const newlines = (str.match(/\n/g) || []).length;
1678
+ if (newlines > 0) {
1679
+ pos.line += newlines;
1680
+ const lastNewline = str.lastIndexOf('\n');
1681
+ pos.column = str.length - lastNewline;
1682
+ }
1683
+ else {
1684
+ pos.column += str.length;
1685
+ }
1686
+ return {
1687
+ line: pos.line,
1688
+ column: pos.column,
1689
+ };
748
1690
  }
749
1691
 
750
1692
  class ExpTokenizer {
751
- constructor() {
1693
+ constructor(template) {
752
1694
  Object.defineProperty(this, "template", {
753
1695
  enumerable: true,
754
1696
  configurable: true,
755
1697
  writable: true,
756
- value: ''
1698
+ value: template
757
1699
  });
758
- Object.defineProperty(this, "length", {
1700
+ Object.defineProperty(this, "val", {
759
1701
  enumerable: true,
760
1702
  configurable: true,
761
1703
  writable: true,
762
- value: 0
1704
+ value: ''
763
1705
  });
764
1706
  Object.defineProperty(this, "tokens", {
765
1707
  enumerable: true,
@@ -767,22 +1709,42 @@ ${output
767
1709
  writable: true,
768
1710
  value: []
769
1711
  });
770
- Object.defineProperty(this, "cursor", {
1712
+ Object.defineProperty(this, "index", {
771
1713
  enumerable: true,
772
1714
  configurable: true,
773
1715
  writable: true,
774
1716
  value: 0
775
1717
  });
1718
+ Object.defineProperty(this, "line", {
1719
+ enumerable: true,
1720
+ configurable: true,
1721
+ writable: true,
1722
+ value: 1
1723
+ });
1724
+ Object.defineProperty(this, "column", {
1725
+ enumerable: true,
1726
+ configurable: true,
1727
+ writable: true,
1728
+ value: 1
1729
+ });
776
1730
  }
777
- tokenize(template) {
778
- this.template = template;
779
- this.length = template.length;
1731
+ tokenize(val, loc) {
1732
+ this.val = val;
1733
+ this.index = 0;
1734
+ this.line = loc.start.line;
1735
+ this.column = loc.start.column;
780
1736
  this.tokens = [];
781
- this.cursor = 0;
782
- while (this.cursor < this.length) {
783
- const char = this.template[this.cursor];
1737
+ while (this.index < this.val.length) {
1738
+ const char = this.val[this.index];
784
1739
  if (isWhitespace(char)) {
785
- this.cursor++;
1740
+ if (char === '\n') {
1741
+ this.line++;
1742
+ this.column = 0;
1743
+ }
1744
+ else {
1745
+ this.column++;
1746
+ }
1747
+ this.index++;
786
1748
  continue;
787
1749
  }
788
1750
  if (char === '\'' || char === '"' || char === '`') {
@@ -801,21 +1763,21 @@ ${output
801
1763
  this.readSymbol(char);
802
1764
  continue;
803
1765
  }
804
- throw new ParseError(`unexpect "${char}"`, { source: template, range: {
805
- start: this.cursor,
806
- end: this.cursor + 1,
807
- } });
1766
+ throw new CompileError(`Unexpect "${char}"`, this.template, {
1767
+ start: { line: this.line, column: this.column },
1768
+ end: { line: this.line, column: this.column + 1 },
1769
+ });
808
1770
  }
809
1771
  return this.tokens;
810
1772
  }
811
1773
  readString(quoteChar) {
812
1774
  let value = '';
813
1775
  let escaped = false;
814
- const start = this.cursor;
1776
+ const start = { line: this.line, column: this.column };
815
1777
  // Skip opening quote char
816
- this.cursor++;
817
- while (this.cursor < this.length) {
818
- const char = this.template[this.cursor];
1778
+ this.index++;
1779
+ while (this.index < this.val.length) {
1780
+ const char = this.val[this.index];
819
1781
  if (escaped) {
820
1782
  value += char;
821
1783
  escaped = false;
@@ -830,24 +1792,26 @@ ${output
830
1792
  else {
831
1793
  value += char;
832
1794
  }
833
- this.cursor++;
1795
+ this.index++;
834
1796
  }
835
1797
  // skip closing quote char
836
- this.cursor++;
1798
+ this.index++;
837
1799
  this.tokens.push({
838
1800
  type: 'LIT',
839
1801
  value,
840
- start,
841
- end: this.cursor,
1802
+ loc: {
1803
+ start,
1804
+ end: updatePosition(value, this),
1805
+ },
842
1806
  raw: `${quoteChar}${value}${quoteChar}`,
843
1807
  });
844
1808
  }
845
1809
  readNumber() {
846
1810
  let value = '';
847
1811
  let hasDot = false;
848
- const start = this.cursor;
849
- while (this.cursor < this.length) {
850
- const char = this.template[this.cursor];
1812
+ const start = { line: this.line, column: this.column };
1813
+ while (this.index < this.val.length) {
1814
+ const char = this.val[this.index];
851
1815
  if (isDigit(char)) {
852
1816
  value += char;
853
1817
  }
@@ -858,24 +1822,26 @@ ${output
858
1822
  else {
859
1823
  break;
860
1824
  }
861
- this.cursor++;
1825
+ this.index++;
862
1826
  }
863
1827
  this.tokens.push({
864
1828
  type: 'LIT',
865
1829
  value: Number.parseFloat(value),
866
- start,
867
- end: this.cursor,
1830
+ loc: {
1831
+ start,
1832
+ end: updatePosition(value, this),
1833
+ },
868
1834
  raw: value,
869
1835
  });
870
1836
  }
871
1837
  readIdentifier() {
872
1838
  let value = '';
873
- const start = this.cursor;
874
- while (this.cursor < this.length) {
875
- const char = this.template[this.cursor];
1839
+ const start = { line: this.line, column: this.column };
1840
+ while (this.index < this.val.length) {
1841
+ const char = this.val[this.index];
876
1842
  if (isIdentifierChar(char)) {
877
1843
  value += char;
878
- this.cursor++;
1844
+ this.index++;
879
1845
  continue;
880
1846
  }
881
1847
  break;
@@ -894,21 +1860,25 @@ ${output
894
1860
  ? undefined
895
1861
  : value
896
1862
  : value,
897
- start,
898
- end: this.cursor,
1863
+ loc: {
1864
+ start,
1865
+ end: updatePosition(value, this),
1866
+ },
899
1867
  raw: value,
900
1868
  });
901
1869
  }
902
1870
  readSymbol(char) {
903
- const start = this.cursor;
1871
+ const start = { line: this.line, column: this.column };
1872
+ this.index++;
904
1873
  this.tokens.push({
905
1874
  type: expTokenTypes[char],
906
1875
  value: char,
907
- start,
908
- end: this.cursor,
1876
+ loc: {
1877
+ start,
1878
+ end: updatePosition(char, this),
1879
+ },
909
1880
  raw: char,
910
1881
  });
911
- this.cursor++;
912
1882
  }
913
1883
  }
914
1884
  function isWhitespace(char) {
@@ -928,8 +1898,14 @@ ${output
928
1898
  }
929
1899
 
930
1900
  class ExpParser {
931
- constructor() {
1901
+ constructor(template) {
932
1902
  Object.defineProperty(this, "template", {
1903
+ enumerable: true,
1904
+ configurable: true,
1905
+ writable: true,
1906
+ value: template
1907
+ });
1908
+ Object.defineProperty(this, "val", {
933
1909
  enumerable: true,
934
1910
  configurable: true,
935
1911
  writable: true,
@@ -941,25 +1917,32 @@ ${output
941
1917
  writable: true,
942
1918
  value: []
943
1919
  });
944
- Object.defineProperty(this, "length", {
1920
+ Object.defineProperty(this, "index", {
945
1921
  enumerable: true,
946
1922
  configurable: true,
947
1923
  writable: true,
948
1924
  value: 0
949
1925
  });
950
- Object.defineProperty(this, "cursor", {
1926
+ Object.defineProperty(this, "line", {
951
1927
  enumerable: true,
952
1928
  configurable: true,
953
1929
  writable: true,
954
- value: 0
1930
+ value: 1
1931
+ });
1932
+ Object.defineProperty(this, "column", {
1933
+ enumerable: true,
1934
+ configurable: true,
1935
+ writable: true,
1936
+ value: 1
955
1937
  });
956
1938
  }
957
- parse(template) {
958
- this.template = template;
959
- this.tokens = new ExpTokenizer().tokenize(template);
960
- this.length = this.tokens.length;
961
- this.cursor = 0;
962
- return this.template ? this.parseExp() : null;
1939
+ parse(val, loc) {
1940
+ this.val = val;
1941
+ this.index = 0;
1942
+ this.line = loc.start.line;
1943
+ this.column = loc.start.column;
1944
+ this.tokens = new ExpTokenizer(this.template).tokenize(val, loc);
1945
+ return this.val ? this.parseExp() : null;
963
1946
  }
964
1947
  parseExp(checker) {
965
1948
  let left = null;
@@ -978,42 +1961,27 @@ ${output
978
1961
  }
979
1962
  if (token.type === 'LP') {
980
1963
  if (!this.peek()) {
981
- throw new ParseError(`unexpected end of expression`, {
982
- source: this.template,
983
- range: {
984
- start: token.start,
985
- end: token.end,
986
- },
987
- });
1964
+ throw new CompileError(`unexpected end of expression`, this.template, token.loc);
988
1965
  }
989
1966
  const elements = this.parseSequence();
990
1967
  const rp = this.consume('RP');
991
1968
  if (!rp) {
992
- throw new ParseError(`expected "RP" after "LP"`, {
993
- source: this.template,
994
- range: {
995
- start: token.start,
996
- end: token.end,
997
- },
998
- });
1969
+ throw new CompileError(`expected "RP" after "LP"`, this.template, token.loc);
999
1970
  }
1000
1971
  left = {
1001
1972
  ...token,
1002
1973
  type: 'SEQ',
1003
1974
  elements,
1004
- end: rp.end,
1975
+ loc: {
1976
+ start: token.loc.start,
1977
+ end: rp.loc.end,
1978
+ },
1005
1979
  };
1006
1980
  continue;
1007
1981
  }
1008
1982
  if (token.type === 'NOT') {
1009
1983
  if (!this.peek()) {
1010
- throw new ParseError(`unexpected end of expression`, {
1011
- source: this.template,
1012
- range: {
1013
- start: token.start,
1014
- end: token.end,
1015
- },
1016
- });
1984
+ throw new CompileError(`unexpected end of expression`, this.template, token.loc);
1017
1985
  }
1018
1986
  left = {
1019
1987
  ...token,
@@ -1031,17 +1999,11 @@ ${output
1031
1999
  if (this.check('DOT')) {
1032
2000
  left.path = this.parsePath();
1033
2001
  }
1034
- if (this.consume('LP')) {
2002
+ const lp = this.consume('LP');
2003
+ if (lp) {
1035
2004
  left.args = this.parseSequence();
1036
- const rp = this.consume('RP');
1037
- if (!rp) {
1038
- throw new ParseError(`expected "RP" after "LP"`, {
1039
- source: this.template,
1040
- range: {
1041
- start: token.start,
1042
- end: token.end,
1043
- },
1044
- });
2005
+ if (!this.consume('RP')) {
2006
+ throw new CompileError(`expected "RP" after "LP"`, this.template, lp.loc);
1045
2007
  }
1046
2008
  continue;
1047
2009
  }
@@ -1057,13 +2019,7 @@ ${output
1057
2019
  if (token.type === 'IF') {
1058
2020
  const test = this.parseExp(t => t.type === 'ELSE' ? 'BACK' : isHigher(token, t) ? 'BACK' : undefined);
1059
2021
  if (!test) {
1060
- throw new ParseError('expected test expression', {
1061
- source: this.template,
1062
- range: {
1063
- start: token.start,
1064
- end: token.end,
1065
- },
1066
- });
2022
+ throw new CompileError('expected test expression', this.template, token.loc);
1067
2023
  }
1068
2024
  left = {
1069
2025
  ...token,
@@ -1074,13 +2030,7 @@ ${output
1074
2030
  if (this.consume('ELSE')) {
1075
2031
  const alternative = this.parseExp(t => isHigher(token, t) ? 'BACK' : undefined);
1076
2032
  if (!alternative) {
1077
- throw new ParseError('expected alternative expression', {
1078
- source: this.template,
1079
- range: {
1080
- start: token.start,
1081
- end: token.end,
1082
- },
1083
- });
2033
+ throw new CompileError('expected alternative expression', this.template, token.loc);
1084
2034
  }
1085
2035
  left.alternative = alternative;
1086
2036
  }
@@ -1105,23 +2055,11 @@ ${output
1105
2055
  || token.type === 'MOD'
1106
2056
  || token.type === 'SET') {
1107
2057
  if (!left) {
1108
- throw new ParseError(`no left operand for "${token.type}"`, {
1109
- source: this.template,
1110
- range: {
1111
- start: token.start,
1112
- end: token.end,
1113
- },
1114
- });
2058
+ throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
1115
2059
  }
1116
2060
  const right = this.parseExp(t => isHigher(token, t) ? 'BACK' : undefined);
1117
2061
  if (!right) {
1118
- throw new ParseError(`no right operand for "${token.type}"`, {
1119
- source: this.template,
1120
- range: {
1121
- start: token.start,
1122
- end: token.end,
1123
- },
1124
- });
2062
+ throw new CompileError(`no right operand for "${token.type}"`, this.template, token.loc);
1125
2063
  }
1126
2064
  left = {
1127
2065
  ...token,
@@ -1133,22 +2071,10 @@ ${output
1133
2071
  }
1134
2072
  if (token.type === 'PIPE') {
1135
2073
  if (!left) {
1136
- throw new ParseError(`no left operand for "${token.type}"`, {
1137
- source: this.template,
1138
- range: {
1139
- start: token.start,
1140
- end: token.end,
1141
- },
1142
- });
2074
+ throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
1143
2075
  }
1144
2076
  if (!this.check('ID')) {
1145
- throw new ParseError(`expected "ID" after "PIPE"`, {
1146
- source: this.template,
1147
- range: {
1148
- start: token.start,
1149
- end: token.end,
1150
- },
1151
- });
2077
+ throw new CompileError(`expected "ID" after "PIPE"`, this.template, token.loc);
1152
2078
  }
1153
2079
  left = {
1154
2080
  ...token,
@@ -1171,714 +2097,628 @@ ${output
1171
2097
  break;
1172
2098
  }
1173
2099
  const token = this.next();
1174
- if (!token) {
1175
- throw new ParseError(`expected "ID" after "DOT"`, {
1176
- source: this.template,
1177
- range: {
1178
- start: dot.start,
1179
- end: dot.end,
1180
- },
1181
- });
1182
- }
1183
- if (token.type !== 'ID') {
1184
- throw new ParseError(`expected "ID" after "DOT"`, {
1185
- source: this.template,
1186
- range: {
1187
- start: token.start,
1188
- end: token.end,
1189
- },
1190
- });
1191
- }
1192
- ids.push({
1193
- ...token,
1194
- type: 'ID',
1195
- value: token.value,
1196
- });
1197
- }
1198
- return ids;
1199
- }
1200
- parseSequence() {
1201
- const elements = [];
1202
- while (!this.check('RP')) {
1203
- const element = this.parseExp(t => t.type === 'COMMA' ? 'BREAK' : undefined);
1204
- if (element) {
1205
- elements.push(element);
1206
- }
1207
- else {
1208
- break;
1209
- }
1210
- }
1211
- return elements;
1212
- }
1213
- parsePipe() {
1214
- const token = this.next();
1215
- const right = {
1216
- ...token,
1217
- type: 'ID',
1218
- value: token.value,
1219
- };
1220
- if (this.consume('LP')) {
1221
- const args = this.parseSequence();
1222
- if (args.length) {
1223
- right.args = args;
1224
- }
1225
- const rp = this.consume('RP');
1226
- if (!rp) {
1227
- throw new ParseError(`expected "RP" after "LP"`, {
1228
- source: this.template,
1229
- range: {
1230
- start: token.start,
1231
- end: token.end,
1232
- },
1233
- });
1234
- }
1235
- }
1236
- return right;
1237
- }
1238
- next() {
1239
- return this.tokens[this.cursor++] ?? null;
1240
- }
1241
- back() {
1242
- return this.tokens[this.cursor--];
1243
- }
1244
- peek() {
1245
- return this.tokens[this.cursor] ?? null;
1246
- }
1247
- check(type) {
1248
- return this.peek()?.type === type;
1249
- }
1250
- consume(type) {
1251
- if (this.check(type)) {
1252
- return this.next();
1253
- }
1254
- }
1255
- }
1256
- function isHigher(a, b) {
1257
- return expTokenPrecedences[a.type] > expTokenPrecedences[b.type];
1258
- }
1259
-
1260
- const compiler = new ExpCompiler();
1261
- const parser = new ExpParser();
1262
-
1263
- const CALL = 'call';
1264
- const ENDCALL = 'endcall';
1265
- /**
1266
- * @example {{ call my_macro(x, "a", 1) }}...{{ endcall }}
1267
- */
1268
- const tag$7 = {
1269
- names: [CALL, ENDCALL],
1270
- async compile({ tag: { name, value }, ctx, out }) {
1271
- if (name === CALL) {
1272
- if (value?.type !== 'ID') {
1273
- throw new Error(`"${CALL}" tag must specify a "macro" name`);
1274
- }
1275
- ctx.expect(ENDCALL);
1276
- const { context } = ctx;
1277
- return out.pushLine(`await ${compiler.compile(value, context, FILTERS)}(async()=>{`);
1278
- }
1279
- if (name === ENDCALL) {
1280
- if (!ctx.consume(ENDCALL)) {
1281
- throw new Error(`unexpected "${ENDCALL}"`);
1282
- }
1283
- return out.pushLine(`});`);
1284
- }
1285
- },
1286
- };
1287
-
1288
- const COMMENT = 'comment';
1289
- const ENDCOMMENT = 'endcomment';
1290
- /**
1291
- * @example {{# This is a comment }}
1292
- * @example {{ comment }} This is a comment {{ endcomment }}
1293
- */
1294
- const tag$6 = {
1295
- names: [COMMENT, '#', ENDCOMMENT],
1296
- async compile({ tag: { name, value }, ctx, out }) {
1297
- // inline comment
1298
- if (name === '#') {
1299
- if (!value.value || out.options.stripComments) {
1300
- return;
1301
- }
1302
- return out.pushStr(`<!--${value.value}-->`);
1303
- }
1304
- // block comment
1305
- if (name === COMMENT) {
1306
- ctx.expect(ENDCOMMENT);
1307
- return out.pushStr(`<!--`);
1308
- }
1309
- if (name === ENDCOMMENT) {
1310
- if (!ctx.consume(ENDCOMMENT)) {
1311
- throw new Error(`unexpected "${ENDCOMMENT}"`);
1312
- }
1313
- return out.pushStr(`-->`);
1314
- }
1315
- },
1316
- };
1317
-
1318
- const EXPRESSION = '=';
1319
- /**
1320
- * @example {{= x | f }}
1321
- * @example {{= 'a' if x else 'b' }}
1322
- */
1323
- const tag$5 = {
1324
- names: [EXPRESSION],
1325
- compile({ tag: { value }, ctx: { context }, out }) {
1326
- return out.pushVar(compiler.compile(value, context, FILTERS));
1327
- },
1328
- };
1329
-
1330
- const FOR = 'for';
1331
- const BREAK = 'break';
1332
- const CONTINUE = 'continue';
1333
- const ENDFOR = 'endfor';
1334
- /**
1335
- * @example {{ for item in items }}{{= item }}{{ endfor }}
1336
- * @example {{ for (x, y) in items }}{{= x }},{{= y }}{{ endfor }}
1337
- */
1338
- const tag$4 = {
1339
- names: [FOR, BREAK, CONTINUE, ENDFOR],
1340
- async compile({ tag: { name, value }, ctx, out }) {
1341
- if (name === FOR) {
1342
- if (!value) {
1343
- throw new Error(`"${FOR}" tag must have expression`);
1344
- }
1345
- ctx.expect(ENDFOR);
1346
- const { context } = ctx;
1347
- const { type, elements } = value.left;
1348
- if (type === 'SEQ') {
1349
- return out.pushLine(`{`, `for(${compiler.compile(value, context, FILTERS)}){`, `const ${ctx.in()}={`, `...${context},`, elements.map(({ value }) => value).join(','), `};`);
1350
- }
1351
- return out.pushLine(`{`, `for(${compiler.compile(value, context, FILTERS)}){`, `const ${ctx.in()}={`, `...${context},`, `${value.left.value},`, `};`);
1352
- }
1353
- if (name === BREAK) {
1354
- if (!ctx.matchAny(ENDFOR)) {
1355
- throw new Error(`"${BREAK}" tag must inside a "${FOR}" loop`);
1356
- }
1357
- return out.pushLine(`break;`);
1358
- }
1359
- if (name === CONTINUE) {
1360
- if (!ctx.matchAny(ENDFOR)) {
1361
- throw new Error(`"${CONTINUE}" tag must inside a "${FOR}" loop`);
1362
- }
1363
- return out.pushLine(`continue;`);
1364
- }
1365
- if (name === ENDFOR) {
1366
- if (!ctx.consume(ENDFOR)) {
1367
- throw new Error(`unexpected "${ENDFOR}"`);
1368
- }
1369
- ctx.out();
1370
- return out.pushLine(`}}`);
1371
- }
1372
- },
1373
- };
1374
-
1375
- const IF = 'if';
1376
- const ELIF = 'elif';
1377
- const ELSE = 'else';
1378
- const ENDIF = 'endif';
1379
- /**
1380
- * @example {{ if my_var | my_filter }}yes{{ else }}no{{ endif }}
1381
- */
1382
- const tag$3 = {
1383
- names: [IF, ELIF, ELSE, ENDIF],
1384
- async compile({ tag: { name, value }, ctx, out }) {
1385
- if (name === IF) {
1386
- if (!value) {
1387
- throw new Error(`"${IF}" tag must have expression`);
1388
- }
1389
- ctx.expect(ENDIF);
1390
- const { context } = ctx;
1391
- return out.pushLine(`if(${compiler.compile(value, context, FILTERS)}){`);
1392
- }
1393
- if (name === ELIF) {
1394
- if (!value) {
1395
- throw new Error(`"${ELIF}" tag must have expression`);
1396
- }
1397
- if (!ctx.match(ENDIF)) {
1398
- throw new Error(`"${ELIF}" tag must follow "${IF}" tag`);
1399
- }
1400
- const { context } = ctx;
1401
- return out.pushLine(`}else if(${compiler.compile(value, context, FILTERS)}){`);
1402
- }
1403
- if (name === ELSE) {
1404
- if (!ctx.match(ENDIF)) {
1405
- throw new Error(`"${ELSE}" tag must follow "${IF}" tag`);
1406
- }
1407
- return out.pushLine(`}else{`);
1408
- }
1409
- if (name === ENDIF) {
1410
- if (!ctx.consume(ENDIF)) {
1411
- throw new Error(`unexpected "${ENDIF}"`);
1412
- }
1413
- return out.pushLine(`}`);
1414
- }
1415
- },
1416
- };
1417
-
1418
- const MACRO = 'macro';
1419
- const CALLER = 'caller';
1420
- const ENDMACRO = 'endmacro';
1421
- const CALLER_PN = '_c';
1422
- /**
1423
- * @example {{ macro my_macro = (x, y) }}...{{ caller }}{{ endmacro }}{{ my_macro("foo", 1) }}
1424
- */
1425
- const tag$2 = {
1426
- names: [MACRO, CALLER, ENDMACRO],
1427
- async compile({ tag: { name, value }, ctx, out }) {
1428
- if (name === MACRO) {
1429
- if (value?.type !== 'SET') {
1430
- throw new Error(`"${MACRO}" tag must have "SET" expression`);
2100
+ if (!token) {
2101
+ throw new CompileError(`expected "ID" after "DOT"`, this.template, dot.loc);
1431
2102
  }
1432
- ctx.expect(ENDMACRO);
1433
- const { context } = ctx;
1434
- const { elements } = value.right;
1435
- return out.pushLine(`${compiler.compile(value, context, FILTERS)}=>async(${CALLER_PN})=>{`, `const ${ctx.in()}={`, `...${context},`, elements.map(el => el.type === 'SET'
1436
- ? el.left.value
1437
- : el.value).join(','), `};`);
1438
- }
1439
- if (name === CALLER) {
1440
- if (!ctx.matchAny(ENDMACRO)) {
1441
- throw new Error(`"${CALLER}" tag must inside a "${MACRO}" tag`);
2103
+ if (token.type !== 'ID') {
2104
+ throw new CompileError(`expected "ID" after "DOT"`, this.template, dot.loc);
1442
2105
  }
1443
- return out.pushLine(`await ${CALLER_PN}?.();`);
2106
+ ids.push({
2107
+ ...token,
2108
+ type: 'ID',
2109
+ value: token.value,
2110
+ });
1444
2111
  }
1445
- if (name === ENDMACRO) {
1446
- if (!ctx.consume(ENDMACRO)) {
1447
- throw new Error(`unexpected "${ENDMACRO}"`);
2112
+ return ids;
2113
+ }
2114
+ parseSequence() {
2115
+ const elements = [];
2116
+ while (!this.check('RP')) {
2117
+ const element = this.parseExp(t => t.type === 'COMMA' ? 'BREAK' : undefined);
2118
+ if (element) {
2119
+ elements.push(element);
2120
+ }
2121
+ else {
2122
+ break;
1448
2123
  }
1449
- ctx.out();
1450
- return out.pushLine(`};`);
1451
2124
  }
1452
- },
1453
- };
1454
-
1455
- const RAW = 'raw';
1456
- /**
1457
- * @example hello world
1458
- */
1459
- const tag$1 = {
1460
- names: [RAW],
1461
- async compile({ tag: { raw, previous, next }, out }) {
1462
- return out.pushStr(raw, {
1463
- trimStart: previous?.stripAfter,
1464
- trimEnd: next?.stripBefore,
1465
- });
1466
- },
1467
- };
1468
-
1469
- const SET = 'set';
1470
- const ENDSET = 'endset';
1471
- /**
1472
- * @example {{ set left = right }}
1473
- * @example {{ set variable }} this is {{= my_value }} {{ endset }}
1474
- */
1475
- const tag = {
1476
- names: [SET, ENDSET],
1477
- async compile({ tag: { name, value }, ctx, out }) {
1478
- if (name === SET) {
1479
- if (!value) {
1480
- throw new Error(`"${SET}" tag must have expression`);
2125
+ return elements;
2126
+ }
2127
+ parsePipe() {
2128
+ const token = this.next();
2129
+ const right = {
2130
+ ...token,
2131
+ type: 'ID',
2132
+ value: token.value,
2133
+ };
2134
+ const lp = this.consume('LP');
2135
+ if (lp) {
2136
+ const args = this.parseSequence();
2137
+ if (args.length) {
2138
+ right.args = args;
1481
2139
  }
1482
- const { context } = ctx;
1483
- // inline assignment
1484
- if (value.right) {
1485
- return out.pushLine(compiler.compile(value, CONTEXT, FILTERS));
2140
+ if (!this.consume('RP')) {
2141
+ throw new CompileError(`expected "RP" after "LP"`, this.template, lp.loc);
1486
2142
  }
1487
- ctx.expect(ENDSET);
1488
- // block assignment
1489
- return out.pushLine(`Object.assign(${context},{`, `${value.value}:await(async(s)=>{`);
1490
2143
  }
1491
- if (name === ENDSET) {
1492
- if (!ctx.consume(ENDSET)) {
1493
- throw new Error(`unexpected "${ENDSET}"`);
1494
- }
1495
- return out.pushLine(`return s;})("")});`);
2144
+ return right;
2145
+ }
2146
+ next() {
2147
+ return this.tokens[this.index++] ?? null;
2148
+ }
2149
+ back() {
2150
+ return this.tokens[this.index--];
2151
+ }
2152
+ peek() {
2153
+ return this.tokens.at(this.index) ?? null;
2154
+ }
2155
+ check(type) {
2156
+ return this.peek()?.type === type;
2157
+ }
2158
+ consume(type) {
2159
+ if (this.check(type)) {
2160
+ return this.next();
1496
2161
  }
1497
- },
1498
- };
1499
-
1500
- const compilers = [
1501
- tag,
1502
- tag$7,
1503
- tag$6,
1504
- tag$5,
1505
- tag$4,
1506
- tag$3,
1507
- tag$2,
1508
- tag$1,
1509
- ].reduce((acc, compiler) => {
1510
- for (const name of compiler.names) {
1511
- acc[name] = [...(acc[name] || []), compiler];
1512
- }
1513
- return acc;
1514
- }, {});
2162
+ }
2163
+ }
2164
+ function isHigher(a, b) {
2165
+ return expTokenPrecedences[a.type] > expTokenPrecedences[b.type];
2166
+ }
1515
2167
 
1516
- const config = {
1517
- globals: {
1518
- translations: {},
1519
- },
1520
- filters: { ...filters },
1521
- compilers: { ...compilers },
1522
- autoEscape: true,
1523
- strictMode: true,
1524
- stripComments: false,
1525
- trimWhitespace: false,
1526
- };
2168
+ var TokenType;
2169
+ (function (TokenType) {
2170
+ TokenType["TEXT"] = "TEXT";
2171
+ TokenType["OUTPUT"] = "OUTPUT";
2172
+ TokenType["DIRECTIVE"] = "DIRECTIVE";
2173
+ TokenType["COMMENT"] = "COMMENT";
2174
+ })(TokenType || (TokenType = {}));
1527
2175
 
1528
2176
  function unescapeTag(v) {
1529
- return v.replace(/\\(\{|\})/g, '$1');
2177
+ return v.replace(/\\([{}])/g, '$1');
1530
2178
  }
1531
2179
 
1532
- class Parser {
2180
+ class Tokenizer {
1533
2181
  constructor(options) {
1534
2182
  Object.defineProperty(this, "options", {
1535
2183
  enumerable: true,
1536
2184
  configurable: true,
1537
2185
  writable: true,
1538
- value: options
2186
+ value: void 0
1539
2187
  });
1540
2188
  Object.defineProperty(this, "template", {
1541
2189
  enumerable: true,
1542
2190
  configurable: true,
1543
2191
  writable: true,
1544
- value: ''
2192
+ value: void 0
2193
+ });
2194
+ Object.defineProperty(this, "length", {
2195
+ enumerable: true,
2196
+ configurable: true,
2197
+ writable: true,
2198
+ value: void 0
1545
2199
  });
1546
2200
  Object.defineProperty(this, "index", {
1547
2201
  enumerable: true,
1548
2202
  configurable: true,
1549
2203
  writable: true,
1550
- value: 0
2204
+ value: void 0
1551
2205
  });
1552
- Object.defineProperty(this, "first", {
2206
+ Object.defineProperty(this, "tokens", {
1553
2207
  enumerable: true,
1554
2208
  configurable: true,
1555
2209
  writable: true,
1556
- value: null
2210
+ value: void 0
1557
2211
  });
1558
- Object.defineProperty(this, "group", {
2212
+ Object.defineProperty(this, "tokenPatterns", {
1559
2213
  enumerable: true,
1560
2214
  configurable: true,
1561
2215
  writable: true,
1562
- value: ''
2216
+ value: void 0
1563
2217
  });
1564
- Object.defineProperty(this, "blocks", {
2218
+ Object.defineProperty(this, "line", {
1565
2219
  enumerable: true,
1566
2220
  configurable: true,
1567
2221
  writable: true,
1568
- value: {}
2222
+ value: 1
1569
2223
  });
1570
- Object.defineProperty(this, "cursor", {
2224
+ Object.defineProperty(this, "column", {
1571
2225
  enumerable: true,
1572
2226
  configurable: true,
1573
2227
  writable: true,
1574
- value: null
2228
+ value: 1
1575
2229
  });
2230
+ this.options = {
2231
+ ...parserOptions,
2232
+ ...options,
2233
+ };
2234
+ 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));
1576
2252
  }
1577
- async parse(template) {
2253
+ tokenize(template) {
1578
2254
  this.template = template;
2255
+ this.length = template.length;
1579
2256
  this.index = 0;
1580
- this.blocks = {};
1581
- const tagRe = /\{\{(-)?([=#])?((?:\\[{}]|(?!\{\}).)+?)(-)?\}\}/gs;
1582
- let match;
1583
- while ((match = tagRe.exec(template))) {
1584
- if (match.index > this.index) {
1585
- this.addRaw(this.index, match.index);
2257
+ this.line = 1;
2258
+ this.column = 1;
2259
+ this.tokens = [];
2260
+ while (this.index < this.length) {
2261
+ if (this.consumeSpecialTokens()) {
2262
+ continue;
1586
2263
  }
1587
- await this.addTag(match);
1588
- this.index = match.index + match[0].length;
1589
- }
1590
- if (this.index < template.length) {
1591
- this.addRaw(this.index, template.length);
1592
- }
1593
- this.cursor = this.first;
1594
- this.rebuildBlocks();
1595
- return this.cursor;
1596
- }
1597
- addRaw(start, end) {
1598
- this.push({
1599
- name: RAW$1,
1600
- raw: this.template.slice(start, end),
1601
- previous: null,
1602
- next: null,
1603
- start,
1604
- end,
1605
- });
1606
- }
1607
- async addTag(match) {
1608
- const start = match.index;
1609
- const end = start + match[0].length;
1610
- const base = {
1611
- raw: match[0],
1612
- previous: null,
1613
- next: null,
1614
- stripBefore: match[1] === '-',
1615
- stripAfter: match[4] === '-',
1616
- start,
1617
- end,
1618
- };
1619
- if (match[2] === '#') {
1620
- this.push({
1621
- ...base,
1622
- name: match[2],
1623
- value: {
1624
- type: 'LIT',
1625
- value: unescapeTag(match[3]),
1626
- },
1627
- });
1628
- }
1629
- else if (match[2] === '=') {
1630
- this.push({
1631
- ...base,
1632
- name: match[2],
1633
- value: parser.parse(unescapeTag(match[3])),
1634
- });
2264
+ this.consumeTextToken();
1635
2265
  }
1636
- else {
1637
- const [, name, value = ''] = match[3].trim().match(/^([a-z]+)(?: (.+))?$/) ?? [];
1638
- if (name === LAYOUT) {
1639
- await this.layout(value);
2266
+ return this.tokens;
2267
+ }
2268
+ consumeSpecialTokens() {
2269
+ return this.tokenPatterns.some(([type, openMarker, closeMarker]) => {
2270
+ if (!this.lookahead(openMarker)) {
2271
+ return false;
1640
2272
  }
1641
- else if (name === INCLUDE) {
1642
- await this.include(value);
2273
+ const start = {
2274
+ line: this.line,
2275
+ column: this.column,
2276
+ };
2277
+ const endIndex = this.template.indexOf(closeMarker, this.index + openMarker.length);
2278
+ if (endIndex === -1) {
2279
+ throw new CompileError(`Unclosed "${openMarker}"`, this.template, {
2280
+ start,
2281
+ end: updatePosition(openMarker, { ...start }),
2282
+ });
1643
2283
  }
1644
- else {
1645
- this.push({
1646
- ...base,
2284
+ const stripBefore = this.lookahead('-', openMarker.length);
2285
+ const stripAfter = this.template[endIndex - 1] === '-';
2286
+ const val = this.template.slice(this.index + openMarker.length + +stripBefore, endIndex - +stripAfter);
2287
+ const end = updatePosition(this.template.slice(this.index, (this.index = endIndex + closeMarker.length)), this);
2288
+ const token = {
2289
+ type,
2290
+ val: unescapeTag(val),
2291
+ strip: {
2292
+ before: stripBefore,
2293
+ after: stripAfter,
2294
+ },
2295
+ loc: {
2296
+ start,
2297
+ end,
2298
+ },
2299
+ };
2300
+ if (type === TokenType.DIRECTIVE) {
2301
+ let i = 0;
2302
+ let name = '';
2303
+ while (i < val.length) {
2304
+ const char = val[i];
2305
+ if (/\S/.test(char)) {
2306
+ name += char;
2307
+ }
2308
+ else if (name) {
2309
+ break;
2310
+ }
2311
+ i++;
2312
+ }
2313
+ Object.assign(token, {
1647
2314
  name,
1648
- value: parser.parse(unescapeTag(value)),
2315
+ expression: i === val.length || /^\s*$/m.test(val.slice(i + 1))
2316
+ ? null
2317
+ : {
2318
+ val: val.slice(i + 1),
2319
+ loc: {
2320
+ start: updatePosition(val.slice(0, i + 1), updatePosition(`${openMarker}${stripBefore ? '-' : ''}`, { ...start })),
2321
+ end: {
2322
+ line: this.line,
2323
+ column: this.column - closeMarker.length - +stripAfter,
2324
+ },
2325
+ },
2326
+ },
1649
2327
  });
1650
2328
  }
1651
- }
2329
+ this.tokens.push(token);
2330
+ return true;
2331
+ });
1652
2332
  }
1653
- async layout(value) {
1654
- const exp = parser.parse(value);
1655
- if (exp?.type !== 'LIT' || typeof exp.value !== 'string' || !exp.value) {
1656
- throw new ParseError(`"layout" tag must have a file path`, {
1657
- source: this.template,
1658
- range: {
1659
- start: this.index,
1660
- end: this.index + value.length,
2333
+ consumeTextToken() {
2334
+ 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),
1661
2347
  },
2348
+ strip: {},
1662
2349
  });
2350
+ this.index = nextSpecialIndex;
1663
2351
  }
1664
- await this.child(`layouts/${exp.value}.janja`);
1665
- }
1666
- async include(value) {
1667
- const exp = parser.parse(value.replace(/\?$/, ''));
1668
- if (exp?.type !== 'LIT' || typeof exp.value !== 'string' || !exp.value) {
1669
- throw new ParseError(`"include" tag must have a file path`, {
1670
- source: this.template,
1671
- range: {
1672
- start: this.index,
1673
- end: this.index + value.length,
1674
- },
1675
- });
2352
+ else {
2353
+ updatePosition(this.template[this.index++], this);
1676
2354
  }
1677
- await this.child(`partials/${exp.value}.janja`, value.endsWith('?'));
1678
2355
  }
1679
- async child(path, optional) {
1680
- let content;
1681
- try {
1682
- content = await this.options.loader(path);
1683
- }
1684
- catch (error) {
1685
- if (optional) {
1686
- return;
1687
- }
1688
- throw error;
1689
- }
1690
- if (!content) {
1691
- return;
1692
- }
1693
- let cursor = await new Parser(this.options).parse(content);
1694
- while (cursor) {
1695
- this.push(cursor);
1696
- cursor = cursor.next;
1697
- }
2356
+ lookahead(marker, offset = 0) {
2357
+ return this.template.startsWith(marker, this.index + offset);
1698
2358
  }
1699
- push(tag) {
1700
- if (tag.name === BLOCK) {
1701
- const { type, value } = tag.value;
1702
- if (type !== 'ID') {
1703
- throw new ParseError(`"${BLOCK}" tag must have a title`, {
1704
- source: this.template,
1705
- range: {
1706
- start: this.index,
1707
- end: this.index + value.length,
1708
- },
1709
- });
2359
+ findNextSpecialIndex() {
2360
+ const { outputOpen, directiveOpen, commentOpen, } = this.options;
2361
+ const commentIndex = this.template.indexOf(commentOpen, this.index);
2362
+ const directiveIndex = this.template.indexOf(directiveOpen, this.index);
2363
+ const outputIndex = this.template.indexOf(outputOpen, this.index);
2364
+ const indexes = [
2365
+ commentIndex,
2366
+ directiveIndex,
2367
+ outputIndex,
2368
+ ]
2369
+ .filter(index => index !== -1)
2370
+ .sort((a, b) => a - b);
2371
+ return indexes.length ? indexes[0] : this.length;
2372
+ }
2373
+ }
2374
+
2375
+ class Parser extends Tokenizer {
2376
+ constructor() {
2377
+ super(...arguments);
2378
+ Object.defineProperty(this, "expParser", {
2379
+ enumerable: true,
2380
+ configurable: true,
2381
+ writable: true,
2382
+ value: void 0
2383
+ });
2384
+ Object.defineProperty(this, "cursor", {
2385
+ enumerable: true,
2386
+ configurable: true,
2387
+ writable: true,
2388
+ value: void 0
2389
+ });
2390
+ }
2391
+ parse(template) {
2392
+ this.tokenize(template);
2393
+ const start = this.tokens[0]?.loc.start ?? { line: 1, column: 1 };
2394
+ const end = this.tokens.at(-1)?.loc.end ?? { line: 1, column: 1 };
2395
+ this.expParser = new ExpParser(template);
2396
+ this.cursor = 0;
2397
+ return new RootNode(this.parseUntil(), { start, end });
2398
+ }
2399
+ parseUntil(names) {
2400
+ const nodes = [];
2401
+ let prevToken = null;
2402
+ while (true) {
2403
+ const token = this.peek();
2404
+ if (!token
2405
+ || (token.type === TokenType.DIRECTIVE
2406
+ && names
2407
+ && this.match(names, token))) {
2408
+ break;
1710
2409
  }
1711
- this.group = value;
1712
- // child blocks
1713
- if (this.blocks[value]) {
1714
- this.blocks[value].push([tag]);
1715
- return;
2410
+ if (prevToken?.strip?.after && token.type === TokenType.TEXT) {
2411
+ token.strip.start = true;
1716
2412
  }
1717
- // parent block
1718
- this.blocks[value] = [[tag]];
1719
- }
1720
- else if (this.group) {
1721
- const chunks = this.blocks[this.group];
1722
- if (tag.name === ENDBLOCK) {
1723
- this.group = '';
2413
+ if (token.strip?.before && prevToken?.type === TokenType.TEXT) {
2414
+ prevToken.strip.end = true;
1724
2415
  }
1725
- chunks.at(-1).push(tag);
1726
- // child blocks
1727
- if (chunks.length > 1) {
1728
- return;
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;
1729
2429
  }
2430
+ prevToken = token;
1730
2431
  }
1731
- if (this.cursor) {
1732
- tag.previous = this.cursor;
1733
- this.cursor.next = tag;
2432
+ return nodes;
2433
+ }
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));
2452
+ this.advance();
2453
+ return new UnexpectedDirectiveNode(token.name, token.val, token.loc, token.strip);
2454
+ }
2455
+ createUnknownDirective(token) {
2456
+ this.options.debug?.(new CompileError(`Unknown "${token.name}" directive`, this.template, token.loc));
2457
+ this.advance();
2458
+ return new UnknownDirectiveNode(token.name, token.val, token.loc, token.strip);
2459
+ }
2460
+ parseExp({ val, loc }) {
2461
+ return this.expParser.parse(val, loc);
2462
+ }
2463
+ peek() {
2464
+ return this.tokens.at(this.cursor) ?? null;
2465
+ }
2466
+ advance() {
2467
+ this.cursor++;
2468
+ }
2469
+ match(names, token = this.peek()) {
2470
+ return names.includes(token?.name);
2471
+ }
2472
+ requireExpression({ expression, name, loc }) {
2473
+ if (!expression) {
2474
+ throw this.options.debug?.(new CompileError(`"${name}" requires expression`, this.template, loc));
1734
2475
  }
1735
- else {
1736
- this.first = tag;
2476
+ }
2477
+ requireNoExpression({ expression, name, loc }) {
2478
+ if (expression) {
2479
+ throw this.options.debug?.(new CompileError(`"${name}" should not have expression`, this.template, loc));
1737
2480
  }
1738
- this.cursor = tag;
1739
- }
1740
- /**
1741
- * @note Block tags are hoisted to top level
1742
- */
1743
- rebuildBlocks() {
1744
- for (const chunks of Object.values(this.blocks)) {
1745
- if (chunks.length < 2) {
1746
- continue;
1747
- }
1748
- const [[{ previous }]] = chunks;
1749
- const { next } = chunks[0].at(-1);
1750
- // break the chain
1751
- if (previous) {
1752
- if (previous.next) {
1753
- previous.next.previous = null;
2481
+ }
2482
+ }
2483
+
2484
+ class Compiler extends Context {
2485
+ constructor(options) {
2486
+ super();
2487
+ Object.defineProperty(this, "options", {
2488
+ enumerable: true,
2489
+ configurable: true,
2490
+ writable: true,
2491
+ value: void 0
2492
+ });
2493
+ Object.defineProperty(this, "template", {
2494
+ enumerable: true,
2495
+ configurable: true,
2496
+ writable: true,
2497
+ value: void 0
2498
+ });
2499
+ Object.defineProperty(this, "state", {
2500
+ enumerable: true,
2501
+ configurable: true,
2502
+ writable: true,
2503
+ value: void 0
2504
+ });
2505
+ Object.defineProperty(this, "isRoot", {
2506
+ enumerable: true,
2507
+ configurable: true,
2508
+ writable: true,
2509
+ value: void 0
2510
+ });
2511
+ Object.defineProperty(this, "rootNode", {
2512
+ enumerable: true,
2513
+ configurable: true,
2514
+ writable: true,
2515
+ value: void 0
2516
+ });
2517
+ Object.defineProperty(this, "partials", {
2518
+ enumerable: true,
2519
+ configurable: true,
2520
+ writable: true,
2521
+ value: void 0
2522
+ });
2523
+ Object.defineProperty(this, "blocks", {
2524
+ enumerable: true,
2525
+ configurable: true,
2526
+ writable: true,
2527
+ value: void 0
2528
+ });
2529
+ this.options = {
2530
+ ...compilerOptions,
2531
+ ...options,
2532
+ };
2533
+ }
2534
+ async compile(template, root = true, partials = new Map(), blocks = new Map()) {
2535
+ this.template = template;
2536
+ this.isRoot = root;
2537
+ this.partials = partials;
2538
+ this.blocks = blocks;
2539
+ this.rootNode = new Parser(this.options).parse(template);
2540
+ this.state = {};
2541
+ this.start();
2542
+ await this.parseTemplates();
2543
+ if (this.isRoot) {
2544
+ if (this.partials.size) {
2545
+ this.pushRaw(null, `const p={`);
2546
+ for (const [path, code] of this.partials) {
2547
+ this.pushRaw(null, `"${path}":async()=>{`, code, `},`);
1754
2548
  }
1755
- previous.next = null;
1756
- }
1757
- else {
1758
- this.first = null;
1759
- this.cursor = null;
1760
- }
1761
- if (next) {
1762
- if (next.previous) {
1763
- next.previous.next = null;
2549
+ this.pushRaw(null, `};`);
2550
+ }
2551
+ 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:[`);
2555
+ this.state.block = name;
2556
+ for (const block of blocks) {
2557
+ this.pushRaw(null, `async()=>{`, `let s="";`);
2558
+ await this.compileNodes(block.body);
2559
+ this.pushRaw(null, `return s;`, `},`);
2560
+ }
2561
+ this.state.block = undefined;
2562
+ this.pushRaw(null, `],`, `},`);
1764
2563
  }
1765
- next.previous = null;
2564
+ this.pushRaw(null, `};`);
1766
2565
  }
1767
- const body = this.rebuildBlockBody(chunks.pop(), chunks);
1768
- this.rebuildBlockChain(body, previous, next);
1769
2566
  }
2567
+ await this.compileNode(this.rootNode);
2568
+ this.end();
2569
+ return this;
1770
2570
  }
1771
- rebuildBlockBody(child, parents) {
1772
- if (!child) {
1773
- return [];
2571
+ async parseTemplates() {
2572
+ const { partials, blocks } = this.collectPartialsAndBlocks();
2573
+ for (const [path, node] of partials) {
2574
+ if (!this.partials.has(path)) {
2575
+ let template;
2576
+ try {
2577
+ template = await this.options.loader(path);
2578
+ }
2579
+ catch {
2580
+ this.options.debug?.(new CompileError(`Failed to load template from "${path}"`, this.template, node.loc));
2581
+ return;
2582
+ }
2583
+ if (template) {
2584
+ await this.compilePartial(path, node, template);
2585
+ }
2586
+ }
1774
2587
  }
1775
- const chunk = [];
1776
- child.forEach((tag) => {
1777
- if (tag.name === SUPER) {
1778
- this.rebuildBlockBody(parents.pop(), parents).forEach(t => chunk.push(t));
2588
+ for (const block of blocks) {
2589
+ const { val: { value } } = block;
2590
+ if (!this.blocks.has(value)) {
2591
+ this.blocks.set(value, []);
1779
2592
  }
1780
- else {
1781
- chunk.push(tag);
2593
+ this.blocks.get(value).push(block);
2594
+ }
2595
+ }
2596
+ collectPartialsAndBlocks() {
2597
+ const partials = new Map();
2598
+ const blocks = [];
2599
+ const traverse = (node) => {
2600
+ if (node.type === NodeType.INCLUDE) {
2601
+ if (!partials.has(node.val.value)) {
2602
+ partials.set(node.val.value, node);
2603
+ }
1782
2604
  }
1783
- });
1784
- return chunk;
2605
+ if (node.type === NodeType.BLOCK) {
2606
+ blocks.push(node);
2607
+ }
2608
+ node.traverse(traverse);
2609
+ };
2610
+ traverse(this.rootNode);
2611
+ return {
2612
+ partials,
2613
+ blocks,
2614
+ };
1785
2615
  }
1786
- rebuildBlockChain(tags, previous, next) {
1787
- for (let i = 0; i < tags.length; i++) {
1788
- tags[i].previous = tags[i - 1] || previous;
1789
- tags[i].next = tags[i + 1] || next;
2616
+ async compileNode(node) {
2617
+ if (node.type === NodeType.TEMPLATE) {
2618
+ await this.compileNodes(node.body);
2619
+ return;
1790
2620
  }
1791
- if (previous) {
1792
- [previous.next] = tags;
2621
+ if (this.options.compilers[node.type]) {
2622
+ await this.options.compilers[node.type](node, this);
2623
+ return;
2624
+ }
2625
+ this.options.debug?.(new CompileError(`Unknown "${node.name}" directive`, this.template, node.loc));
2626
+ }
2627
+ async compileNodes(nodes) {
2628
+ for (const child of nodes) {
2629
+ await this.compileNode(child);
1793
2630
  }
1794
- if (next) {
1795
- next.previous = tags[tags.length - 1];
2631
+ }
2632
+ async compilePartial(path, node, template) {
2633
+ try {
2634
+ const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks);
2635
+ this.partials.set(path, code);
1796
2636
  }
1797
- if (!this.first) {
1798
- [this.first] = tags;
1799
- this.cursor = this.first;
2637
+ catch {
2638
+ this.options.debug?.(new CompileError(`Failed to compile template`, this.template, node.loc));
1800
2639
  }
1801
2640
  }
1802
2641
  }
1803
2642
 
1804
- class RenderError extends Error {
1805
- constructor(message, options) {
1806
- super(message);
1807
- Object.defineProperty(this, "options", {
2643
+ class RenderError extends CompileError {
2644
+ constructor(message, src, getLoc) {
2645
+ super(message, src);
2646
+ Object.defineProperty(this, "src", {
2647
+ enumerable: true,
2648
+ configurable: true,
2649
+ writable: true,
2650
+ value: src
2651
+ });
2652
+ Object.defineProperty(this, "getLoc", {
1808
2653
  enumerable: true,
1809
2654
  configurable: true,
1810
2655
  writable: true,
1811
- value: options
2656
+ value: getLoc
1812
2657
  });
1813
- this.name = 'RenderError';
1814
- Error.captureStackTrace?.(this, this.constructor);
2658
+ this.name = 'CompileError';
2659
+ RenderError.captureStackTrace?.(this, this.constructor);
1815
2660
  }
1816
2661
  get details() {
1817
- const ranges = this.options.sourcemap.getRanges(+(this.options.error.stack.match(/<anonymous>:\d:(\d+)\)/)?.[1] ?? 0));
1818
- return highlightSource(this.message, this.options.source, ranges);
2662
+ this.loc = this.getLoc();
2663
+ return super.details;
1819
2664
  }
1820
2665
  }
1821
2666
 
1822
- class Engine {
1823
- constructor({ globals, filters, compilers, ...options } = {}) {
2667
+ class Renderer {
2668
+ constructor({ globals, filters, parsers, compilers, ...options } = {}) {
1824
2669
  Object.defineProperty(this, "options", {
1825
2670
  enumerable: true,
1826
2671
  configurable: true,
1827
2672
  writable: true,
1828
2673
  value: void 0
1829
2674
  });
1830
- this.options = { ...config, ...options };
2675
+ this.options = { ...renderOptions, ...options };
1831
2676
  Object.assign(this.options.globals, globals);
1832
2677
  Object.assign(this.options.filters, filters);
2678
+ Object.assign(this.options.parsers, parsers);
1833
2679
  Object.assign(this.options.compilers, compilers);
1834
2680
  }
1835
2681
  async render(template, globals) {
1836
- const { script, sourcemap } = await this._compile(template);
1837
- return this._render(template, globals, script, sourcemap);
1838
- }
1839
- async renderFile(filepath, globals) {
1840
- if (this.options.cache?.has(filepath)) {
1841
- const { template, script, sourcemap } = this.options.cache.get(filepath);
1842
- return this._render(template, globals, script, sourcemap);
1843
- }
1844
- const template = await this.options.loader(filepath);
1845
- const { script, sourcemap } = await this._compile(template);
1846
- this.options.cache?.set(filepath, { template, script, sourcemap });
1847
- return this._render(template, globals, script, sourcemap);
1848
- }
1849
- async _compile(template, filepath) {
1850
- return new Compiler(this.options).compile(await new Parser(this.options).parse(template), filepath);
1851
- }
1852
- async _render(template, globals, script, sourcemap) {
2682
+ const compiler = new Compiler(this.options);
1853
2683
  try {
1854
- return await script({ ...this.options.globals, ...globals }, { ...this.options.filters, ...filters }, (v) => {
2684
+ await compiler.compile(template);
2685
+ return await compiler.script({ ...this.options.globals, ...globals }, (v) => {
1855
2686
  if (v instanceof Safe) {
1856
2687
  return `${v}`;
1857
2688
  }
1858
2689
  return this.options.autoEscape ? escape(v) : v;
1859
- });
2690
+ }, { ...this.options.filters, ...filters });
1860
2691
  }
1861
2692
  catch (error) {
1862
- throw new RenderError(error.message, {
1863
- source: template,
1864
- error,
1865
- sourcemap,
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 ?? '';
2700
+ }
2701
+ const [loc] = compiler.getSourceLoc({
2702
+ line: +matched[1] - 2,
2703
+ column: +matched[2],
2704
+ });
2705
+ return loc;
1866
2706
  });
1867
2707
  }
1868
2708
  }
2709
+ async renderFile(filepath, globals) {
2710
+ return this.render(await this.options.loader(filepath), globals);
2711
+ }
1869
2712
  }
2713
+
1870
2714
  async function render(template, data, options) {
1871
- return new Engine(options).render(template, data);
2715
+ return new Renderer(options).render(template, data);
1872
2716
  }
1873
2717
  async function renderFile(filepath, data, options) {
1874
- return new Engine(options).renderFile(filepath, data);
2718
+ return new Renderer(options).renderFile(filepath, data);
1875
2719
  }
1876
2720
 
1877
- exports.Engine = Engine;
1878
- exports.ExpCompiler = ExpCompiler;
1879
- exports.ExpParser = ExpParser;
1880
- exports.compiler = compiler;
1881
- exports.parser = parser;
2721
+ exports.Renderer = Renderer;
1882
2722
  exports.render = render;
1883
2723
  exports.renderFile = renderFile;
1884
2724