janja 4.3.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';
@@ -1568,251 +1786,78 @@ ${suggestionText}`;
1568
1786
  }
1569
1787
  return nodes;
1570
1788
  }
1571
- parseExp({ val, loc }) {
1572
- try {
1573
- return this.expParser.parse(val, loc);
1574
- }
1575
- catch (error) {
1576
- this.options.debug(error.loc
1577
- ? new CompileError(error.message, this.template, error.loc)
1578
- : error);
1579
- }
1580
- }
1581
- peek() {
1582
- return this.tokens.at(this.cursor) ?? null;
1583
- }
1584
- advance() {
1585
- this.cursor++;
1586
- }
1587
- match(names, token = this.peek()) {
1588
- // Directive names are case-insensitive, like the lookup of their parser
1589
- return names.includes(token?.name?.toLowerCase());
1590
- }
1591
- emitExpErr({ name, loc }, required = true) {
1592
- this.options.debug(new CompileError(required
1593
- ? `"${name}" requires expression`
1594
- : `"${name}" should not have expression`, this.template, loc));
1595
- }
1596
- }
1597
-
1598
- const special = /[&<>"']/;
1599
- const specials = /[&<>"']/g;
1600
- const entities = {
1601
- '&': '&amp;',
1602
- '"': '&#34;',
1603
- "'": '&#39;',
1604
- '<': '&lt;',
1605
- '>': '&gt;',
1606
- };
1607
- const entity = (char) => entities[char];
1608
- function escape(v) {
1609
- const str = typeof v === 'string' ? v : `${v}`;
1610
- // Most values contain nothing to escape; they are returned as they are,
1611
- // without allocating
1612
- return special.test(str) ? str.replace(specials, entity) : str;
1613
- }
1614
-
1615
- class Safe extends String {
1616
- constructor(value) {
1617
- super(`${value}`);
1618
- }
1619
- }
1620
-
1621
- /** Defaults and resolved limits used by the compiler and renderer. */
1622
- function resolveSecurityLimits(security = {}) {
1623
- return {
1624
- maxIncludeDepth: security.maxIncludeDepth ?? 100,
1625
- maxLoopIterations: security.maxLoopIterations,
1626
- maxCallDepth: security.maxCallDepth,
1627
- timeoutMs: security.timeoutMs,
1628
- };
1629
- }
1630
- class SecuritySandbox {
1631
- constructor(options = {}) {
1632
- Object.defineProperty(this, "allowedGlobals", {
1633
- enumerable: true,
1634
- configurable: true,
1635
- writable: true,
1636
- value: void 0
1637
- });
1638
- Object.defineProperty(this, "cspNonce", {
1639
- enumerable: true,
1640
- configurable: true,
1641
- writable: true,
1642
- value: void 0
1643
- });
1644
- this.allowedGlobals = new Set(options.allowedGlobals || []);
1645
- this.cspNonce = options.cspNonce;
1646
- }
1647
- sanitizeGlobals(globals) {
1648
- const sanitized = {};
1649
- for (const [key, value] of Object.entries(globals)) {
1650
- if (this.allowedGlobals.has(key)) {
1651
- sanitized[key] = value;
1652
- }
1653
- }
1654
- return sanitized;
1655
- }
1656
- validateExpression(expression) {
1657
- // Prevent access to dangerous globals
1658
- const dangerousPatterns = [
1659
- /\bprocess\b/,
1660
- /\brequire\b/,
1661
- /\bimport\b/,
1662
- /\bexport\b/,
1663
- /\beval\b/,
1664
- /\bFunction\b/,
1665
- /\b__proto__\b/,
1666
- /\bconstructor\b/,
1667
- ];
1668
- for (const pattern of dangerousPatterns) {
1669
- if (pattern.test(expression)) {
1670
- return false;
1671
- }
1672
- }
1673
- return true;
1674
- }
1675
- createSecureContext(globals) {
1676
- const sanitized = this.sanitizeGlobals(globals);
1677
- // Add safe utility functions
1678
- return {
1679
- ...sanitized,
1680
- Math,
1681
- Date,
1682
- JSON,
1683
- // Add other safe built-ins as needed
1684
- };
1685
- }
1686
- getCSPNonce() {
1687
- return this.cspNonce;
1688
- }
1689
- generateCSPHeaders() {
1690
- const headers = {};
1691
- if (this.cspNonce) {
1692
- headers['Content-Security-Policy'] =
1693
- `script-src 'nonce-${this.cspNonce}'`;
1694
- }
1695
- return headers;
1696
- }
1697
- }
1698
- function deepEscape(value, seen = new WeakSet()) {
1699
- if (value === null || value === undefined) {
1700
- return '';
1701
- }
1702
- if (value instanceof Safe) {
1703
- return `${value}`;
1704
- }
1705
- if (typeof value === 'object') {
1706
- // Guard against circular references
1707
- if (seen.has(value)) {
1708
- return '';
1709
- }
1710
- seen.add(value);
1711
- const values = Array.isArray(value)
1712
- ? value
1713
- : Object.values(value);
1714
- return values.map((v) => deepEscape(v, seen)).join('');
1715
- }
1716
- return escape(value);
1717
- }
1718
- class SecurityAuditor {
1719
- auditTemplate(template) {
1720
- const issues = [];
1721
- // Check for dangerous patterns
1722
- const dangerousPatterns = [
1723
- {
1724
- pattern: /\beval\s*\(/,
1725
- type: 'dangerous-eval',
1726
- message: 'Use of eval() is dangerous and should be avoided',
1727
- severity: 'critical',
1728
- },
1729
- {
1730
- pattern: /\bFunction\s*\(/,
1731
- type: 'dangerous-function',
1732
- message: 'Use of Function constructor is dangerous',
1733
- severity: 'critical',
1734
- },
1735
- {
1736
- pattern: /\brequire\s*\(/,
1737
- type: 'require-usage',
1738
- message: 'Direct require() usage in templates is unsafe',
1739
- severity: 'high',
1740
- },
1741
- {
1742
- pattern: /\bimport\s*\(/,
1743
- type: 'dynamic-import',
1744
- message: 'Dynamic import() usage in templates may be unsafe',
1745
- severity: 'high',
1746
- },
1747
- ];
1748
- for (const { pattern, type, message, severity } of dangerousPatterns) {
1749
- const match = template.match(pattern);
1750
- if (match) {
1751
- issues.push({
1752
- type,
1753
- message,
1754
- location: `at index ${match.index}`,
1755
- severity,
1756
- });
1757
- }
1758
- }
1759
- // Calculate overall severity
1760
- const overallSeverity = this.calculateOverallSeverity(issues);
1761
- return {
1762
- issues,
1763
- severity: overallSeverity,
1764
- };
1765
- }
1766
- calculateOverallSeverity(issues) {
1767
- if (issues.length === 0) {
1768
- return 'low';
1789
+ parseExp({ val, loc }) {
1790
+ try {
1791
+ return this.expParser.parse(val, loc);
1769
1792
  }
1770
- const severityMap = {
1771
- critical: 4,
1772
- high: 3,
1773
- medium: 2,
1774
- low: 1,
1775
- };
1776
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1777
- 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));
1778
1813
  }
1779
1814
  }
1780
1815
 
1781
- const fingerprints = new WeakMap();
1782
- // How deep includes may nest while rendering. Only templates that include
1783
- // themselves get anywhere near it; the limit turns a cycle that never ends
1784
- // into an error instead of a stack overflow.
1785
- const MAX_INCLUDE_DEPTH = 100;
1786
- // Directives whose body is still the template's own top-level output
1787
- const transparent = new Set(['IF', 'FOR']);
1788
- // The template itself is the key: one string that is hashed once, and two
1789
- // different templates can never share an entry
1790
- function templateCacheKey(template, stream = false) {
1791
- return stream ? `\0stream:${template}` : template;
1816
+ function isStringLit(exp) {
1817
+ return exp.type === 'LIT' && typeof exp.value === 'string';
1792
1818
  }
1793
- function optionsFingerprint(options) {
1794
- let fingerprint = fingerprints.get(options);
1795
- if (fingerprint === undefined) {
1796
- const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1797
- // Limits that change the generated code must bust the compile cache
1798
- const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1799
- fingerprint = JSON.stringify([
1800
- trimWhitespace,
1801
- stripComments,
1802
- commentOpen,
1803
- commentClose,
1804
- directiveOpen,
1805
- directiveClose,
1806
- outputOpen,
1807
- outputClose,
1808
- maxIncludeDepth,
1809
- maxLoopIterations ?? null,
1810
- maxCallDepth ?? null,
1811
- ]);
1812
- 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
+ });
1813
1852
  }
1814
- return fingerprint;
1815
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']);
1816
1861
  class Compiler extends Context {
1817
1862
  constructor(options, cache, revalidate = true, stream = false) {
1818
1863
  super();
@@ -1902,6 +1947,13 @@ ${suggestionText}`;
1902
1947
  writable: true,
