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