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