janja 1.1.0 → 2.0.0

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