mutorjs 1.3.1 → 1.3.3

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.cjs CHANGED
@@ -1,1350 +1,14 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- default: () => index_default
24
- });
25
- module.exports = __toCommonJS(index_exports);
26
-
27
- // src/utils/construct-pointer.ts
28
- function constructPointer(pos, offset) {
29
- return `${" ".repeat(pos + offset + 1)}^`;
30
- }
31
-
32
- // src/core/error.ts
33
- var MutorError = class _MutorError extends Error {
34
- constructor(message) {
35
- super(message);
36
- this.name = "MutorError";
37
- Object.setPrototypeOf(this, _MutorError.prototype);
38
- }
39
- };
40
- var MutorCompilerError = class _MutorCompilerError extends MutorError {
41
- constructor(message, line, lineText, column, file) {
42
- const gutterWidth = line.toString().length + 2;
43
- let report = `${message}
44
-
45
- `;
46
- report += `at ${file}:${line}:${column + 1}
47
- `;
48
- if (line > 1) {
49
- report += `${(line - 1).toString().padStart(gutterWidth - 2)} | ...
50
- `;
51
- }
52
- report += `${line} | ${lineText}
53
- `;
54
- report += constructPointer(column, gutterWidth);
55
- super(report);
56
- this.name = "MutorCompilerError";
57
- Object.setPrototypeOf(this, _MutorCompilerError.prototype);
58
- }
59
- };
60
-
61
- // src/core/constants.ts
62
- var keywords = /* @__PURE__ */ new Set([
63
- "for",
64
- "if",
65
- "else",
66
- "true",
67
- "false",
68
- "null",
69
- "undefined",
70
- "end",
71
- "in",
72
- "of"
73
- ]);
74
- var operators = /* @__PURE__ */ new Set([
75
- "::",
76
- // Namespace access
77
- "||",
78
- // Or
79
- "??",
80
- // Nullish coalesce
81
- "&&",
82
- // And
83
- "**",
84
- // Power
85
- "^",
86
- // Bitwise XOr
87
- "|",
88
- // Bitwise Or
89
- "&",
90
- // Bitwise And
91
- "!",
92
- // Not
93
- "-",
94
- // Minus
95
- "%",
96
- // Modulus
97
- "+",
98
- // Plus
99
- "*",
100
- // Times
101
- "/",
102
- // Divide
103
- ">",
104
- // Greater than
105
- "<",
106
- // Less than
107
- ">=",
108
- // Greater or equal
109
- "<=",
110
- // Less or equal
111
- "==",
112
- // Strict equal
113
- "!=",
114
- // Strict not equal
115
- ">>",
116
- // Bitwise right shift
117
- "<<",
118
- // Bitwise left shift
119
- ".",
120
- // Property acess
121
- "?.",
122
- // Optional property access
123
- "(",
124
- // Open parentheses
125
- ")",
126
- // Close parentheses
127
- "[",
128
- // Square open parentheses
129
- "]",
130
- // Square close parentheses
131
- ",",
132
- // Comma
133
- ":",
134
- // Column
135
- "?"
136
- // Ternary operator
137
- ]);
138
- var equalityOperators = /* @__PURE__ */ new Set(["==", "!="]);
139
- var comparisonOperators = /* @__PURE__ */ new Set([">", "<", ">=", "<="]);
140
- var additiveOperators = /* @__PURE__ */ new Set(["+", "-"]);
141
- var multiplicativeOperators = /* @__PURE__ */ new Set(["*", "/", "%"]);
142
- var propertyAccessOperators = /* @__PURE__ */ new Set([".", "?.", "[", "::"]);
143
- var unaryOperators = /* @__PURE__ */ new Set(["-", "+", "!"]);
144
- var ESCAPE_MAP = {
145
- "&": "&amp;",
146
- "<": "&lt;",
147
- ">": "&gt;",
148
- '"': "&quot;",
149
- "'": "&#39;"
150
- };
151
- var defaultConfig = {
152
- build: {
153
- include: /* @__PURE__ */ new Set([".html", ".txt"]),
154
- exclude: /* @__PURE__ */ new Set(["node_modules", ".git"])
155
- },
156
- autoEscape: true,
157
- allowedProps: /* @__PURE__ */ new Set(),
158
- forbiddenProps: /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]),
159
- allowFnCalls: false,
160
- delimiters: {
161
- closingTag: "}}",
162
- openingTag: "{{",
163
- openingTagEscape: "\\",
164
- whitespaceTrim: "~",
165
- commentTag: "#"
166
- },
167
- keepOpeningTagEscapeDelimiter: false,
168
- cache: {
169
- active: true,
170
- maxSize: 50 * 1024 * 1024
171
- // 50MB
172
- }
173
- };
174
- var namespaces = {
175
- JSON: {
176
- stringify(value) {
177
- try {
178
- return JSON.stringify(value);
179
- } catch {
180
- throw new MutorError("JSON.stringify failed: invalid value");
181
- }
182
- },
183
- parse(str) {
184
- if (typeof str !== "string") {
185
- throw new MutorError("JSON.parse expects a string");
186
- }
187
- try {
188
- return JSON.parse(str);
189
- } catch {
190
- throw new MutorError("JSON.parse failed: invalid JSON string");
191
- }
192
- }
193
- },
194
- Object: {
195
- keys(obj) {
196
- if (!obj || typeof obj !== "object") {
197
- throw new MutorError("Object.keys expects an object");
198
- }
199
- return Object.keys(obj);
200
- },
201
- values(obj) {
202
- if (!obj || typeof obj !== "object") {
203
- throw new MutorError("Object.values expects an object");
204
- }
205
- return Object.values(obj);
206
- },
207
- entries(obj) {
208
- if (!obj || typeof obj !== "object") {
209
- throw new MutorError("Object.entries expects an object");
210
- }
211
- return Object.entries(obj);
212
- },
213
- hasOwn(obj, key) {
214
- if (!obj || typeof obj !== "object") {
215
- throw new MutorError("Object.hasOwn expects an object");
216
- }
217
- return Object.hasOwn(obj, key);
218
- },
219
- freeze(obj) {
220
- if (!obj || typeof obj !== "object") {
221
- throw new MutorError("Object.freeze expects an object");
222
- }
223
- return Object.freeze(obj);
224
- },
225
- seal(obj) {
226
- if (!obj || typeof obj !== "object") {
227
- throw new MutorError("Object.seal expects an object");
228
- }
229
- return Object.seal(obj);
230
- },
231
- fromEntries(entries) {
232
- if (!Array.isArray(entries)) {
233
- throw new MutorError("Object.fromEntries expects an array");
234
- }
235
- return Object.fromEntries(entries);
236
- }
237
- },
238
- Array: {
239
- isArray(value) {
240
- return Array.isArray(value);
241
- },
242
- from(value) {
243
- return Array.from(value);
244
- }
245
- },
246
- Number: {
247
- isFinite(value) {
248
- return Number.isFinite(value);
249
- },
250
- isNaN(value) {
251
- return Number.isNaN(value);
252
- },
253
- parseInt(value, radix = 10) {
254
- return Number.parseInt(value, radix);
255
- },
256
- parseFloat(value) {
257
- return Number.parseFloat(value);
258
- }
259
- },
260
- String: {
261
- fromCharCode(...args) {
262
- return String.fromCharCode(...args);
263
- }
264
- },
265
- Math: {
266
- abs(x) {
267
- return Math.abs(x);
268
- },
269
- floor(x) {
270
- return Math.floor(x);
271
- },
272
- ceil(x) {
273
- return Math.ceil(x);
274
- },
275
- round(x) {
276
- return Math.round(x);
277
- },
278
- max(...args) {
279
- return Math.max(...args);
280
- },
281
- min(...args) {
282
- return Math.min(...args);
283
- },
284
- random() {
285
- return Math.random();
286
- }
287
- },
288
- Date: {
289
- now() {
290
- return Date.now();
291
- },
292
- parse(str) {
293
- if (typeof str !== "string") {
294
- throw new MutorError("Date.parse expects a string");
295
- }
296
- return Date.parse(str);
297
- }
298
- },
299
- Boolean: {
300
- valueOf(value) {
301
- return Boolean(value);
302
- }
303
- }
304
- };
305
-
306
- // src/utils/escape-fn.ts
307
- function escapeFn(e) {
308
- if (typeof e !== "string") return e;
309
- return /[&<>"']/.test(e) ? e.replace(/[&<>"']/g, (char) => ESCAPE_MAP[char]) : e;
310
- }
311
-
312
- // src/utils/validate-computed-prop.ts
313
- function validateComputedProp(r, allowedProps, forbiddenProps) {
314
- if (forbiddenProps.has(r) && !allowedProps.has(r)) {
315
- throw new MutorError(
316
- `Forbidden property access. Access to this computed property "${r}" is forbidden.`
317
- );
318
- }
319
- return r;
320
- }
321
-
322
- // src/utils/validate-context.ts
323
- var OBJECT = "object";
324
- var MUTOR_SAFE = /* @__PURE__ */ Symbol("__mutor_safe_context");
325
- function validateContext(ctx) {
326
- if (!ctx || typeof ctx !== OBJECT) {
327
- return ctx;
328
- }
329
- if (MUTOR_SAFE in ctx) {
330
- return ctx;
331
- }
332
- const seen = /* @__PURE__ */ new WeakSet();
333
- function walk(value, path = "") {
334
- if (!value || typeof value !== OBJECT) return value;
335
- if (seen.has(value)) return value;
336
- seen.add(value);
337
- const proto = Object.getPrototypeOf(value);
338
- if (proto && proto !== Object.prototype && proto !== Array.prototype) {
339
- throw new MutorError(`Unsafe prototype detected at ${path || "root"}`);
340
- }
341
- if (Array.isArray(value)) {
342
- for (let i = 0; i < value.length; i++) {
343
- value[i] = walk(value[i], `${path}[${i}]`);
344
- }
345
- return value;
346
- }
347
- if (value instanceof Map) {
348
- for (const [k, v] of value.entries()) {
349
- if (typeof k === OBJECT) walk(k, `${path}.mapKey`);
350
- value.set(k, walk(v, `${path}.mapValue`));
351
- }
352
- return value;
353
- }
354
- if (value instanceof Set) {
355
- const next = /* @__PURE__ */ new Set();
356
- for (const v of value.values()) {
357
- next.add(walk(v, path));
358
- }
359
- value.clear();
360
- for (const v of next) value.add(v);
361
- return value;
362
- }
363
- const descriptors = Object.getOwnPropertyDescriptors(value);
364
- for (const key of Object.keys(descriptors)) {
365
- const desc = descriptors[key];
366
- if (desc.get || desc.set) {
367
- throw new MutorError(`Getter/setter not allowed: ${path}.${key}`);
368
- }
369
- const prop = value[key];
370
- if (prop && typeof prop === OBJECT) {
371
- value[key] = walk(prop, `${path}.${key}`);
372
- }
373
- }
374
- return value;
375
- }
376
- const safeData = walk(ctx);
377
- if (safeData && typeof safeData === OBJECT) {
378
- Object.defineProperty(safeData, MUTOR_SAFE, {
379
- value: true,
380
- enumerable: false,
381
- writable: false,
382
- configurable: false
383
- });
384
- }
385
- return safeData;
386
- }
387
-
388
- // src/utils/escape-raw-text.ts
389
- function escapeRawText(text) {
390
- return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
391
- }
392
-
393
- // src/utils/get-line-and-column-nums.ts
394
- function getLineAndColumnNumbers(str, idx) {
395
- const lines = str.slice(0, idx).split("\n");
396
- const line = lines.length;
397
- const lineIndex = str.lastIndexOf("\n", idx - 1) + 1;
398
- return { line, lineIndex };
399
- }
400
-
401
- // src/utils/get-line-snapshot.ts
402
- function getLineSnapshot(str, lineIdx, idx) {
403
- const nextNewlineIdx = str.indexOf("\n", lineIdx);
404
- const line = str.slice(
405
- lineIdx,
406
- nextNewlineIdx === -1 ? void 0 : nextNewlineIdx
407
- );
408
- return { line, pos: idx - lineIdx };
409
- }
410
-
411
- // src/core/build.ts
412
- function build(ast, context) {
413
- const { scope, forbiddenProps, allowedProps } = context;
414
- function prefixWithCtx(ident) {
415
- return scope.includes(ident) ? ident : `ctx.${ident}`;
416
- }
417
- function buildExpr(expr) {
418
- switch (expr.type) {
419
- case 17 /* END */:
420
- return "}";
421
- case 5 /* NUMBER */:
422
- return expr.value;
423
- case 4 /* STRING */:
424
- return `\`${/\$/.test(expr.value) ? expr.value.replaceAll("$", "\\$") : expr.value}\``;
425
- case 10 /* BOOLEAN */:
426
- return expr.true ? "true" : "false";
427
- case 12 /* NULL */:
428
- return "null";
429
- case 11 /* UNDEFINED */:
430
- return "undefined";
431
- case 7 /* IDENT */:
432
- return prefixWithCtx(expr.value);
433
- case 9 /* GROUP */:
434
- return `(${buildExpr(expr.expr)})`;
435
- case 2 /* UNARY */:
436
- return `${expr.operator}${buildExpr(expr.expr)}`;
437
- case 0 /* BINARY */:
438
- return `${buildExpr(expr.left)} ${expr.operator} ${buildExpr(expr.right)}`;
439
- case 1 /* TERNARY */:
440
- return `${buildExpr(expr.condition)} ? ${buildExpr(expr.left)} : ${buildExpr(expr.right)}`;
441
- case 8 /* PROP_ACCESS */:
442
- return buildPropAccess(expr);
443
- case 3 /* CALL */:
444
- return buildCall(expr);
445
- case 6 /* NAMESPACE */:
446
- return buildNamespace(expr);
447
- case 13 /* FOR */:
448
- return buildForLoop(expr);
449
- case 16 /* ELSE */:
450
- return "} else {";
451
- case 14 /* IF */:
452
- return buildIfBlock(expr);
453
- case 15 /* ELSE_IF */:
454
- return buildElseIfBlock(expr);
455
- default:
456
- throw new MutorError(
457
- `Unsupported expression type: ${expr.type}`
458
- );
459
- }
460
- }
461
- function buildNamespace(expr) {
462
- if (expr.left.type !== 7 /* IDENT */) {
463
- throw {
464
- message: "Invalid usage of namespace operator.",
465
- pos: expr.pos
466
- };
467
- }
468
- return `namespaces.${expr.left.value}.${expr.right.value}`;
469
- }
470
- function buildPropAccess(expr) {
471
- const left = buildExpr(expr.left);
472
- if (expr.bracketNotation) {
473
- const right = buildExpr(expr.right);
474
- const optionalChain = expr.optional ? "?." : "";
475
- return expr.right.type === 4 /* STRING */ || expr.right.type === 5 /* NUMBER */ ? `${left}${optionalChain}[${right}]` : `${left}${optionalChain}[validateComputedProps(${right}, allowedProps, forbiddenProps)]`;
476
- } else {
477
- const propName = expr.right.value;
478
- const optionalChain = expr.optional ? "?." : ".";
479
- if (forbiddenProps.has(propName) && !allowedProps.has(propName)) {
480
- throw { message: "Forbidden property access.", pos: expr.right.pos };
481
- }
482
- return `${left}${optionalChain}${propName}`;
483
- }
484
- }
485
- function buildCall(expr) {
486
- const func = buildExpr(expr.expr);
487
- const optionalChain = expr.optional ? "?." : "";
488
- const args = expr.args.map((arg) => buildExpr(arg)).join(", ");
489
- return `${func}${optionalChain}(${args})`;
490
- }
491
- function buildForLoop(expr) {
492
- const { iterable, loopType, variable } = expr;
493
- return `for(const ${variable} ${loopType === 1 /* IN */ ? "in" : "of"} ${build(iterable, context)}){`;
494
- }
495
- function buildIfBlock(expr) {
496
- const { condition } = expr;
497
- return `if(${build(condition, context)}){`;
498
- }
499
- function buildElseIfBlock(expr) {
500
- const { condition } = expr;
501
- return `}else if(${build(condition, context)}){`;
502
- }
503
- return buildExpr(ast);
504
- }
505
-
506
- // src/utils/get-token-type-words.ts
507
- function getTokenTypeWords(type) {
508
- switch (type) {
509
- case 0 /* IDENT */:
510
- return "identifier";
511
- case 1 /* KEYWORD */:
512
- return "keyword";
513
- case 2 /* NUMBER */:
514
- return "number";
515
- case 4 /* OPERATOR */:
516
- return "operator";
517
- case 3 /* STRING */:
518
- return "string";
519
- }
520
- }
521
-
522
- // src/core/generate-ast.ts
523
- function generateAst(tokens, config) {
524
- let cursor = 0, generatingNamespace = false;
525
- function expectOrThrow(type, value) {
526
- const token = tokens[cursor];
527
- const lastToken = tokens[tokens.length - 1];
528
- if (!token) {
529
- throw {
530
- message: `Unexpected end of expression. Expected ${value ? `'${value}'` : `${type === 0 /* IDENT */ ? "an" : "a"} ${getTokenTypeWords(type)}`}.`,
531
- pos: lastToken.pos + lastToken.value.length - 1
532
- };
533
- }
534
- if (token.type !== type) {
535
- throw {
536
- message: `Unexpected token type. Expected ${value ? `'${value}'` : getTokenTypeWords(type)} but got ${getTokenTypeWords(token.type)} instead.`,
537
- pos: token.pos
538
- };
539
- }
540
- if (value !== void 0 && token.value !== value) {
541
- throw {
542
- message: `Unexpected token '${token?.value}'. Expected ${type === 0 /* IDENT */ ? "an" : "a"} ${getTokenTypeWords(type)} instead.`,
543
- pos: token.pos
544
- };
545
- }
546
- return tokens[cursor++];
547
- }
548
- function parseForLoop() {
549
- const pos = tokens[cursor - 1].pos;
550
- const variable = expectOrThrow(0 /* IDENT */).value;
551
- let token;
552
- try {
553
- token = expectOrThrow(1 /* KEYWORD */, "in");
554
- } catch {
555
- token = expectOrThrow(1 /* KEYWORD */, "of");
556
- }
557
- const loopType = token.value === "in" ? 1 /* IN */ : 0 /* OF */;
558
- const iterable = parseTernaryExpr();
559
- return { type: 13 /* FOR */, loopType, iterable, variable, pos };
560
- }
561
- function parseIfExpression() {
562
- const condition = parseTernaryExpr();
563
- return { condition, pos: condition.pos, type: 14 /* IF */ };
564
- }
565
- function parseElseExpression() {
566
- const pos = tokens[cursor - 1].pos;
567
- try {
568
- expectOrThrow(1 /* KEYWORD */, "if");
569
- return { ...parseIfExpression(), type: 15 /* ELSE_IF */, pos };
570
- } catch {
571
- return { type: 16 /* ELSE */, pos };
572
- }
573
- }
574
- function extractFnArgs() {
575
- const args = [];
576
- const emptyArgs = tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === ")";
577
- if (emptyArgs) {
578
- return args;
579
- }
580
- args.push(parseTernaryExpr());
581
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "," && tokens[cursor]?.value !== ")") {
582
- cursor++;
583
- args.push(parseTernaryExpr());
584
- }
585
- return args;
586
- }
587
- function parsePrimaryExpr() {
588
- const token = tokens[cursor++];
589
- if (token?.type === 2 /* NUMBER */) {
590
- return { type: 5 /* NUMBER */, value: token.value, pos: token.pos };
591
- }
592
- if (token?.type === 3 /* STRING */) {
593
- return { type: 4 /* STRING */, value: token.value, pos: token.pos };
594
- }
595
- if (token?.type === 1 /* KEYWORD */) {
596
- if (token.value === "for" && cursor === 1) {
597
- return parseForLoop();
598
- }
599
- if (token.value === "true" || token.value === "false") {
600
- return {
601
- type: 10 /* BOOLEAN */,
602
- true: token.value === "true",
603
- pos: token.pos
604
- };
605
- }
606
- if (token.value === "undefined") {
607
- return { type: 11 /* UNDEFINED */, pos: token.pos };
608
- }
609
- if (token.value === "null") {
610
- return { type: 12 /* NULL */, pos: token.pos };
611
- }
612
- if (token.value === "end" && tokens.length === 1) {
613
- return { type: 17 /* END */, pos: token.pos };
614
- }
615
- if (token.value === "if" && cursor === 1) {
616
- return parseIfExpression();
617
- }
618
- if (token.value === "else" && cursor === 1) {
619
- return parseElseExpression();
620
- }
621
- }
622
- if (token?.type === 0 /* IDENT */) {
623
- return { type: 7 /* IDENT */, value: token.value, pos: token.pos };
624
- }
625
- if (token?.type === 4 /* OPERATOR */ && token.value === "(") {
626
- const expr = parseTernaryExpr();
627
- expectOrThrow(4 /* OPERATOR */, ")");
628
- return { type: 9 /* GROUP */, expr, pos: token.pos };
629
- }
630
- if (token?.type === 4 /* OPERATOR */ && unaryOperators.has(token.value)) {
631
- const operator = token.value;
632
- const expr = parseTernaryExpr();
633
- return { type: 2 /* UNARY */, operator, expr, pos: token.pos };
634
- }
635
- if (cursor > tokens.length) {
636
- throw {
637
- message: `Unexpected end of expression.`,
638
- pos: tokens[tokens.length - 1].pos
639
- };
640
- }
641
- throw {
642
- message: `Unexpected token '${token?.value}'.`,
643
- pos: token.pos
644
- };
645
- }
646
- function parsePropertyAccess() {
647
- let left = parsePrimaryExpr();
648
- while (tokens[cursor]) {
649
- const token = tokens[cursor];
650
- if (token?.type === 4 /* OPERATOR */ && token?.value === "(") {
651
- cursor++;
652
- if (!generatingNamespace && !config.allowFnCalls) {
653
- throw {
654
- message: "Function calls are not allowed.",
655
- pos: tokens[cursor - 1].pos
656
- };
657
- }
658
- const args = extractFnArgs();
659
- expectOrThrow(4 /* OPERATOR */, ")");
660
- left = {
661
- type: 3 /* CALL */,
662
- expr: left,
663
- args,
664
- pos: tokens[cursor - 1].pos
665
- };
666
- } else if (token?.type === 4 /* OPERATOR */ && token?.value === "?." && tokens[cursor + 1]?.type === 4 /* OPERATOR */ && tokens[cursor + 1]?.value === "(") {
667
- cursor++;
668
- cursor++;
669
- if (!generatingNamespace && !config.allowFnCalls) {
670
- throw {
671
- message: "Function calls are not allowed.",
672
- pos: tokens[cursor - 1].pos
673
- };
674
- }
675
- const args = extractFnArgs();
676
- expectOrThrow(4 /* OPERATOR */, ")");
677
- left = {
678
- type: 3 /* CALL */,
679
- expr: left,
680
- args,
681
- optional: true,
682
- pos: tokens[cursor - 1].pos
683
- };
684
- } else if (token?.type === 4 /* OPERATOR */ && propertyAccessOperators.has(token?.value)) {
685
- const isNamespace = token?.value === "::";
686
- const isBracketNotation = token?.value === "[";
687
- const isOptional = token?.value === "?.";
688
- cursor++;
689
- if (isNamespace && (tokens[cursor - 2]?.type !== 0 /* IDENT */ || tokens[cursor]?.type !== 0 /* IDENT */)) {
690
- throw {
691
- message: `Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${tokens[cursor - 2]?.value}::${tokens[cursor]?.value}' instead.`,
692
- pos: tokens[cursor]?.pos
693
- };
694
- }
695
- if (isNamespace) {
696
- generatingNamespace = true;
697
- const right = parsePrimaryExpr();
698
- left = {
699
- type: 6 /* NAMESPACE */,
700
- left,
701
- right,
702
- pos: tokens[cursor - 1].pos
703
- };
704
- } else if (isBracketNotation) {
705
- const right = parseTernaryExpr();
706
- expectOrThrow(4 /* OPERATOR */, "]");
707
- left = {
708
- type: 8 /* PROP_ACCESS */,
709
- right,
710
- left,
711
- bracketNotation: true,
712
- pos: tokens[cursor - 1].pos
713
- };
714
- } else if (isOptional) {
715
- if (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "[") {
716
- cursor++;
717
- const right = parseTernaryExpr();
718
- expectOrThrow(4 /* OPERATOR */, "]");
719
- left = {
720
- type: 8 /* PROP_ACCESS */,
721
- left,
722
- right,
723
- bracketNotation: true,
724
- optional: true,
725
- pos: tokens[cursor - 1].pos
726
- };
727
- } else {
728
- const right = parsePrimaryExpr();
729
- left = {
730
- type: 8 /* PROP_ACCESS */,
731
- left,
732
- right,
733
- optional: true,
734
- pos: tokens[cursor - 1].pos
735
- };
736
- }
737
- } else {
738
- const right = parsePrimaryExpr();
739
- left = {
740
- type: 8 /* PROP_ACCESS */,
741
- left,
742
- right,
743
- pos: tokens[cursor - 1].pos
744
- };
745
- }
746
- } else {
747
- break;
748
- }
749
- }
750
- generatingNamespace = false;
751
- return left;
752
- }
753
- function parseMultiplicativeExpr() {
754
- let left = parsePropertyAccess();
755
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && multiplicativeOperators.has(tokens[cursor]?.value)) {
756
- const operator = tokens[cursor++].value;
757
- const right = parsePropertyAccess();
758
- left = {
759
- type: 0 /* BINARY */,
760
- left,
761
- right,
762
- operator,
763
- pos: tokens[cursor - 1].pos
764
- };
765
- }
766
- return left;
767
- }
768
- function parseAdditiveExpr() {
769
- let left = parseMultiplicativeExpr();
770
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && additiveOperators.has(tokens[cursor]?.value)) {
771
- const operator = tokens[cursor++].value;
772
- const right = parseMultiplicativeExpr();
773
- left = {
774
- type: 0 /* BINARY */,
775
- left,
776
- right,
777
- operator,
778
- pos: tokens[cursor - 1].pos
779
- };
780
- }
781
- return left;
782
- }
783
- function parseBitwiseExpr() {
784
- let left = parseAdditiveExpr();
785
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && comparisonOperators.has(tokens[cursor]?.value)) {
786
- const operator = tokens[cursor++].value;
787
- const right = parseAdditiveExpr();
788
- left = {
789
- type: 0 /* BINARY */,
790
- left,
791
- right,
792
- operator,
793
- pos: tokens[cursor - 1].pos
794
- };
795
- }
796
- return left;
797
- }
798
- function parseComparisonExpr() {
799
- let left = parseBitwiseExpr();
800
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && comparisonOperators.has(tokens[cursor]?.value)) {
801
- const operator = tokens[cursor++].value;
802
- const right = parseBitwiseExpr();
803
- left = {
804
- type: 0 /* BINARY */,
805
- left,
806
- right,
807
- operator,
808
- pos: tokens[cursor - 1].pos
809
- };
810
- }
811
- return left;
812
- }
813
- function parseEqualityExpr() {
814
- let left = parseComparisonExpr();
815
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && equalityOperators.has(tokens[cursor]?.value)) {
816
- const operator = tokens[cursor++].value;
817
- const right = parseComparisonExpr();
818
- left = {
819
- type: 0 /* BINARY */,
820
- left,
821
- right,
822
- operator,
823
- pos: tokens[cursor - 1].pos
824
- };
825
- }
826
- return left;
827
- }
828
- function parseLogicalOrExpr() {
829
- let left = parseLogicalAndExpr();
830
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "||") {
831
- const operator = tokens[cursor++].value;
832
- const right = parseLogicalAndExpr();
833
- left = {
834
- type: 0 /* BINARY */,
835
- left,
836
- right,
837
- operator,
838
- pos: tokens[cursor - 1].pos
839
- };
840
- }
841
- return left;
842
- }
843
- function parseLogicalAndExpr() {
844
- let left = parseNullishCoalesceExpr();
845
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "&&") {
846
- const operator = tokens[cursor++].value;
847
- const right = parseNullishCoalesceExpr();
848
- left = {
849
- type: 0 /* BINARY */,
850
- left,
851
- right,
852
- operator,
853
- pos: tokens[cursor - 1].pos
854
- };
855
- }
856
- return left;
857
- }
858
- function parseNullishCoalesceExpr() {
859
- let left = parseEqualityExpr();
860
- while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "??") {
861
- const operator = tokens[cursor++].value;
862
- const right = parseEqualityExpr();
863
- left = {
864
- type: 0 /* BINARY */,
865
- left,
866
- right,
867
- operator,
868
- pos: tokens[cursor - 1].pos
869
- };
870
- }
871
- return left;
872
- }
873
- function parseTernaryExpr() {
874
- const condition = parseLogicalOrExpr();
875
- if (tokens[cursor]?.type !== 4 /* OPERATOR */ || tokens[cursor]?.value !== "?") {
876
- return condition;
877
- }
878
- cursor++;
879
- const left = parseTernaryExpr();
880
- expectOrThrow(4 /* OPERATOR */, ":");
881
- const right = parseTernaryExpr();
882
- return {
883
- type: 1 /* TERNARY */,
884
- left,
885
- right,
886
- condition,
887
- pos: tokens[cursor - 1].pos
888
- };
889
- }
890
- const ast = parseTernaryExpr();
891
- return ast;
892
- }
893
-
894
- // src/core/parse.ts
895
- function parse(templateBlock, { delimiters }) {
896
- const openingTagWithWhitespaceCtrl = `${delimiters.openingTag}${delimiters.whitespaceTrim}`;
897
- const closingTagWithWhitespaceCtrl = `${delimiters.whitespaceTrim}${delimiters.closingTag}`;
898
- const leftTrim = templateBlock.startsWith(openingTagWithWhitespaceCtrl);
899
- const rightTrim = templateBlock.endsWith(closingTagWithWhitespaceCtrl);
900
- const isComment = templateBlock.startsWith(
901
- leftTrim ? openingTagWithWhitespaceCtrl + delimiters.commentTag : delimiters.openingTag + delimiters.commentTag
902
- );
903
- if (isComment) {
904
- return { isComment, leftTrim, rightTrim };
905
- }
906
- const inner = templateBlock.slice(
907
- leftTrim ? openingTagWithWhitespaceCtrl.length : delimiters.openingTag.length,
908
- templateBlock.length - (rightTrim ? closingTagWithWhitespaceCtrl.length : delimiters.closingTag.length)
909
- );
910
- const trimmed = inner.trim();
911
- const isBlock = trimmed.startsWith("for") || trimmed.startsWith("if") || trimmed.startsWith("else");
912
- const requiresBlockClose = trimmed.startsWith("for") || trimmed.startsWith("if");
913
- const isBlockEnd = trimmed === "end";
914
- const hasContext = trimmed.startsWith("for");
915
- return {
916
- leftTrim,
917
- rightTrim,
918
- inner,
919
- isBlock,
920
- isBlockEnd,
921
- hasContext,
922
- requiresBlockClose
923
- };
924
- }
925
-
926
- // src/core/tokenize.ts
927
- function tokenize(expr) {
928
- let cursor = 0, char = "";
929
- const tokens = [];
930
- function accumulateKeywordOrIdentifier() {
931
- let buffer = "";
932
- if (/[a-zA-Z$_]/.test(char)) {
933
- let j = cursor;
934
- while (/[a-zA-Z$_0-9]/.test(expr[j]) && j < expr.length) {
935
- buffer += expr[j];
936
- j++;
937
- }
938
- tokens.push({
939
- type: keywords.has(buffer) ? 1 /* KEYWORD */ : 0 /* IDENT */,
940
- value: buffer,
941
- pos: cursor
942
- });
943
- cursor = j;
944
- char = expr[cursor];
945
- }
946
- }
947
- function accumulateStr() {
948
- let buffer = "";
949
- if (char === '"' || char === "'" || char === "`") {
950
- let j = cursor + 1;
951
- while (expr[j] !== char && j < expr.length) {
952
- buffer += expr[j];
953
- j++;
954
- }
955
- if (j > expr.length) {
956
- throw { pos: cursor, message: `Found string without closing quote.` };
957
- }
958
- tokens.push({ type: 3 /* STRING */, value: buffer, pos: cursor });
959
- cursor = j;
960
- }
961
- }
962
- function accumulateNumber() {
963
- if (/[0-9]/.test(char)) {
964
- let j = cursor, buffer = "";
965
- while (/[0-9.oxe]/.test(expr[j]) && j < expr.length) {
966
- buffer += expr[j];
967
- j++;
968
- }
969
- const numVal = Number(buffer);
970
- const isNan = Number.isNaN(numVal);
971
- if (isNan) {
972
- throw { pos: cursor, message: "Found invalid number literal." };
973
- }
974
- tokens.push({ type: 2 /* NUMBER */, value: `${numVal}`, pos: cursor });
975
- cursor = j - 1;
976
- char = expr[cursor];
977
- }
978
- }
979
- function accumulateOperator() {
980
- const op = `${char}${expr[cursor + 1]}`;
981
- if (operators.has(op)) {
982
- tokens.push({ type: 4 /* OPERATOR */, value: op, pos: cursor });
983
- cursor++;
984
- return;
985
- }
986
- if (operators.has(char)) {
987
- tokens.push({ type: 4 /* OPERATOR */, value: char, pos: cursor });
988
- return;
989
- }
990
- }
991
- while (cursor < expr.length) {
992
- char = expr[cursor];
993
- accumulateNumber();
994
- accumulateKeywordOrIdentifier();
995
- accumulateStr();
996
- accumulateOperator();
997
- if (!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(char) && !operators.has(char) && !operators.has(expr[cursor - 1] + char)) {
998
- throw {
999
- message: `Unexpected token '${char}' in expression.`,
1000
- pos: cursor
1001
- };
1002
- }
1003
- cursor++;
1004
- }
1005
- return tokens;
1006
- }
1007
-
1008
- // src/core/compile.ts
1009
- function compile(src, config, meta) {
1010
- const scope = [];
1011
- const blockOpeningStack = [];
1012
- const {
1013
- delimiters,
1014
- keepOpeningTagEscapeDelimiter,
1015
- allowFnCalls,
1016
- allowedProps,
1017
- forbiddenProps,
1018
- autoEscape
1019
- } = config;
1020
- let trimNext = false, cursor = 0, body = `let acc="";`;
1021
- while (cursor < src.length) {
1022
- let isEscaped2 = function() {
1023
- let j = templateOpenTagIdx, count = 0;
1024
- while (j >= delimiters.openingTagEscape.length && src.slice(j - delimiters.openingTagEscape.length, j) === delimiters.openingTagEscape) {
1025
- count++;
1026
- j -= delimiters.openingTagEscape.length;
1027
- }
1028
- return count % 2 === 1;
1029
- };
1030
- var isEscaped = isEscaped2;
1031
- const templateOpenTagIdx = src.indexOf(delimiters.openingTag, cursor);
1032
- if (templateOpenTagIdx === -1) {
1033
- let lastChunk = src.slice(cursor);
1034
- if (trimNext) lastChunk = lastChunk.trimStart();
1035
- if (lastChunk) body += `acc+=\`${escapeRawText(lastChunk)}\`;`;
1036
- break;
1037
- }
1038
- if (isEscaped2()) {
1039
- let escapedChunk = src.slice(
1040
- cursor,
1041
- keepOpeningTagEscapeDelimiter ? templateOpenTagIdx + delimiters.openingTagEscape.length + 1 : templateOpenTagIdx - delimiters.openingTag.length + 1
1042
- );
1043
- if (trimNext) {
1044
- escapedChunk = escapedChunk.trimStart();
1045
- trimNext = false;
1046
- }
1047
- body += `acc+=\`${escapeRawText(escapedChunk)}\`;`;
1048
- if (!keepOpeningTagEscapeDelimiter)
1049
- body += `acc+=\`${delimiters.openingTag}\`;`;
1050
- cursor = templateOpenTagIdx + delimiters.openingTag.length;
1051
- continue;
1052
- }
1053
- const templateEndTagIdx = src.indexOf(
1054
- delimiters.closingTag,
1055
- templateOpenTagIdx
1056
- );
1057
- if (templateEndTagIdx === -1) {
1058
- const { line, lineIndex } = getLineAndColumnNumbers(
1059
- src,
1060
- templateOpenTagIdx
1061
- );
1062
- const { line: lineText, pos } = getLineSnapshot(
1063
- src,
1064
- lineIndex,
1065
- templateOpenTagIdx
1066
- );
1067
- throw new MutorCompilerError(
1068
- "No closing tag found.",
1069
- line,
1070
- lineText,
1071
- pos,
1072
- meta.path
1073
- );
1074
- }
1075
- const template = src.slice(
1076
- templateOpenTagIdx,
1077
- templateEndTagIdx + delimiters.closingTag.length
1078
- );
1079
- const {
1080
- inner,
1081
- leftTrim,
1082
- rightTrim,
1083
- isBlock,
1084
- isBlockEnd,
1085
- hasContext,
1086
- requiresBlockClose,
1087
- isComment
1088
- } = parse(template, { delimiters });
1089
- let rawText = src.slice(cursor, templateOpenTagIdx);
1090
- if (rawText) {
1091
- if (trimNext) {
1092
- rawText = rawText.trimStart();
1093
- }
1094
- if (leftTrim) {
1095
- rawText = rawText.trimEnd();
1096
- }
1097
- if (rawText) {
1098
- body += `acc+=\`${escapeRawText(rawText)}\`;`;
1099
- }
1100
- }
1101
- trimNext = false;
1102
- cursor = templateEndTagIdx + delimiters.closingTag.length;
1103
- try {
1104
- if (!isComment) {
1105
- const tokens = tokenize(inner);
1106
- const ast = generateAst(tokens, { allowFnCalls });
1107
- if (isBlock && requiresBlockClose && hasContext) {
1108
- scope.push(ast.variable);
1109
- blockOpeningStack.push({
1110
- type: 0 /* LOOP */,
1111
- pos: templateOpenTagIdx
1112
- });
1113
- } else if (isBlock && requiresBlockClose && !hasContext) {
1114
- blockOpeningStack.push({
1115
- type: 1 /* NON_LOOP */,
1116
- pos: templateOpenTagIdx
1117
- });
1118
- }
1119
- if (isBlockEnd) {
1120
- const lastBlockOpened = blockOpeningStack.pop();
1121
- if (lastBlockOpened?.type === 0 /* LOOP */) scope.pop();
1122
- if (lastBlockOpened === void 0)
1123
- throw {
1124
- message: "Unexpected end of block",
1125
- pos: templateOpenTagIdx
1126
- };
1127
- }
1128
- const js = build(ast, { allowedProps, forbiddenProps, scope });
1129
- if (isBlock || isBlockEnd) {
1130
- body += js;
1131
- } else {
1132
- body += autoEscape && !js.startsWith("namespaces.Mutor.include") ? `acc+=escapeFn(${js});` : `acc+=${js};`;
1133
- }
1134
- }
1135
- if (rightTrim) trimNext = true;
1136
- } catch (e) {
1137
- const { message, pos: relPos } = e;
1138
- const { line, lineIndex } = getLineAndColumnNumbers(
1139
- src,
1140
- templateOpenTagIdx
1141
- );
1142
- const { line: lineText, pos } = getLineSnapshot(
1143
- src,
1144
- lineIndex,
1145
- templateOpenTagIdx
1146
- );
1147
- throw new MutorCompilerError(
1148
- message,
1149
- line,
1150
- lineText,
1151
- pos + relPos + (leftTrim ? delimiters.openingTag.length + delimiters.whitespaceTrim.length : delimiters.openingTag.length),
1152
- meta.path
1153
- );
1154
- }
1155
- }
1156
- if (blockOpeningStack.length) {
1157
- const lastPos = blockOpeningStack.pop()?.pos;
1158
- const { line, lineIndex } = getLineAndColumnNumbers(src, lastPos);
1159
- const { line: lineText, pos } = getLineSnapshot(src, lineIndex, lastPos);
1160
- throw new MutorCompilerError(
1161
- "Unclosed block detected.",
1162
- line,
1163
- lineText,
1164
- pos + delimiters.openingTag.length,
1165
- meta.path
1166
- );
1167
- }
1168
- body += `return acc;`;
1169
- return new Function(
1170
- "ctx",
1171
- "namespaces",
1172
- "allowedProps",
1173
- "forbiddenProps",
1174
- "escapeFn",
1175
- "validateComputedProps",
1176
- body
1177
- );
1178
- }
1179
-
1180
- // src/core/mutor.ts
1181
- var Mutor = class {
1182
- constructor(config = {}) {
1183
- this.__currentRenderedPath = "";
1184
- this.__includeStack = /* @__PURE__ */ new Set();
1185
- this.__cacheSize = 0;
1186
- this.__config = { ...defaultConfig };
1187
- this.__compiledTemplatesMap = /* @__PURE__ */ new Map();
1188
- this.__currentContext = null;
1189
- this.__namespaces = {
1190
- ...namespaces,
1191
- Mutor: {
1192
- include: (path, ctx) => {
1193
- if (this.__includeStack.has(path)) {
1194
- throw new MutorError(
1195
- `Circular include detected:
1196
- ${Array.from(this.__includeStack).join("\n")}
1197
- ${path}`
1198
- );
1199
- }
1200
- try {
1201
- this.__includeStack.add(path);
1202
- return this.renderComponent(path, ctx ?? this.__currentContext);
1203
- } finally {
1204
- this.__includeStack.delete(path);
1205
- }
1206
- }
1207
- }
1208
- };
1209
- this.addConfig(config);
1210
- Object.defineProperty(this.__namespaces.Mutor, "$$context", {
1211
- get: () => {
1212
- return this.__currentContext;
1213
- }
1214
- });
1215
- }
1216
- addConfig(conf) {
1217
- const {
1218
- autoEscape,
1219
- delimiters: overrideDelimeters,
1220
- allowedProps,
1221
- forbiddenProps,
1222
- keepOpeningTagEscapeDelimiter,
1223
- allowFnCalls,
1224
- cache,
1225
- build: build2
1226
- } = conf;
1227
- this.__config = {
1228
- build: {
1229
- include: /* @__PURE__ */ new Set([...build2?.include || defaultConfig.build.include]),
1230
- exclude: /* @__PURE__ */ new Set([
1231
- ...defaultConfig.build.exclude,
1232
- ...build2?.exclude || []
1233
- ])
1234
- },
1235
- autoEscape: autoEscape === true ? true : autoEscape !== false,
1236
- allowedProps: allowedProps || defaultConfig.allowedProps,
1237
- allowFnCalls: !!allowFnCalls,
1238
- cache: { ...defaultConfig.cache, ...cache || {} },
1239
- forbiddenProps: /* @__PURE__ */ new Set([
1240
- ...defaultConfig.forbiddenProps,
1241
- ...forbiddenProps || []
1242
- ]),
1243
- keepOpeningTagEscapeDelimiter: keepOpeningTagEscapeDelimiter === true ? true : keepOpeningTagEscapeDelimiter !== false,
1244
- delimiters: {
1245
- ...defaultConfig.delimiters,
1246
- ...overrideDelimeters || {}
1247
- }
1248
- };
1249
- return this.__config;
1250
- }
1251
- restoreDefaultConfig() {
1252
- this.__config = { ...defaultConfig };
1253
- }
1254
- compile(template) {
1255
- return compile(template, this.__config, {
1256
- path: this.__currentRenderedPath || "anonymous"
1257
- });
1258
- }
1259
- render(template, context) {
1260
- const prevContext = this.__currentContext;
1261
- if (prevContext !== context) {
1262
- this.__currentContext = context;
1263
- }
1264
- const result = this.compile(template)(
1265
- validateContext(context),
1266
- this.__namespaces,
1267
- this.__config.allowedProps,
1268
- this.__config.forbiddenProps,
1269
- escapeFn,
1270
- validateComputedProp
1271
- );
1272
- this.__currentContext = prevContext;
1273
- return result;
1274
- }
1275
- renderComponent(identifier, context) {
1276
- if (!this.__compiledTemplatesMap.has(identifier)) {
1277
- throw new MutorError(
1278
- `No template exists with the identifier '${identifier}'`
1279
- );
1280
- }
1281
- const prevRenderComponentIdentifier = this.__currentRenderedPath;
1282
- const prevContext = this.__currentContext;
1283
- const compiled = this.__compiledTemplatesMap.get(identifier);
1284
- this.__currentContext = context;
1285
- this.__currentRenderedPath = identifier;
1286
- const result = compiled.fn(
1287
- validateContext(context),
1288
- this.__namespaces,
1289
- this.__config.allowedProps,
1290
- this.__config.forbiddenProps,
1291
- escapeFn,
1292
- validateComputedProp
1293
- );
1294
- this.__currentContext = prevContext;
1295
- this.__currentRenderedPath = prevRenderComponentIdentifier;
1296
- return result;
1297
- }
1298
- registerComponent(identifier, template) {
1299
- const templateSize = template.length * 2 + 500;
1300
- if (this.__cacheSize + templateSize > this.__config.cache.maxSize) {
1301
- if (!this.createEntrySpaceForTemplate(templateSize)) {
1302
- throw new MutorError(
1303
- `The template for the component '${identifier}' is too large. Consider increasing 'cache.maxSize' in the config`
1304
- );
1305
- }
1306
- }
1307
- this.__cacheSize += template.length * 2 + 500;
1308
- this.__compiledTemplatesMap.set(identifier, {
1309
- fn: this.compile(template),
1310
- size: templateSize
1311
- });
1312
- }
1313
- reset() {
1314
- this.__config = { ...defaultConfig };
1315
- this.__compiledTemplatesMap.clear();
1316
- this.__currentContext = null;
1317
- this.__cacheSize = 0;
1318
- }
1319
- createEntrySpaceForTemplate(targetSize) {
1320
- if (this.__cacheSize + targetSize < this.__config.cache.maxSize) {
1321
- return true;
1322
- }
1323
- if (targetSize > this.__config.cache.maxSize) {
1324
- return false;
1325
- }
1326
- const firstEntry = this.__compiledTemplatesMap.entries().next().value;
1327
- if (firstEntry) {
1328
- const [oldestKey, oldestData] = firstEntry;
1329
- this.__compiledTemplatesMap.delete(oldestKey);
1330
- this.__cacheSize -= oldestData.size;
1331
- }
1332
- return this.createEntrySpaceForTemplate(targetSize);
1333
- }
1334
- getDiagnostics() {
1335
- const maxSize = this.__config.cache.maxSize;
1336
- return {
1337
- bytesUsed: this.__cacheSize,
1338
- bytesMax: maxSize,
1339
- readableUsed: `${(this.__cacheSize / 1024 / 1024).toFixed(2)} MB`,
1340
- readableMax: `${(maxSize / 1024 / 1024).toFixed(2)} MB`,
1341
- totalEntries: this.__compiledTemplatesMap.size,
1342
- percentFull: maxSize > 0 ? Math.min(100, Math.round(this.__cacheSize / maxSize * 100)) : 0,
1343
- avgTemplateSize: this.__compiledTemplatesMap.size > 0 ? Math.round(this.__cacheSize / this.__compiledTemplatesMap.size) : 0
1344
- };
1345
- }
1346
- };
1347
-
1348
- // src/index.ts
1349
- var index_default = Mutor;
1
+ "use strict";var J=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(e,n)=>{for(var t in n)J(e,t,{get:n[t],enumerable:!0})},Ee=(e,n,t,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of de(n))!ge.call(e,o)&&o!==t&&J(e,o,{get:()=>n[o],enumerable:!(a=he(n,o))||a.enumerable});return e};var Oe=e=>Ee(J({},"__esModule",{value:!0}),e);var be={};me(be,{default:()=>_e});module.exports=Oe(be);function q(e,n){return`${" ".repeat(e+n)}^`}var g=class e extends Error{constructor(t){super(t);this.name="MutorError";Object.setPrototypeOf(this,e.prototype)}},v=class e extends g{constructor(t,a,o,p,u){let y=a.toString().length+2,i=`${t}
2
+
3
+ `;i+=`at ${u}:${a}:${p+1}
4
+ `,a>1&&(i+=`${(a-1).toString().padStart(y-2)} | ...
5
+ `),i+=`${a} | ${o}
6
+ `,i+=q(p,y+1);super(i);this.name="MutorCompilerError";Object.setPrototypeOf(this,e.prototype)}};var te=new Set(["for","if","else","true","false","null","undefined","end","in","of"]),F=new Set(["::","||","??","&&","**","^","|","&","!","-","%","+","*","/",">","<",">=","<=","==","!=",">>","<<",".","?.","(",")","[","]",",",":","?"]);var re=new Set(["==","!="]),Z=new Set([">","<",">=","<="]);var ne=new Set(["+","-"]),oe=new Set(["*","/","%"]),se=new Set([".","?.","[","::"]),ie=new Set(["-","+","!"]),ae={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},x={build:{include:new Set([".html",".txt"]),exclude:new Set(["node_modules",".git"])},autoEscape:!0,allowedProps:new Set,forbiddenProps:new Set(["__proto__","constructor","prototype"]),allowFnCalls:!1,delimiters:{closingTag:"}}",openingTag:"{{",openingTagEscape:"\\",whitespaceTrim:"~",commentTag:"#"},keepOpeningTagEscapeDelimiter:!1,cache:{active:!0,maxSize:50*1024*1024}},ce={JSON:{stringify(e){try{return JSON.stringify(e)}catch{throw new g("JSON.stringify failed: invalid value")}},parse(e){if(typeof e!="string")throw new g("JSON.parse expects a string");try{return JSON.parse(e)}catch{throw new g("JSON.parse failed: invalid JSON string")}}},Object:{keys(e){if(!e||typeof e!="object")throw new g("Object.keys expects an object");return Object.keys(e)},values(e){if(!e||typeof e!="object")throw new g("Object.values expects an object");return Object.values(e)},entries(e){if(!e||typeof e!="object")throw new g("Object.entries expects an object");return Object.entries(e)},hasOwn(e,n){if(!e||typeof e!="object")throw new g("Object.hasOwn expects an object");return Object.hasOwn(e,n)},freeze(e){if(!e||typeof e!="object")throw new g("Object.freeze expects an object");return Object.freeze(e)},seal(e){if(!e||typeof e!="object")throw new g("Object.seal expects an object");return Object.seal(e)},fromEntries(e){if(!Array.isArray(e))throw new g("Object.fromEntries expects an array");return Object.fromEntries(e)}},Array:{isArray(e){return Array.isArray(e)},from(e){return Array.from(e)}},Number:{isFinite(e){return Number.isFinite(e)},isNaN(e){return Number.isNaN(e)},parseInt(e,n=10){return Number.parseInt(e,n)},parseFloat(e){return Number.parseFloat(e)}},String:{fromCharCode(...e){return String.fromCharCode(...e)}},Math:{abs(e){return Math.abs(e)},floor(e){return Math.floor(e)},ceil(e){return Math.ceil(e)},round(e){return Math.round(e)},max(...e){return Math.max(...e)},min(...e){return Math.min(...e)},random(){return Math.random()}},Date:{now(){return Date.now()},parse(e){if(typeof e!="string")throw new g("Date.parse expects a string");return Date.parse(e)}},Boolean:{valueOf(e){return!!e}}};function Y(e){return typeof e!="string"?e:/[&<>"']/.test(e)?e.replace(/[&<>"']/g,n=>ae[n]):e}function G(e,n,t){if(t.has(e)&&!n.has(e))throw new g(`Forbidden property access. Access to this computed property "${e}" is forbidden.`);return e}var D="object",pe=Symbol("__mutor_safe_context");function K(e){if(!e||typeof e!==D||pe in e)return e;let n=new WeakSet;function t(o,p=""){if(!o||typeof o!==D||n.has(o))return o;n.add(o);let u=Object.getPrototypeOf(o);if(u&&u!==Object.prototype&&u!==Array.prototype)throw new g(`Unsafe prototype detected at ${p||"root"}`);if(Array.isArray(o)){for(let i=0;i<o.length;i++)o[i]=t(o[i],`${p}[${i}]`);return o}if(o instanceof Map){for(let[i,f]of o.entries())typeof i===D&&t(i,`${p}.mapKey`),o.set(i,t(f,`${p}.mapValue`));return o}if(o instanceof Set){let i=new Set;for(let f of o.values())i.add(t(f,p));o.clear();for(let f of i)o.add(f);return o}let y=Object.getOwnPropertyDescriptors(o);for(let i of Object.keys(y)){let f=y[i];if(f.get||f.set)throw new g(`Getter/setter not allowed: ${p}.${i}`);let d=o[i];d&&typeof d===D&&(o[i]=t(d,`${p}.${i}`))}return o}let a=t(e);return a&&typeof a===D&&Object.defineProperty(a,pe,{value:!0,enumerable:!1,writable:!1,configurable:!1}),a}function T(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$/g,"\\$")}function j(e,n){let a=e.slice(0,n).split(`
7
+ `).length,o=e.lastIndexOf(`
8
+ `,n-1)+1;return[a,o]}function L(e,n){let t=e.indexOf(`
9
+ `,n);return e.slice(n,t===-1?void 0:t).replaceAll(" "," ")}function M(e,n){let{scope:t,forbiddenProps:a,allowedProps:o}=n;function p(s){return t.includes(s)?s:`ctx.${s}`}function u(s){switch(s.type){case 17:return"}";case 5:return s.value;case 4:return`\`${/\$\\/.test(s.value)?T(s.value):s.value}\``;case 10:return s.true?"true":"false";case 12:return"null";case 11:return"undefined";case 7:return p(s.value);case 9:return`(${u(s.expr)})`;case 2:return`${s.operator}${u(s.expr)}`;case 0:return`${u(s.left)} ${s.operator} ${u(s.right)}`;case 1:return`${u(s.condition)} ? ${u(s.left)} : ${u(s.right)}`;case 8:return i(s);case 3:return f(s);case 6:return y(s);case 13:return d(s);case 16:return"} else {";case 14:return m(s);case 15:return E(s);default:throw new g(`Unsupported expression type: ${s.type}`)}}function y(s){if(s.left.type!==7)throw{message:"Invalid usage of namespace operator.",pos:s.pos};return`namespaces.${s.left.value}.${s.right.value}`}function i(s){let w=u(s.left);if(s.bracketNotation){let h=u(s.right),_=s.optional?"?.":"";return s.right.type===4||s.right.type===5?`${w}${_}[${h}]`:`${w}${_}[validateComputedProps(${h}, allowedProps, forbiddenProps)]`}else{let h=s.right.value,_=s.optional?"?.":".";if(a.has(h)&&!o.has(h))throw{message:"Forbidden property access.",pos:s.right.pos};return`${w}${_}${h}`}}function f(s){let w=u(s.expr),h=s.optional?"?.":"",_=s.args.map(R=>u(R)).join(", ");return`${w}${h}(${_})`}function d(s){let{iterable:w,loopType:h,variable:_}=s;return`for(const ${_} ${h===1?"in":"of"} ${M(w,n)}){`}function m(s){let{condition:w}=s;return`if(${M(w,n)}){`}function E(s){let{condition:w}=s;return`}else if(${M(w,n)}){`}return u(e)}function U(e){switch(e){case 0:return"identifier";case 1:return"keyword";case 2:return"number";case 4:return"operator";case 3:return"string"}}function V(e,n){let t=0,a=!1;function o(r,c){let l=e[t],P=e[e.length-1];if(!l)throw{message:`Unexpected end of expression. Expected ${c?`'${c}'`:`${r===0?"an":"a"} ${U(r)}`}.`,pos:P.pos+P.value.length-1};if(l.type!==r)throw{message:`Unexpected token type. Expected ${c?`'${c}'`:U(r)} but got ${U(l.type)} instead.`,pos:l.pos};if(c!==void 0&&l.value!==c)throw{message:`Unexpected token '${l?.value}'. Expected ${r===0?"an":"a"} ${U(r)} instead.`,pos:l.pos};return e[t++]}function p(){let r=e[t-1].pos,c=o(0).value,l;try{l=o(1,"in")}catch{l=o(1,"of")}let P=l.value==="in"?1:0,I=b();return{type:13,loopType:P,iterable:I,variable:c,pos:r}}function u(){let r=b();return{condition:r,pos:r.pos,type:14}}function y(){let r=e[t-1].pos;try{return o(1,"if"),{...u(),type:15,pos:r}}catch{return{type:16,pos:r}}}function i(){let r=[];if(e[t]?.type===4&&e[t]?.value===")")return r;for(r.push(b());e[t]?.type===4&&e[t]?.value===","&&e[t]?.value!==")";)t++,r.push(b());return r}function f(){let r=e[t++];if(r?.type===2)return{type:5,value:r.value,pos:r.pos};if(r?.type===3)return{type:4,value:r.value,pos:r.pos};if(r?.type===1){if(r.value==="for"&&t===1)return p();if(r.value==="true"||r.value==="false")return{type:10,true:r.value==="true",pos:r.pos};if(r.value==="undefined")return{type:11,pos:r.pos};if(r.value==="null")return{type:12,pos:r.pos};if(r.value==="end"&&e.length===1)return{type:17,pos:r.pos};if(r.value==="if"&&t===1)return u();if(r.value==="else"&&t===1)return y()}if(r?.type===0)return{type:7,value:r.value,pos:r.pos};if(r?.type===4&&r.value==="("){let c=b();return o(4,")"),{type:9,expr:c,pos:r.pos}}if(r?.type===4&&ie.has(r.value)){let c=r.value,l=b();return{type:2,operator:c,expr:l,pos:r.pos}}throw t>e.length?{message:"Unexpected end of expression.",pos:e[e.length-1].pos}:{message:`Unexpected token '${r?.value}'.`,pos:r.pos}}function d(){let r=f();for(;e[t];){let c=e[t];if(c?.type===4&&c?.value==="("){if(t++,!a&&!n.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let l=i();o(4,")"),r={type:3,expr:r,args:l,pos:e[t-1].pos}}else if(c?.type===4&&c?.value==="?."&&e[t+1]?.type===4&&e[t+1]?.value==="("){if(t++,t++,!a&&!n.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let l=i();o(4,")"),r={type:3,expr:r,args:l,optional:!0,pos:e[t-1].pos}}else if(c?.type===4&&se.has(c?.value)){let l=c?.value==="::",P=c?.value==="[",I=c?.value==="?.";if(t++,l&&(e[t-2]?.type!==0||e[t]?.type!==0))throw{message:`Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${e[t-2]?.value}::${e[t]?.value}' instead.`,pos:e[t]?.pos};if(l){a=!0;let N=f();r={type:6,left:r,right:N,pos:e[t-1].pos}}else if(P){let N=b();o(4,"]"),r={type:8,right:N,left:r,bracketNotation:!0,pos:e[t-1].pos}}else if(I)if(e[t]?.type===4&&e[t]?.value==="["){t++;let N=b();o(4,"]"),r={type:8,left:r,right:N,bracketNotation:!0,optional:!0,pos:e[t-1].pos}}else{let N=f();r={type:8,left:r,right:N,optional:!0,pos:e[t-1].pos}}else{let N=f();r={type:8,left:r,right:N,pos:e[t-1].pos}}}else break}return a=!1,r}function m(){let r=d();for(;e[t]?.type===4&&oe.has(e[t]?.value);){let c=e[t++].value,l=d();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function E(){let r=m();for(;e[t]?.type===4&&ne.has(e[t]?.value);){let c=e[t++].value,l=m();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function s(){let r=E();for(;e[t]?.type===4&&Z.has(e[t]?.value);){let c=e[t++].value,l=E();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function w(){let r=s();for(;e[t]?.type===4&&Z.has(e[t]?.value);){let c=e[t++].value,l=s();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function h(){let r=w();for(;e[t]?.type===4&&re.has(e[t]?.value);){let c=e[t++].value,l=w();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function _(){let r=R();for(;e[t]?.type===4&&e[t]?.value==="||";){let c=e[t++].value,l=R();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function R(){let r=$();for(;e[t]?.type===4&&e[t]?.value==="&&";){let c=e[t++].value,l=$();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function $(){let r=h();for(;e[t]?.type===4&&e[t]?.value==="??";){let c=e[t++].value,l=h();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function b(){let r=_();if(e[t]?.type!==4||e[t]?.value!=="?")return r;t++;let c=b();o(4,":");let l=b();return{type:1,left:c,right:l,condition:r,pos:e[t-1].pos}}let z=b();if(t!==e.length)throw{pos:e[t].pos,message:`Unexpected end of expression.
10
+ Expected end of expression but found "${e[t].value}".`};return z}function H(e,{delimiters:n}){let t=`${n.openingTag}${n.whitespaceTrim}`,a=`${n.whitespaceTrim}${n.closingTag}`,o=e.startsWith(t),p=e.endsWith(a),u=e.startsWith(o?t+n.commentTag:n.openingTag+n.commentTag);if(u)return{isComment:u,leftTrim:o,rightTrim:p};let y=e.slice(o?t.length:n.openingTag.length,e.length-(p?a.length:n.closingTag.length)),i=y.trim(),f=i.startsWith("for")||i.startsWith("if")||i.startsWith("else"),d=i.startsWith("for")||i.startsWith("if"),m=i==="end",E=i.startsWith("for");return{leftTrim:o,rightTrim:p,inner:y,isBlock:f,isBlockEnd:m,hasContext:E,requiresBlockClose:d}}function Q(e){let n=0,t="",a=[];function o(){let i="";if(/[a-zA-Z$_]/.test(t)){let f=n;for(;/[a-zA-Z$_0-9]/.test(e[f])&&f<e.length;)i+=e[f],f++;a.push({type:te.has(i)?1:0,value:i,pos:n}),n=f,t=e[n]}}function p(){if(t!=='"'&&t!=="'"&&t!=="`")return!1;let i=t,f=n,d=n+1,m="";for(;d<e.length;){let E=e[d];if(E==="\\"){if(d+1>=e.length)throw{pos:d,message:"Unexpected end of string after escape character."};m+=E,m+=e[d+1],d+=2;continue}if(E===i)break;m+=E,d++}if(d>=e.length||e[d]!==i)throw{pos:f,message:`String literal missing closing ${i}.`};return a.push({type:3,value:m,pos:f}),n=d+1,!0}function u(){if(/[0-9]/.test(t)){let i=n,f="";for(;/[0-9.oxe]/.test(e[i])&&i<e.length;)f+=e[i],i++;let d=Number(f);if(Number.isNaN(d))throw{pos:n,message:"Found invalid number literal."};a.push({type:2,value:`${d}`,pos:n}),n=i-1,t=e[n]}}function y(){let i=`${t}${e[n+1]}`;if(F.has(i)){a.push({type:4,value:i,pos:n}),n++;return}if(F.has(t)){a.push({type:4,value:t,pos:n});return}}for(;n<e.length;){if(t=e[n],u(),o(),p(),y(),!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(t)&&!F.has(t)&&!F.has(e[n-1]+t))throw{message:`Unexpected token '${t}' in expression.`,pos:n};n++}return a}function X(e,n,t){let a=[],o=[],{delimiters:p,keepOpeningTagEscapeDelimiter:u,allowFnCalls:y,allowedProps:i,forbiddenProps:f,autoEscape:d}=n,m=!1,E=0,s='let acc="";';for(;E<e.length;){let _=function(){let O=h,S=0;for(;O>=p.openingTagEscape.length&&e.slice(O-p.openingTagEscape.length,O)===p.openingTagEscape;)S++,O-=p.openingTagEscape.length;return S%2===1};var w=_;let h=e.indexOf(p.openingTag,E);if(h===-1){let O=e.slice(E);m&&(O=O.trimStart()),O&&(s+=`acc+=\`${T(O)}\`;`);break}if(_()){let O=e.slice(E,u?h+p.openingTagEscape.length+1:h-p.openingTag.length+1);m&&(O=O.trimStart(),m=!1),s+=`acc+=\`${T(O)}\`;`,u||(s+=`acc+=\`${p.openingTag}\`;`),E=h+p.openingTag.length;continue}let R=e.indexOf(p.closingTag,h);if(R===-1){let[O,S]=j(e,h),A=L(e,S);throw new v("No closing tag found.",O,A,h,t.path)}let $=e.slice(h,R+p.closingTag.length),{inner:b,leftTrim:z,rightTrim:r,isBlock:c,isBlockEnd:l,hasContext:P,requiresBlockClose:I,isComment:N}=H($,{delimiters:p}),C=e.slice(E,h);C&&(m&&(C=C.trimStart()),z&&(C=C.trimEnd()),C&&(s+=`acc+=\`${T(C)}\`;`)),m=!1,E=R+p.closingTag.length;try{if(!N){let O=Q(b),S=V(O,{allowFnCalls:y});if(c&&I&&P?(a.push(S.variable),o.push({type:0,pos:h})):c&&I&&!P&&o.push({type:1,pos:h}),l){let W=o.pop();if(W?.type===0&&a.pop(),W===void 0)throw{message:"Unexpected end of block",pos:h}}let A=M(S,{allowedProps:i,forbiddenProps:f,scope:a});c||l?s+=A:s+=d&&!A.startsWith("namespaces.Mutor.include")?`acc+=escapeFn(${A});`:`acc+=${A};`}r&&(m=!0)}catch(O){let{message:S,pos:A}=O,W=z?p.whitespaceTrim.length+p.openingTag.length:p.openingTag.length,k=h+A+W,[ue,ee]=j(e,k),fe=L(e,ee);throw new v(S,ue,fe,k-ee,t.path)}}if(o.length){let h=o.pop()?.pos,[_,R]=j(e,h),$=L(e,R);throw new v("Unclosed block detected.",_,$,h-R,t.path)}return s+="return acc;",new Function("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",s)}var B=class{constructor(n={}){this.__currentRenderedPath="";this.__includeStack=new Set;this.__cacheSize=0;this.__config={...x};this.__compiledTemplatesMap=new Map;this.__currentContext=null;this.__namespaces={...ce,Mutor:{include:(n,t)=>{if(this.__includeStack.has(n))throw new g(`Circular include detected:
11
+ ${Array.from(this.__includeStack).join(`
12
+ `)}
13
+ ${n}`);try{return this.__includeStack.add(n),this.renderComponent(n,t??this.__currentContext)}finally{this.__includeStack.delete(n)}}}};this.addConfig(n),Object.defineProperty(this.__namespaces.Mutor,"$$context",{get:()=>this.__currentContext})}addConfig(n){let{autoEscape:t,delimiters:a,allowedProps:o,forbiddenProps:p,keepOpeningTagEscapeDelimiter:u,allowFnCalls:y,cache:i,build:f}=n;return this.__config={build:{include:new Set([...f?.include||x.build.include]),exclude:new Set([...x.build.exclude,...f?.exclude||[]])},autoEscape:t===!0?!0:t!==!1,allowedProps:o||x.allowedProps,allowFnCalls:!!y,cache:{...x.cache,...i||{}},forbiddenProps:new Set([...x.forbiddenProps,...p||[]]),keepOpeningTagEscapeDelimiter:u===!0?!0:u!==!1,delimiters:{...x.delimiters,...a||{}}},this.__config}restoreDefaultConfig(){this.__config={...x}}compile(n){return X(n,this.__config,{path:this.__currentRenderedPath||"anonymous"})}render(n,t){let a=this.__currentContext;a!==t&&(this.__currentContext=t);let o=this.compile(n)(K(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,Y,G);return this.__currentContext=a,o}renderComponent(n,t){if(!this.__compiledTemplatesMap.has(n))throw new g(`No template exists with the identifier '${n}'`);let a=this.__currentRenderedPath,o=this.__currentContext,p=this.__compiledTemplatesMap.get(n);this.__currentContext=t,this.__currentRenderedPath=n;let u=p.fn(K(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,Y,G);return this.__currentContext=o,this.__currentRenderedPath=a,u}registerComponent(n,t){let a=t.length*2+500;if(this.__cacheSize+a>this.__config.cache.maxSize&&!this.createEntrySpaceForTemplate(a))throw new g(`The template for the component '${n}' is too large. Consider increasing 'cache.maxSize' in the config`);this.__cacheSize+=t.length*2+500,this.__compiledTemplatesMap.set(n,{fn:this.compile(t),size:a})}reset(){this.__config={...x},this.__compiledTemplatesMap.clear(),this.__currentContext=null,this.__cacheSize=0}createEntrySpaceForTemplate(n){if(this.__cacheSize+n<this.__config.cache.maxSize)return!0;if(n>this.__config.cache.maxSize)return!1;let t=this.__compiledTemplatesMap.entries().next().value;if(t){let[a,o]=t;this.__compiledTemplatesMap.delete(a),this.__cacheSize-=o.size}return this.createEntrySpaceForTemplate(n)}getDiagnostics(){let n=this.__config.cache.maxSize;return{bytesUsed:this.__cacheSize,bytesMax:n,readableUsed:`${(this.__cacheSize/1024/1024).toFixed(2)} MB`,readableMax:`${(n/1024/1024).toFixed(2)} MB`,totalEntries:this.__compiledTemplatesMap.size,percentFull:n>0?Math.min(100,Math.round(this.__cacheSize/n*100)):0,avgTemplateSize:this.__compiledTemplatesMap.size>0?Math.round(this.__cacheSize/this.__compiledTemplatesMap.size):0}}};var _e=B;
1350
14
  //# sourceMappingURL=index.cjs.map