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