janja 4.2.0 → 4.4.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.cjs CHANGED
@@ -336,6 +336,224 @@ class CompileError extends SyntaxError {
336
336
  }
337
337
  }
338
338
 
339
+ const special = /[&<>"']/;
340
+ const specials = /[&<>"']/g;
341
+ const entities = {
342
+ '&': '&amp;',
343
+ '"': '&#34;',
344
+ "'": '&#39;',
345
+ '<': '&lt;',
346
+ '>': '&gt;',
347
+ };
348
+ const entity = (char) => entities[char];
349
+ function escape(v) {
350
+ const str = typeof v === 'string' ? v : `${v}`;
351
+ // Most values contain nothing to escape; they are returned as they are,
352
+ // without allocating
353
+ return special.test(str) ? str.replace(specials, entity) : str;
354
+ }
355
+
356
+ class Safe extends String {
357
+ constructor(value) {
358
+ super(`${value}`);
359
+ }
360
+ }
361
+
362
+ /** Defaults and resolved limits used by the compiler and renderer. */
363
+ function resolveSecurityLimits(security = {}) {
364
+ return {
365
+ maxIncludeDepth: security.maxIncludeDepth ?? 100,
366
+ maxLoopIterations: security.maxLoopIterations,
367
+ maxCallDepth: security.maxCallDepth,
368
+ timeoutMs: security.timeoutMs,
369
+ };
370
+ }
371
+ class SecuritySandbox {
372
+ constructor(options = {}) {
373
+ Object.defineProperty(this, "allowedGlobals", {
374
+ enumerable: true,
375
+ configurable: true,
376
+ writable: true,
377
+ value: void 0
378
+ });
379
+ Object.defineProperty(this, "cspNonce", {
380
+ enumerable: true,
381
+ configurable: true,
382
+ writable: true,
383
+ value: void 0
384
+ });
385
+ this.allowedGlobals = new Set(options.allowedGlobals || []);
386
+ this.cspNonce = options.cspNonce;
387
+ }
388
+ sanitizeGlobals(globals) {
389
+ const sanitized = {};
390
+ for (const [key, value] of Object.entries(globals)) {
391
+ if (this.allowedGlobals.has(key)) {
392
+ sanitized[key] = value;
393
+ }
394
+ }
395
+ return sanitized;
396
+ }
397
+ validateExpression(expression) {
398
+ // Prevent access to dangerous globals
399
+ const dangerousPatterns = [
400
+ /\bprocess\b/,
401
+ /\brequire\b/,
402
+ /\bimport\b/,
403
+ /\bexport\b/,
404
+ /\beval\b/,
405
+ /\bFunction\b/,
406
+ /\b__proto__\b/,
407
+ /\bconstructor\b/,
408
+ ];
409
+ for (const pattern of dangerousPatterns) {
410
+ if (pattern.test(expression)) {
411
+ return false;
412
+ }
413
+ }
414
+ return true;
415
+ }
416
+ createSecureContext(globals) {
417
+ const sanitized = this.sanitizeGlobals(globals);
418
+ // Add safe utility functions
419
+ return {
420
+ ...sanitized,
421
+ Math,
422
+ Date,
423
+ JSON,
424
+ // Add other safe built-ins as needed
425
+ };
426
+ }
427
+ getCSPNonce() {
428
+ return this.cspNonce;
429
+ }
430
+ generateCSPHeaders() {
431
+ const headers = {};
432
+ if (this.cspNonce) {
433
+ headers['Content-Security-Policy'] =
434
+ `script-src 'nonce-${this.cspNonce}'`;
435
+ }
436
+ return headers;
437
+ }
438
+ }
439
+ function deepEscape(value, seen = new WeakSet()) {
440
+ if (value === null || value === undefined) {
441
+ return '';
442
+ }
443
+ if (value instanceof Safe) {
444
+ return `${value}`;
445
+ }
446
+ if (typeof value === 'object') {
447
+ // Guard against circular references
448
+ if (seen.has(value)) {
449
+ return '';
450
+ }
451
+ seen.add(value);
452
+ const values = Array.isArray(value)
453
+ ? value
454
+ : Object.values(value);
455
+ return values.map((v) => deepEscape(v, seen)).join('');
456
+ }
457
+ return escape(value);
458
+ }
459
+ class SecurityAuditor {
460
+ auditTemplate(template) {
461
+ const issues = [];
462
+ // Check for dangerous patterns
463
+ const dangerousPatterns = [
464
+ {
465
+ pattern: /\beval\s*\(/,
466
+ type: 'dangerous-eval',
467
+ message: 'Use of eval() is dangerous and should be avoided',
468
+ severity: 'critical',
469
+ },
470
+ {
471
+ pattern: /\bFunction\s*\(/,
472
+ type: 'dangerous-function',
473
+ message: 'Use of Function constructor is dangerous',
474
+ severity: 'critical',
475
+ },
476
+ {
477
+ pattern: /\brequire\s*\(/,
478
+ type: 'require-usage',
479
+ message: 'Direct require() usage in templates is unsafe',
480
+ severity: 'high',
481
+ },
482
+ {
483
+ pattern: /\bimport\s*\(/,
484
+ type: 'dynamic-import',
485
+ message: 'Dynamic import() usage in templates may be unsafe',
486
+ severity: 'high',
487
+ },
488
+ ];
489
+ for (const { pattern, type, message, severity } of dangerousPatterns) {
490
+ const match = template.match(pattern);
491
+ if (match) {
492
+ issues.push({
493
+ type,
494
+ message,
495
+ location: `at index ${match.index}`,
496
+ severity,
497
+ });
498
+ }
499
+ }
500
+ // Calculate overall severity
501
+ const overallSeverity = this.calculateOverallSeverity(issues);
502
+ return {
503
+ issues,
504
+ severity: overallSeverity,
505
+ };
506
+ }
507
+ calculateOverallSeverity(issues) {
508
+ if (issues.length === 0) {
509
+ return 'low';
510
+ }
511
+ const severityMap = {
512
+ critical: 4,
513
+ high: 3,
514
+ medium: 2,
515
+ low: 1,
516
+ };
517
+ const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
518
+ return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
519
+ }
520
+ }
521
+
522
+ const fingerprints = new WeakMap();
523
+ // How deep includes may nest while rendering. Only templates that include
524
+ // themselves get anywhere near it; the limit turns a cycle that never ends
525
+ // into an error instead of a stack overflow.
526
+ const MAX_INCLUDE_DEPTH = 100;
527
+ // The template itself is the key: one string that is hashed once, and two
528
+ // different templates can never share an entry
529
+ function templateCacheKey(template, stream = false) {
530
+ return stream ? `\0stream:${template}` : template;
531
+ }
532
+ function optionsFingerprint(options) {
533
+ let fingerprint = fingerprints.get(options);
534
+ if (fingerprint === undefined) {
535
+ const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, preloadIncludes, } = options;
536
+ // Limits that change the generated code must bust the compile cache
537
+ const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
538
+ fingerprint = JSON.stringify([
539
+ trimWhitespace,
540
+ stripComments,
541
+ commentOpen,
542
+ commentClose,
543
+ directiveOpen,
544
+ directiveClose,
545
+ outputOpen,
546
+ outputClose,
547
+ maxIncludeDepth,
548
+ maxLoopIterations ?? null,
549
+ maxCallDepth ?? null,
550
+ preloadIncludes,
551
+ ]);
552
+ fingerprints.set(options, fingerprint);
553
+ }
554
+ return fingerprint;
555
+ }
556
+
339
557
  const CONTEXT = 'c';
340
558
  const ESCAPE = 'e';
341
559
  const FILTERS = 'f';
@@ -344,6 +562,9 @@ const WRITE = 'w';
344
562
  const UNKNOWN_FILTER = 'u_';
345
563
  // Holds the result of a filter call while checking whether to await it
346
564
  const RESULT = 'r_';
565
+ // Top-level render context; plain include always receives this, even when
566
+ // nested inside a for/with or an `include … with` partial.
567
+ const TOP_CONTEXT = 'tc_';
347
568
 
348
569
  /**
349
570
  * Contains the source map information.
@@ -611,6 +832,7 @@ const expTokenTypes = {
611
832
  in: 'IN',
612
833
  ni: 'NI',
613
834
  of: 'OF',
835
+ with: 'WITH',
614
836
  '+': 'ADD',
615
837
  '-': 'SUB',
616
838
  '*': 'MUL',
@@ -902,6 +1124,7 @@ const expTokenPrecedences = {
902
1124
  IN: 40,
903
1125
  NI: 40,
904
1126
  OF: 40,
1127
+ WITH: 40,
905
1128
  ADD: 50,
906
1129
  SUB: 50,
907
1130
  MUL: 60,
@@ -1049,36 +1272,12 @@ class ExpParser {
1049
1272
  }
1050
1273
  continue;
1051
1274
  }
1052
- if (token.type === 'AND' ||
1053
- token.type === 'OR' ||
1054
- token.type === 'IS' ||
1055
- token.type === 'EQ' ||
1056
- token.type === 'NE' ||
1057
- token.type === 'GT' ||
1058
- token.type === 'LT' ||
1059
- token.type === 'GE' ||
1060
- token.type === 'LE' ||
1061
- token.type === 'IN' ||
1062
- token.type === 'NI' ||
1063
- token.type === 'OF' ||
1064
- token.type === 'ADD' ||
1065
- token.type === 'SUB' ||
1066
- token.type === 'MUL' ||
1067
- token.type === 'DIV' ||
1068
- token.type === 'MOD' ||
1069
- token.type === 'ASSIGN') {
1275
+ if (isBinaryOp(token.type)) {
1070
1276
  if (!left) {
1071
1277
  throw new ExpError(`No left operand for "${token.type}"`, token.loc);
1072
1278
  }
1073
1279
  if (token.type === 'ASSIGN') {
1074
- if (left.type === 'SEQ') {
1075
- if (left.elements.some((el) => el.type !== 'ID' || el.path || el.args)) {
1076
- throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1077
- }
1078
- }
1079
- else if (left.type !== 'ID' || left.path || left.args) {
1080
- throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1081
- }
1280
+ assertAssignableLeft(left, token);
1082
1281
  }
1083
1282
  const right = this.parseExp((t) => isHigher(token, t) ? 'BACK' : undefined);
1084
1283
  if (!right) {
@@ -1181,12 +1380,46 @@ class ExpParser {
1181
1380
  }
1182
1381
  }
1183
1382
  }
1383
+ const BINARY_OPS = new Set([
1384
+ 'AND',
1385
+ 'OR',
1386
+ 'IS',
1387
+ 'EQ',
1388
+ 'NE',
1389
+ 'GT',
1390
+ 'LT',
1391
+ 'GE',
1392
+ 'LE',
1393
+ 'IN',
1394
+ 'NI',
1395
+ 'OF',
1396
+ 'WITH',
1397
+ 'ADD',
1398
+ 'SUB',
1399
+ 'MUL',
1400
+ 'DIV',
1401
+ 'MOD',
1402
+ 'ASSIGN',
1403
+ ]);
1404
+ function isBinaryOp(type) {
1405
+ return BINARY_OPS.has(type);
1406
+ }
1184
1407
  // Two operands in a row, e.g. `a b`
1185
1408
  function assertNotOperand(token) {
1186
1409
  if (token.type === 'ID' || token.type === 'LIT' || token.type === 'LP') {
1187
1410
  throw new ExpError(`Unexpected "${token.raw ?? token.value}"`, token.loc);
1188
1411
  }
1189
1412
  }
1413
+ function assertAssignableLeft(left, token) {
1414
+ if (left.type === 'SEQ') {
1415
+ if (left.elements.some((el) => el.type !== 'ID' || el.path || el.args)) {
1416
+ throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1417
+ }
1418
+ }
1419
+ else if (left.type !== 'ID' || left.path || left.args) {
1420
+ throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1421
+ }
1422
+ }
1190
1423
  function isHigher(a, b) {
1191
1424
  // "(" starts an operand; it is not an operator to compare against
1192
1425
  if (b.type === 'LP') {
@@ -1552,251 +1785,78 @@ class Parser extends Tokenizer {
1552
1785
  }
1553
1786
  return nodes;
1554
1787
  }
1555
- parseExp({ val, loc }) {
1556
- try {
1557
- return this.expParser.parse(val, loc);
1558
- }
1559
- catch (error) {
1560
- this.options.debug(error.loc
1561
- ? new CompileError(error.message, this.template, error.loc)
1562
- : error);
1563
- }
1564
- }
1565
- peek() {
1566
- return this.tokens.at(this.cursor) ?? null;
1567
- }
1568
- advance() {
1569
- this.cursor++;
1570
- }
1571
- match(names, token = this.peek()) {
1572
- // Directive names are case-insensitive, like the lookup of their parser
1573
- return names.includes(token?.name?.toLowerCase());
1574
- }
1575
- emitExpErr({ name, loc }, required = true) {
1576
- this.options.debug(new CompileError(required
1577
- ? `"${name}" requires expression`
1578
- : `"${name}" should not have expression`, this.template, loc));
1579
- }
1580
- }
1581
-
1582
- const special = /[&<>"']/;
1583
- const specials = /[&<>"']/g;
1584
- const entities = {
1585
- '&': '&amp;',
1586
- '"': '&#34;',
1587
- "'": '&#39;',
1588
- '<': '&lt;',
1589
- '>': '&gt;',
1590
- };
1591
- const entity = (char) => entities[char];
1592
- function escape(v) {
1593
- const str = typeof v === 'string' ? v : `${v}`;
1594
- // Most values contain nothing to escape; they are returned as they are,
1595
- // without allocating
1596
- return special.test(str) ? str.replace(specials, entity) : str;
1597
- }
1598
-
1599
- class Safe extends String {
1600
- constructor(value) {
1601
- super(`${value}`);
1602
- }
1603
- }
1604
-
1605
- /** Defaults and resolved limits used by the compiler and renderer. */
1606
- function resolveSecurityLimits(security = {}) {
1607
- return {
1608
- maxIncludeDepth: security.maxIncludeDepth ?? 100,
1609
- maxLoopIterations: security.maxLoopIterations,
1610
- maxCallDepth: security.maxCallDepth,
1611
- timeoutMs: security.timeoutMs,
1612
- };
1613
- }
1614
- class SecuritySandbox {
1615
- constructor(options = {}) {
1616
- Object.defineProperty(this, "allowedGlobals", {
1617
- enumerable: true,
1618
- configurable: true,
1619
- writable: true,
1620
- value: void 0
1621
- });
1622
- Object.defineProperty(this, "cspNonce", {
1623
- enumerable: true,
1624
- configurable: true,
1625
- writable: true,
1626
- value: void 0
1627
- });
1628
- this.allowedGlobals = new Set(options.allowedGlobals || []);
1629
- this.cspNonce = options.cspNonce;
1630
- }
1631
- sanitizeGlobals(globals) {
1632
- const sanitized = {};
1633
- for (const [key, value] of Object.entries(globals)) {
1634
- if (this.allowedGlobals.has(key)) {
1635
- sanitized[key] = value;
1636
- }
1637
- }
1638
- return sanitized;
1639
- }
1640
- validateExpression(expression) {
1641
- // Prevent access to dangerous globals
1642
- const dangerousPatterns = [
1643
- /\bprocess\b/,
1644
- /\brequire\b/,
1645
- /\bimport\b/,
1646
- /\bexport\b/,
1647
- /\beval\b/,
1648
- /\bFunction\b/,
1649
- /\b__proto__\b/,
1650
- /\bconstructor\b/,
1651
- ];
1652
- for (const pattern of dangerousPatterns) {
1653
- if (pattern.test(expression)) {
1654
- return false;
1655
- }
1656
- }
1657
- return true;
1658
- }
1659
- createSecureContext(globals) {
1660
- const sanitized = this.sanitizeGlobals(globals);
1661
- // Add safe utility functions
1662
- return {
1663
- ...sanitized,
1664
- Math,
1665
- Date,
1666
- JSON,
1667
- // Add other safe built-ins as needed
1668
- };
1669
- }
1670
- getCSPNonce() {
1671
- return this.cspNonce;
1672
- }
1673
- generateCSPHeaders() {
1674
- const headers = {};
1675
- if (this.cspNonce) {
1676
- headers['Content-Security-Policy'] =
1677
- `script-src 'nonce-${this.cspNonce}'`;
1678
- }
1679
- return headers;
1680
- }
1681
- }
1682
- function deepEscape(value, seen = new WeakSet()) {
1683
- if (value === null || value === undefined) {
1684
- return '';
1685
- }
1686
- if (value instanceof Safe) {
1687
- return `${value}`;
1688
- }
1689
- if (typeof value === 'object') {
1690
- // Guard against circular references
1691
- if (seen.has(value)) {
1692
- return '';
1693
- }
1694
- seen.add(value);
1695
- const values = Array.isArray(value)
1696
- ? value
1697
- : Object.values(value);
1698
- return values.map((v) => deepEscape(v, seen)).join('');
1699
- }
1700
- return escape(value);
1701
- }
1702
- class SecurityAuditor {
1703
- auditTemplate(template) {
1704
- const issues = [];
1705
- // Check for dangerous patterns
1706
- const dangerousPatterns = [
1707
- {
1708
- pattern: /\beval\s*\(/,
1709
- type: 'dangerous-eval',
1710
- message: 'Use of eval() is dangerous and should be avoided',
1711
- severity: 'critical',
1712
- },
1713
- {
1714
- pattern: /\bFunction\s*\(/,
1715
- type: 'dangerous-function',
1716
- message: 'Use of Function constructor is dangerous',
1717
- severity: 'critical',
1718
- },
1719
- {
1720
- pattern: /\brequire\s*\(/,
1721
- type: 'require-usage',
1722
- message: 'Direct require() usage in templates is unsafe',
1723
- severity: 'high',
1724
- },
1725
- {
1726
- pattern: /\bimport\s*\(/,
1727
- type: 'dynamic-import',
1728
- message: 'Dynamic import() usage in templates may be unsafe',
1729
- severity: 'high',
1730
- },
1731
- ];
1732
- for (const { pattern, type, message, severity } of dangerousPatterns) {
1733
- const match = template.match(pattern);
1734
- if (match) {
1735
- issues.push({
1736
- type,
1737
- message,
1738
- location: `at index ${match.index}`,
1739
- severity,
1740
- });
1741
- }
1742
- }
1743
- // Calculate overall severity
1744
- const overallSeverity = this.calculateOverallSeverity(issues);
1745
- return {
1746
- issues,
1747
- severity: overallSeverity,
1748
- };
1749
- }
1750
- calculateOverallSeverity(issues) {
1751
- if (issues.length === 0) {
1752
- return 'low';
1788
+ parseExp({ val, loc }) {
1789
+ try {
1790
+ return this.expParser.parse(val, loc);
1753
1791
  }
1754
- const severityMap = {
1755
- critical: 4,
1756
- high: 3,
1757
- medium: 2,
1758
- low: 1,
1759
- };
1760
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1761
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
1792
+ catch (error) {
1793
+ this.options.debug(error.loc
1794
+ ? new CompileError(error.message, this.template, error.loc)
1795
+ : error);
1796
+ }
1797
+ }
1798
+ peek() {
1799
+ return this.tokens.at(this.cursor) ?? null;
1800
+ }
1801
+ advance() {
1802
+ this.cursor++;
1803
+ }
1804
+ match(names, token = this.peek()) {
1805
+ // Directive names are case-insensitive, like the lookup of their parser
1806
+ return names.includes(token?.name?.toLowerCase());
1807
+ }
1808
+ emitExpErr({ name, loc }, required = true) {
1809
+ this.options.debug(new CompileError(required
1810
+ ? `"${name}" requires expression`
1811
+ : `"${name}" should not have expression`, this.template, loc));
1762
1812
  }
1763
1813
  }
1764
1814
 
1765
- const fingerprints = new WeakMap();
1766
- // How deep includes may nest while rendering. Only templates that include
1767
- // themselves get anywhere near it; the limit turns a cycle that never ends
1768
- // into an error instead of a stack overflow.
1769
- const MAX_INCLUDE_DEPTH = 100;
1770
- // Directives whose body is still the template's own top-level output
1771
- const transparent = new Set(['IF', 'FOR']);
1772
- // The template itself is the key: one string that is hashed once, and two
1773
- // different templates can never share an entry
1774
- function templateCacheKey(template, stream = false) {
1775
- return stream ? `\0stream:${template}` : template;
1815
+ function isStringLit(exp) {
1816
+ return exp.type === 'LIT' && typeof exp.value === 'string';
1776
1817
  }
1777
- function optionsFingerprint(options) {
1778
- let fingerprint = fingerprints.get(options);
1779
- if (fingerprint === undefined) {
1780
- const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1781
- // Limits that change the generated code must bust the compile cache
1782
- const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1783
- fingerprint = JSON.stringify([
1784
- trimWhitespace,
1785
- stripComments,
1786
- commentOpen,
1787
- commentClose,
1788
- directiveOpen,
1789
- directiveClose,
1790
- outputOpen,
1791
- outputClose,
1792
- maxIncludeDepth,
1793
- maxLoopIterations ?? null,
1794
- maxCallDepth ?? null,
1795
- ]);
1796
- fingerprints.set(options, fingerprint);
1818
+ class IncludeNode extends Traversal {
1819
+ constructor(val, loc, strip, withExp = null) {
1820
+ super();
1821
+ Object.defineProperty(this, "val", {
1822
+ enumerable: true,
1823
+ configurable: true,
1824
+ writable: true,
1825
+ value: val
1826
+ });
1827
+ Object.defineProperty(this, "loc", {
1828
+ enumerable: true,
1829
+ configurable: true,
1830
+ writable: true,
1831
+ value: loc
1832
+ });
1833
+ Object.defineProperty(this, "strip", {
1834
+ enumerable: true,
1835
+ configurable: true,
1836
+ writable: true,
1837
+ value: strip
1838
+ });
1839
+ Object.defineProperty(this, "withExp", {
1840
+ enumerable: true,
1841
+ configurable: true,
1842
+ writable: true,
1843
+ value: withExp
1844
+ });
1845
+ Object.defineProperty(this, "type", {
1846
+ enumerable: true,
1847
+ configurable: true,
1848
+ writable: true,
1849
+ value: 'INCLUDE'
1850
+ });
1797
1851
  }
1798
- return fingerprint;
1799
1852
  }
1853
+
1854
+ const PRELOAD_LOC = {
1855
+ start: { line: 1, column: 1 },
1856
+ end: { line: 1, column: 1 },
1857
+ };
1858
+ // Directives whose body is still the template's own top-level output
1859
+ const transparent = new Set(['IF', 'FOR']);
1800
1860
  class Compiler extends Context {
1801
1861
  constructor(options, cache, revalidate = true, stream = false) {
1802
1862
  super();
@@ -1886,6 +1946,13 @@ class Compiler extends Context {
1886
1946
  writable: true,
1887
1947
  value: void 0
1888
1948
  });
1949
+ /** True when the template uses a non-literal include path. */
1950
+ Object.defineProperty(this, "hasDynamicInclude", {
1951
+ enumerable: true,
1952
+ configurable: true,
1953
+ writable: true,
1954
+ value: false
1955
+ });
1889
1956
  /**
1890
1957
  * Whether the code being generated may write output to the stream. True
1891
1958
  * only in stream mode, for the template's own top-level output.
@@ -1906,6 +1973,7 @@ class Compiler extends Context {
1906
1973
  this.stylesheets = stylesheets;
1907
1974
  this.stylesheetKey = stylesheetKey;
1908
1975
  this.sources = sources;
1976
+ this.hasDynamicInclude = false;
1909
1977
  // Generate cache key from template and options
1910
1978
  const cacheKey = this.generateCacheKey(template);
1911
1979
  // Check cache first
@@ -1931,11 +1999,15 @@ class Compiler extends Context {
1931
1999
  }
1932
2000
  await this.parseTemplates();
1933
2001
  if (this.isRoot) {
1934
- if (this.partials.size) {
2002
+ if (this.partials.size || this.hasDynamicInclude) {
1935
2003
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1936
- this.pushRaw(null, 'let d_=0;', 'const p={');
2004
+ // Alias the render data before partials shadow `c` with their argument.
2005
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
1937
2006
  for (const [path, code] of this.partials) {
1938
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${maxIncludeDepth})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
2007
+ this.pushRaw(null,
2008
+ // Partials take the context they should render with: plain include
2009
+ // passes the top-level `tc_`; `include … with` passes a merged scope.
2010
+ `${JSON.stringify(path)}:async(c)=>{`, `if(d_>=${maxIncludeDepth})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
1939
2011
  }
1940
2012
  this.pushRaw(null, '};');
1941
2013
  }
@@ -2025,6 +2097,17 @@ class Compiler extends Context {
2025
2097
  }
2026
2098
  async parseTemplates() {
2027
2099
  const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
2100
+ if (this.isRoot) {
2101
+ for (const path of this.options.preloadIncludes) {
2102
+ if (!partials.has(path)) {
2103
+ partials.set(path, new IncludeNode({
2104
+ type: 'LIT',
2105
+ value: path,
2106
+ loc: PRELOAD_LOC,
2107
+ }, PRELOAD_LOC, { before: false, after: false }));
2108
+ }
2109
+ }
2110
+ }
2028
2111
  for (const [path, node] of partials) {
2029
2112
  if (!this.partials.has(path)) {
2030
2113
  let template;
@@ -2062,8 +2145,14 @@ class Compiler extends Context {
2062
2145
  const stylesheets = [];
2063
2146
  const traverse = (node) => {
2064
2147
  if (node.type === 'INCLUDE') {
2065
- if (!partials.has(node.val.value)) {
2066
- partials.set(node.val.value, node);
2148
+ const include = node;
2149
+ if (isStringLit(include.val)) {
2150
+ if (!partials.has(include.val.value)) {
2151
+ partials.set(include.val.value, include);
2152
+ }
2153
+ }
2154
+ else {
2155
+ this.hasDynamicInclude = true;
2067
2156
  }
2068
2157
  }
2069
2158
  if (node.type === 'BLOCK') {
@@ -2474,6 +2563,7 @@ const compilerOptions = {
2474
2563
  trimWhitespace: false,
2475
2564
  stripComments: false,
2476
2565
  loader: async () => '',
2566
+ preloadIncludes: [],
2477
2567
  };
2478
2568
  const renderOptions = {
2479
2569
  ...compilerOptions,
@@ -2652,6 +2742,7 @@ const expTokenOperators$1 = {
2652
2742
  IN: ' in ',
2653
2743
  NI: ' in ',
2654
2744
  OF: ' of ',
2745
+ WITH: ' with ',
2655
2746
  ADD: '+',
2656
2747
  SUB: '-',
2657
2748
  MUL: '*',
@@ -3537,50 +3628,39 @@ const plugin$9 = {
3537
3628
  parsers: parsers$9,
3538
3629
  };
3539
3630
 
3540
- async function compileInclude({ val: { value }, loc }, compiler) {
3541
- compiler.pushRaw(loc, `s+=await p[${JSON.stringify(value)}]?.()??"";`);
3631
+ async function compileInclude({ val, loc, withExp }, compiler) {
3632
+ const expCompiler = new ExpCompiler();
3633
+ const path = isStringLit(val)
3634
+ ? JSON.stringify(val.value)
3635
+ : expCompiler.compile(val, compiler.context);
3636
+ if (withExp) {
3637
+ const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3638
+ compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3639
+ return;
3640
+ }
3641
+ // Plain include always sees the top-level context, not loop/with scopes.
3642
+ compiler.pushRaw(loc, `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`);
3542
3643
  }
3543
3644
  const compilers$8 = {
3544
3645
  INCLUDE: compileInclude,
3545
3646
  };
3546
3647
 
3547
- class IncludeNode extends Traversal {
3548
- constructor(val, loc, strip) {
3549
- super();
3550
- Object.defineProperty(this, "val", {
3551
- enumerable: true,
3552
- configurable: true,
3553
- writable: true,
3554
- value: val
3555
- });
3556
- Object.defineProperty(this, "loc", {
3557
- enumerable: true,
3558
- configurable: true,
3559
- writable: true,
3560
- value: loc
3561
- });
3562
- Object.defineProperty(this, "strip", {
3563
- enumerable: true,
3564
- configurable: true,
3565
- writable: true,
3566
- value: strip
3567
- });
3568
- Object.defineProperty(this, "type", {
3569
- enumerable: true,
3570
- configurable: true,
3571
- writable: true,
3572
- value: 'INCLUDE'
3573
- });
3574
- }
3575
- }
3576
-
3577
3648
  function* parseInclude(token, parser) {
3578
3649
  if (!token.expression) {
3579
3650
  parser.emitExpErr(token);
3580
3651
  return;
3581
3652
  }
3582
3653
  yield 'NEXT';
3583
- yield new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
3654
+ const exp = parser.parseExp(token.expression);
3655
+ if (!exp) {
3656
+ return;
3657
+ }
3658
+ if (exp.type === 'WITH') {
3659
+ const { left, right } = exp;
3660
+ yield new IncludeNode(left, token.loc, token.strip, right);
3661
+ return;
3662
+ }
3663
+ yield new IncludeNode(exp, token.loc, token.strip);
3584
3664
  }
3585
3665
  const parsers$8 = {
3586
3666
  include: parseInclude,
@@ -3861,14 +3941,18 @@ async function compileStylesheet() {
3861
3941
  async function compileStylesheets({ loc }, compiler) {
3862
3942
  compiler.pushRaw(loc,
3863
3943
  // First `stylesheets` wins; later ones are ignored (same idea as blocks).
3864
- 'if(!ss_u++){', 's+="<style>";', 'for(const f_ of ss_)s+=await f_();', 's+="</style>";', '}');
3944
+ // Bodies are emitted as-is — authors wrap CSS in `<style>` for IDE highlighting.
3945
+ 'if(!ss_u++){', 'for(const f_ of ss_)s+=await f_();', '}');
3865
3946
  }
3866
3947
  const compilers$4 = {
3867
3948
  STYLESHEET: compileStylesheet,
3868
3949
  STYLESHEETS: compileStylesheets,
3869
3950
  };
3870
3951
 
3871
- /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
3952
+ /**
3953
+ * Co-located styles with a section/snippet (Shopify `{% stylesheet %}` analogue).
3954
+ * Body is usually a `<style>…</style>` block for native IDE CSS highlighting.
3955
+ */
3872
3956
  class StylesheetNode extends Traversal {
3873
3957
  constructor(body, loc, strip) {
3874
3958
  super();
@@ -3898,7 +3982,7 @@ class StylesheetNode extends Traversal {
3898
3982
  });
3899
3983
  }
3900
3984
  }
3901
- /** Emits every collected stylesheet into the document (typically in `<head>`). */
3985
+ /** Concatenates collected stylesheet bodies into the document (typically in `<head>`). */
3902
3986
  class StylesheetsNode extends Traversal {
3903
3987
  constructor(loc, strip) {
3904
3988
  super();
@@ -4616,7 +4700,13 @@ class Analyzer {
4616
4700
  await this.nodes(node.body, scope);
4617
4701
  break;
4618
4702
  case 'INCLUDE':
4619
- await this.include(node.val.value, scope);
4703
+ this.exp(node.val, scope);
4704
+ if (node.withExp) {
4705
+ this.exp(node.withExp, scope);
4706
+ }
4707
+ if (node.val.type === 'LIT' && typeof node.val.value === 'string') {
4708
+ await this.include(node.val.value, scope);
4709
+ }
4620
4710
  break;
4621
4711
  default:
4622
4712
  await this.nodes(node.body, scope);
@@ -5298,6 +5388,7 @@ const expTokenOperators = {
5298
5388
  IN: 'in',
5299
5389
  NI: 'ni',
5300
5390
  OF: 'of',
5391
+ WITH: 'with',
5301
5392
  ADD: '+',
5302
5393
  SUB: '-',
5303
5394
  MUL: '*',
@@ -5338,6 +5429,7 @@ class ExpFormatter {
5338
5429
  case 'IN':
5339
5430
  case 'NI':
5340
5431
  case 'OF':
5432
+ case 'WITH':
5341
5433
  case 'ADD':
5342
5434
  case 'SUB':
5343
5435
  case 'MUL':
@@ -5379,6 +5471,149 @@ class ExpFormatter {
5379
5471
  }
5380
5472
  }
5381
5473
 
5474
+ /**
5475
+ * Brace-depth reindent for co-located CSS. Only leading whitespace changes;
5476
+ * braces inside strings/comments are ignored.
5477
+ */
5478
+ function indentCss(source, tabWidth) {
5479
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5480
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5481
+ const lines = source.split(/\r?\n/);
5482
+ let depth = 0;
5483
+ const out = [];
5484
+ for (const line of lines) {
5485
+ const content = line.trim();
5486
+ if (content.length === 0) {
5487
+ out.push('');
5488
+ continue;
5489
+ }
5490
+ const { opens, closes } = countCssBraces(content);
5491
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5492
+ out.push(pad.repeat(lineDepth) + content);
5493
+ depth = Math.max(0, depth + opens - closes);
5494
+ }
5495
+ return out.join(eol);
5496
+ }
5497
+ function countCssBraces(line) {
5498
+ let opens = 0;
5499
+ let closes = 0;
5500
+ let quote = null;
5501
+ let i = 0;
5502
+ while (i < line.length) {
5503
+ const c = line[i];
5504
+ if (quote) {
5505
+ if (c === '\\') {
5506
+ i += 2;
5507
+ continue;
5508
+ }
5509
+ if (c === quote) {
5510
+ quote = null;
5511
+ }
5512
+ i += 1;
5513
+ continue;
5514
+ }
5515
+ if (c === '"' || c === "'") {
5516
+ quote = c;
5517
+ i += 1;
5518
+ continue;
5519
+ }
5520
+ if (c === '/' && line[i + 1] === '*') {
5521
+ const end = line.indexOf('*/', i + 2);
5522
+ i = end === -1 ? line.length : end + 2;
5523
+ continue;
5524
+ }
5525
+ if (c === '/' && line[i + 1] === '/') {
5526
+ break;
5527
+ }
5528
+ if (c === '{') {
5529
+ opens += 1;
5530
+ }
5531
+ else if (c === '}') {
5532
+ closes += 1;
5533
+ }
5534
+ i += 1;
5535
+ }
5536
+ return { opens, closes };
5537
+ }
5538
+
5539
+ /**
5540
+ * Brace-depth reindent for `<script>` bodies. Only leading whitespace changes;
5541
+ * braces inside strings, comments, template literals, and Janja tags are ignored.
5542
+ */
5543
+ function indentJs(source, tabWidth) {
5544
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5545
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5546
+ const lines = source.split(/\r?\n/);
5547
+ let depth = 0;
5548
+ const out = [];
5549
+ for (const line of lines) {
5550
+ const content = line.trim();
5551
+ if (content.length === 0) {
5552
+ out.push('');
5553
+ continue;
5554
+ }
5555
+ const { opens, closes } = countJsBraces(content);
5556
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5557
+ out.push(pad.repeat(lineDepth) + content);
5558
+ depth = Math.max(0, depth + opens - closes);
5559
+ }
5560
+ return out.join(eol);
5561
+ }
5562
+ function countJsBraces(line) {
5563
+ let opens = 0;
5564
+ let closes = 0;
5565
+ let quote = null;
5566
+ let i = 0;
5567
+ while (i < line.length) {
5568
+ const c = line[i];
5569
+ if (quote) {
5570
+ if (c === '\\') {
5571
+ i += 2;
5572
+ continue;
5573
+ }
5574
+ if (c === quote) {
5575
+ quote = null;
5576
+ }
5577
+ i += 1;
5578
+ continue;
5579
+ }
5580
+ if (c === '{' && line[i + 1] === '{') {
5581
+ i = endOfJanja(line, i);
5582
+ continue;
5583
+ }
5584
+ if (c === '"' || c === "'" || c === '`') {
5585
+ quote = c;
5586
+ i += 1;
5587
+ continue;
5588
+ }
5589
+ if (c === '/' && line[i + 1] === '*') {
5590
+ const end = line.indexOf('*/', i + 2);
5591
+ i = end === -1 ? line.length : end + 2;
5592
+ continue;
5593
+ }
5594
+ if (c === '/' && line[i + 1] === '/') {
5595
+ break;
5596
+ }
5597
+ if (c === '{') {
5598
+ opens += 1;
5599
+ }
5600
+ else if (c === '}') {
5601
+ closes += 1;
5602
+ }
5603
+ i += 1;
5604
+ }
5605
+ return { opens, closes };
5606
+ }
5607
+ /** Skip a Janja tag starting at `i` (`{{`, `{{=`, `{{#` …). */
5608
+ function endOfJanja(line, i) {
5609
+ if (line.startsWith('{{#', i)) {
5610
+ const end = line.indexOf('#}}', i + 3);
5611
+ return end === -1 ? line.length : end + 3;
5612
+ }
5613
+ const end = line.indexOf('}}', i + 2);
5614
+ return end === -1 ? line.length : end + 2;
5615
+ }
5616
+
5382
5617
  /** HTML void elements — never take children, so they do not change indent. */
5383
5618
  const VOID = new Set([
5384
5619
  'area',
@@ -5396,8 +5631,13 @@ const VOID = new Set([
5396
5631
  'track',
5397
5632
  'wbr',
5398
5633
  ]);
5399
- /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5634
+ /**
5635
+ * Mark open/close so the body can be buffered. `pre` / `textarea` keep
5636
+ * whitespace; `script` / `style` are reindented (see body buffer below).
5637
+ */
5400
5638
  const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5639
+ /** HTML elements whose bodies are reindented (not left raw). */
5640
+ const REINDENT_HTML = new Set(['script', 'style']);
5401
5641
  const DIR_OPEN = new Set([
5402
5642
  'if',
5403
5643
  'for',
@@ -5408,6 +5648,8 @@ const DIR_OPEN = new Set([
5408
5648
  'with',
5409
5649
  'stylesheet',
5410
5650
  ]);
5651
+ /** Directives whose bodies keep leading whitespace (like `<style>`). */
5652
+ const DIR_SENSITIVE = new Set(['stylesheet']);
5411
5653
  const DIR_MID = new Set(['else', 'elif', 'elseif', 'elsif']);
5412
5654
  const DIR_CLOSE = new Set([
5413
5655
  'endif',
@@ -5422,8 +5664,9 @@ const DIR_CLOSE = new Set([
5422
5664
  /**
5423
5665
  * Reindent a template that already had its Janja tags normalised.
5424
5666
  * Only leading whitespace on each line changes; line breaks and
5425
- * intra-line spacing stay put. Content inside pre/textarea/script/style
5426
- * is left alone; the closing tag of those elements is still reindented.
5667
+ * intra-line spacing stay put. Content inside pre/textarea is left alone;
5668
+ * `script` / `style` bodies are brace-reindented; `stylesheet` bodies are
5669
+ * formatted as an HTML fragment (so nested `<style>` gets CSS indent).
5427
5670
  */
5428
5671
  function indentHtml(source, options) {
5429
5672
  const tabWidth = options.tabWidth ?? 2;
@@ -5432,6 +5675,8 @@ function indentHtml(source, options) {
5432
5675
  const lines = source.split(/\r?\n/);
5433
5676
  let depth = 0;
5434
5677
  let sensitive = null;
5678
+ /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5679
+ let bodyBuf = null;
5435
5680
  const out = [];
5436
5681
  for (const line of lines) {
5437
5682
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
@@ -5440,7 +5685,28 @@ function indentHtml(source, options) {
5440
5685
  const activeSensitive = sensitive;
5441
5686
  const closesSensitive = activeSensitive !== null &&
5442
5687
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5443
- if (sensitive && !closesSensitive) {
5688
+ const reindentBody = activeSensitive === 'stylesheet' ||
5689
+ (activeSensitive !== null && REINDENT_HTML.has(activeSensitive));
5690
+ if (reindentBody && !closesSensitive) {
5691
+ // Do not applyDepth: bodies may contain nested Janja if/for tags.
5692
+ (bodyBuf ?? (bodyBuf = [])).push(line);
5693
+ continue;
5694
+ }
5695
+ if (bodyBuf && closesSensitive && reindentBody) {
5696
+ // stylesheet: same column as the tags; script/style: one level inside.
5697
+ const baseDepth = activeSensitive === 'stylesheet' ? Math.max(0, depth - 1) : depth;
5698
+ const raw = bodyBuf.join(eol);
5699
+ const formatted = activeSensitive === 'stylesheet'
5700
+ ? indentHtml(raw, options)
5701
+ : activeSensitive === 'style'
5702
+ ? indentCss(raw, tabWidth)
5703
+ : indentJs(raw, tabWidth);
5704
+ for (const bodyLine of formatted.split(/\r?\n/)) {
5705
+ out.push(bodyLine.length === 0 ? '' : pad.repeat(baseDepth) + bodyLine);
5706
+ }
5707
+ bodyBuf = null;
5708
+ }
5709
+ else if (sensitive && !closesSensitive) {
5444
5710
  out.push(line);
5445
5711
  applyDepth(pieces);
5446
5712
  continue;
@@ -5542,13 +5808,26 @@ function readDirective(line, start, options) {
5542
5808
  return { end };
5543
5809
  }
5544
5810
  if (DIR_CLOSE.has(name)) {
5545
- return { end, piece: { kind: 'close' } };
5811
+ const base = name.startsWith('end') ? name.slice(3) : name;
5812
+ return {
5813
+ end,
5814
+ piece: {
5815
+ kind: 'close',
5816
+ sensitive: DIR_SENSITIVE.has(base) ? base : undefined,
5817
+ },
5818
+ };
5546
5819
  }
5547
5820
  if (DIR_MID.has(name)) {
5548
5821
  return { end, piece: { kind: 'mid' } };
5549
5822
  }
5550
5823
  if (DIR_OPEN.has(name)) {
5551
- return { end, piece: { kind: 'open' } };
5824
+ return {
5825
+ end,
5826
+ piece: {
5827
+ kind: 'open',
5828
+ sensitive: DIR_SENSITIVE.has(name) ? name : undefined,
5829
+ },
5830
+ };
5552
5831
  }
5553
5832
  return { end };
5554
5833
  }