1903
1948
  value: void 0
1904
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
+ });
1905
1957
  /**
1906
1958
  * Whether the code being generated may write output to the stream. True
1907
1959
  * only in stream mode, for the template's own top-level output.
@@ -1922,6 +1974,7 @@ ${suggestionText}`;
1922
1974
  this.stylesheets = stylesheets;
1923
1975
  this.stylesheetKey = stylesheetKey;
1924
1976
  this.sources = sources;
1977
+ this.hasDynamicInclude = false;
1925
1978
  // Generate cache key from template and options
1926
1979
  const cacheKey = this.generateCacheKey(template);
1927
1980
  // Check cache first
@@ -1947,7 +2000,7 @@ ${suggestionText}`;
1947
2000
  }
1948
2001
  await this.parseTemplates();
1949
2002
  if (this.isRoot) {
1950
- if (this.partials.size) {
2003
+ if (this.partials.size || this.hasDynamicInclude) {
1951
2004
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1952
2005
  // Alias the render data before partials shadow `c` with their argument.
1953
2006
  this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
@@ -2045,6 +2098,17 @@ ${suggestionText}`;
2045
2098
  }
2046
2099
  async parseTemplates() {
2047
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
+ }
2048
2112
  for (const [path, node] of partials) {
2049
2113
  if (!this.partials.has(path)) {
2050
2114
  let template;
@@ -2082,8 +2146,14 @@ ${suggestionText}`;
2082
2146
  const stylesheets = [];
2083
2147
  const traverse = (node) => {
2084
2148
  if (node.type === 'INCLUDE') {
2085
- if (!partials.has(node.val.value)) {
2086
- 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;
2087
2157
  }
2088
2158
  }
2089
2159
  if (node.type === 'BLOCK') {
@@ -2494,6 +2564,7 @@ ${suggestionText}`;
2494
2564
  trimWhitespace: false,
2495
2565
  stripComments: false,
2496
2566
  loader: async () => '',
2567
+ preloadIncludes: [],
2497
2568
  };
2498
2569
  const renderOptions = {
2499
2570
  ...compilerOptions,
@@ -3558,10 +3629,12 @@ ${suggestionText}`;
3558
3629
  parsers: parsers$9,
3559
3630
  };
3560
3631
 
3561
- async function compileInclude({ val: { value }, loc, withExp }, compiler) {
3562
- const path = 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);
3563
3637
  if (withExp) {
3564
- const expCompiler = new ExpCompiler();
3565
3638
  const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3566
3639
  compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3567
3640
  return;
@@ -3573,45 +3646,6 @@ ${suggestionText}`;
3573
3646
  INCLUDE: compileInclude,
3574
3647
  };
3575
3648
 
3576
- class IncludeNode extends Traversal {
3577
- constructor(val, loc, strip, withExp = null) {
3578
- super();
3579
- Object.defineProperty(this, "val", {
3580
- enumerable: true,
3581
- configurable: true,
3582
- writable: true,
3583
- value: val
3584
- });
3585
- Object.defineProperty(this, "loc", {
3586
- enumerable: true,
3587
- configurable: true,
3588
- writable: true,
3589
- value: loc
3590
- });
3591
- Object.defineProperty(this, "strip", {
3592
- enumerable: true,
3593
- configurable: true,
3594
- writable: true,
3595
- value: strip
3596
- });
3597
- Object.defineProperty(this, "withExp", {
3598
- enumerable: true,
3599
- configurable: true,
3600
- writable: true,
3601
- value: withExp
3602
- });
3603
- Object.defineProperty(this, "type", {
3604
- enumerable: true,
3605
- configurable: true,
3606
- writable: true,
3607
- value: 'INCLUDE'
3608
- });
3609
- }
3610
- }
3611
-
3612
- function isStringLit(exp) {
3613
- return exp.type === 'LIT' && typeof exp.value === 'string';
3614
- }
3615
3649
  function* parseInclude(token, parser) {
3616
3650
  if (!token.expression) {
3617
3651
  parser.emitExpErr(token);
@@ -3622,18 +3656,12 @@ ${suggestionText}`;
3622
3656
  if (!exp) {
3623
3657
  return;
3624
3658
  }
3625
- if (isStringLit(exp)) {
3626
- yield new IncludeNode(exp, token.loc, token.strip);
3627
- return;
3628
- }
3629
3659
  if (exp.type === 'WITH') {
3630
3660
  const { left, right } = exp;
3631
- if (isStringLit(left)) {
3632
- yield new IncludeNode(left, token.loc, token.strip, right);
3633
- return;
3634
- }
3661
+ yield new IncludeNode(left, token.loc, token.strip, right);
3662
+ return;
3635
3663
  }
3636
- parser.options.debug?.(new CompileError('"include" expects "path" or "path" with expr', parser.template, token.loc));
3664
+ yield new IncludeNode(exp, token.loc, token.strip);
3637
3665
  }
3638
3666
  const parsers$8 = {
3639
3667
  include: parseInclude,
@@ -3914,14 +3942,18 @@ ${suggestionText}`;
3914
3942
  async function compileStylesheets({ loc }, compiler) {
3915
3943
  compiler.pushRaw(loc,
3916
3944
  // First `stylesheets` wins; later ones are ignored (same idea as blocks).
3917
- '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_();', '}');
3918
3947
  }
3919
3948
  const compilers$4 = {
3920
3949
  STYLESHEET: compileStylesheet,
3921
3950
  STYLESHEETS: compileStylesheets,
3922
3951
  };
3923
3952
 
3924
- /** 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
+ */
3925
3957
  class StylesheetNode extends Traversal {
3926
3958
  constructor(body, loc, strip) {
3927
3959
  super();
@@ -3951,7 +3983,7 @@ ${suggestionText}`;
3951
3983
  });
3952
3984
  }
3953
3985
  }
3954
- /** Emits every collected stylesheet into the document (typically in `<head>`). */
3986
+ /** Concatenates collected stylesheet bodies into the document (typically in `<head>`). */
3955
3987
  class StylesheetsNode extends Traversal {
3956
3988
  constructor(loc, strip) {
3957
3989
  super();
@@ -4669,10 +4701,13 @@ ${suggestionText}`;
4669
4701
  await this.nodes(node.body, scope);
4670
4702
  break;
4671
4703
  case 'INCLUDE':
4704
+ this.exp(node.val, scope);
4672
4705
  if (node.withExp) {
4673
4706
  this.exp(node.withExp, scope);
4674
4707
  }
4675
- await this.include(node.val.value, scope);
4708
+ if (node.val.type === 'LIT' && typeof node.val.value === 'string') {
4709
+ await this.include(node.val.value, scope);
4710
+ }
4676
4711
  break;
4677
4712
  default:
4678
4713
  await this.nodes(node.body, scope);
@@ -5437,6 +5472,149 @@ export default script;
5437
5472
  }
5438
5473
  }
5439
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
+
5440
5618
  /** HTML void elements — never take children, so they do not change indent. */
5441
5619
  const VOID = new Set([
5442
5620
  'area',
@@ -5454,8 +5632,13 @@ export default script;
5454
5632
  'track',
5455
5633
  'wbr',
5456
5634
  ]);
5457
- /** 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
+ */
5458
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']);
5459
5642
  const DIR_OPEN = new Set([
5460
5643
  'if',
5461
5644
  'for',
@@ -5482,8 +5665,9 @@ export default script;
5482
5665
  /**
5483
5666
  * Reindent a template that already had its Janja tags normalised.
5484
5667
  * Only leading whitespace on each line changes; line breaks and
5485
- * intra-line spacing stay put. Content inside pre/textarea/script/style
5486
- * 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).
5487
5671
  */
5488
5672
  function indentHtml(source, options) {
5489
5673
  const tabWidth = options.tabWidth ?? 2;
@@ -5492,6 +5676,8 @@ export default script;
5492
5676
  const lines = source.split(/\r?\n/);
5493
5677
  let depth = 0;
5494
5678
  let sensitive = null;
5679
+ /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5680
+ let bodyBuf = null;
5495
5681
  const out = [];
5496
5682
  for (const line of lines) {
5497
5683
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
@@ -5500,7 +5686,28 @@ export default script;
5500
5686
  const activeSensitive = sensitive;
5501
5687
  const closesSensitive = activeSensitive !== null &&
5502
5688
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5503
- 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) {
5504
5711
  out.push(line);
5505
5712
  applyDepth(pieces);
5506
5713
  continue;