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.esm.js CHANGED
@@ -334,6 +334,224 @@ class CompileError extends SyntaxError {
334
334
  }
335
335
  }
336
336
 
337
+ const special = /[&<>"']/;
338
+ const specials = /[&<>"']/g;
339
+ const entities = {
340
+ '&': '&amp;',
341
+ '"': '&#34;',
342
+ "'": '&#39;',
343
+ '<': '&lt;',
344
+ '>': '&gt;',
345
+ };
346
+ const entity = (char) => entities[char];
347
+ function escape(v) {
348
+ const str = typeof v === 'string' ? v : `${v}`;
349
+ // Most values contain nothing to escape; they are returned as they are,
350
+ // without allocating
351
+ return special.test(str) ? str.replace(specials, entity) : str;
352
+ }
353
+
354
+ class Safe extends String {
355
+ constructor(value) {
356
+ super(`${value}`);
357
+ }
358
+ }
359
+
360
+ /** Defaults and resolved limits used by the compiler and renderer. */
361
+ function resolveSecurityLimits(security = {}) {
362
+ return {
363
+ maxIncludeDepth: security.maxIncludeDepth ?? 100,
364
+ maxLoopIterations: security.maxLoopIterations,
365
+ maxCallDepth: security.maxCallDepth,
366
+ timeoutMs: security.timeoutMs,
367
+ };
368
+ }
369
+ class SecuritySandbox {
370
+ constructor(options = {}) {
371
+ Object.defineProperty(this, "allowedGlobals", {
372
+ enumerable: true,
373
+ configurable: true,
374
+ writable: true,
375
+ value: void 0
376
+ });
377
+ Object.defineProperty(this, "cspNonce", {
378
+ enumerable: true,
379
+ configurable: true,
380
+ writable: true,
381
+ value: void 0
382
+ });
383
+ this.allowedGlobals = new Set(options.allowedGlobals || []);
384
+ this.cspNonce = options.cspNonce;
385
+ }
386
+ sanitizeGlobals(globals) {
387
+ const sanitized = {};
388
+ for (const [key, value] of Object.entries(globals)) {
389
+ if (this.allowedGlobals.has(key)) {
390
+ sanitized[key] = value;
391
+ }
392
+ }
393
+ return sanitized;
394
+ }
395
+ validateExpression(expression) {
396
+ // Prevent access to dangerous globals
397
+ const dangerousPatterns = [
398
+ /\bprocess\b/,
399
+ /\brequire\b/,
400
+ /\bimport\b/,
401
+ /\bexport\b/,
402
+ /\beval\b/,
403
+ /\bFunction\b/,
404
+ /\b__proto__\b/,
405
+ /\bconstructor\b/,
406
+ ];
407
+ for (const pattern of dangerousPatterns) {
408
+ if (pattern.test(expression)) {
409
+ return false;
410
+ }
411
+ }
412
+ return true;
413
+ }
414
+ createSecureContext(globals) {
415
+ const sanitized = this.sanitizeGlobals(globals);
416
+ // Add safe utility functions
417
+ return {
418
+ ...sanitized,
419
+ Math,
420
+ Date,
421
+ JSON,
422
+ // Add other safe built-ins as needed
423
+ };
424
+ }
425
+ getCSPNonce() {
426
+ return this.cspNonce;
427
+ }
428
+ generateCSPHeaders() {
429
+ const headers = {};
430
+ if (this.cspNonce) {
431
+ headers['Content-Security-Policy'] =
432
+ `script-src 'nonce-${this.cspNonce}'`;
433
+ }
434
+ return headers;
435
+ }
436
+ }
437
+ function deepEscape(value, seen = new WeakSet()) {
438
+ if (value === null || value === undefined) {
439
+ return '';
440
+ }
441
+ if (value instanceof Safe) {
442
+ return `${value}`;
443
+ }
444
+ if (typeof value === 'object') {
445
+ // Guard against circular references
446
+ if (seen.has(value)) {
447
+ return '';
448
+ }
449
+ seen.add(value);
450
+ const values = Array.isArray(value)
451
+ ? value
452
+ : Object.values(value);
453
+ return values.map((v) => deepEscape(v, seen)).join('');
454
+ }
455
+ return escape(value);
456
+ }
457
+ class SecurityAuditor {
458
+ auditTemplate(template) {
459
+ const issues = [];
460
+ // Check for dangerous patterns
461
+ const dangerousPatterns = [
462
+ {
463
+ pattern: /\beval\s*\(/,
464
+ type: 'dangerous-eval',
465
+ message: 'Use of eval() is dangerous and should be avoided',
466
+ severity: 'critical',
467
+ },
468
+ {
469
+ pattern: /\bFunction\s*\(/,
470
+ type: 'dangerous-function',
471
+ message: 'Use of Function constructor is dangerous',
472
+ severity: 'critical',
473
+ },
474
+ {
475
+ pattern: /\brequire\s*\(/,
476
+ type: 'require-usage',
477
+ message: 'Direct require() usage in templates is unsafe',
478
+ severity: 'high',
479
+ },
480
+ {
481
+ pattern: /\bimport\s*\(/,
482
+ type: 'dynamic-import',
483
+ message: 'Dynamic import() usage in templates may be unsafe',
484
+ severity: 'high',
485
+ },
486
+ ];
487
+ for (const { pattern, type, message, severity } of dangerousPatterns) {
488
+ const match = template.match(pattern);
489
+ if (match) {
490
+ issues.push({
491
+ type,
492
+ message,
493
+ location: `at index ${match.index}`,
494
+ severity,
495
+ });
496
+ }
497
+ }
498
+ // Calculate overall severity
499
+ const overallSeverity = this.calculateOverallSeverity(issues);
500
+ return {
501
+ issues,
502
+ severity: overallSeverity,
503
+ };
504
+ }
505
+ calculateOverallSeverity(issues) {
506
+ if (issues.length === 0) {
507
+ return 'low';
508
+ }
509
+ const severityMap = {
510
+ critical: 4,
511
+ high: 3,
512
+ medium: 2,
513
+ low: 1,
514
+ };
515
+ const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
516
+ return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
517
+ }
518
+ }
519
+
520
+ const fingerprints = new WeakMap();
521
+ // How deep includes may nest while rendering. Only templates that include
522
+ // themselves get anywhere near it; the limit turns a cycle that never ends
523
+ // into an error instead of a stack overflow.
524
+ const MAX_INCLUDE_DEPTH = 100;
525
+ // The template itself is the key: one string that is hashed once, and two
526
+ // different templates can never share an entry
527
+ function templateCacheKey(template, stream = false) {
528
+ return stream ? `\0stream:${template}` : template;
529
+ }
530
+ function optionsFingerprint(options) {
531
+ let fingerprint = fingerprints.get(options);
532
+ if (fingerprint === undefined) {
533
+ const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, preloadIncludes, } = options;
534
+ // Limits that change the generated code must bust the compile cache
535
+ const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
536
+ fingerprint = JSON.stringify([
537
+ trimWhitespace,
538
+ stripComments,
539
+ commentOpen,
540
+ commentClose,
541
+ directiveOpen,
542
+ directiveClose,
543
+ outputOpen,
544
+ outputClose,
545
+ maxIncludeDepth,
546
+ maxLoopIterations ?? null,
547
+ maxCallDepth ?? null,
548
+ preloadIncludes,
549
+ ]);
550
+ fingerprints.set(options, fingerprint);
551
+ }
552
+ return fingerprint;
553
+ }
554
+
337
555
  const CONTEXT = 'c';
338
556
  const ESCAPE = 'e';
339
557
  const FILTERS = 'f';
@@ -1565,251 +1783,78 @@ class Parser extends Tokenizer {
1565
1783
  }
1566
1784
  return nodes;
1567
1785
  }
1568
- parseExp({ val, loc }) {
1569
- try {
1570
- return this.expParser.parse(val, loc);
1571
- }
1572
- catch (error) {
1573
- this.options.debug(error.loc
1574
- ? new CompileError(error.message, this.template, error.loc)
1575
- : error);
1576
- }
1577
- }
1578
- peek() {
1579
- return this.tokens.at(this.cursor) ?? null;
1580
- }
1581
- advance() {
1582
- this.cursor++;
1583
- }
1584
- match(names, token = this.peek()) {
1585
- // Directive names are case-insensitive, like the lookup of their parser
1586
- return names.includes(token?.name?.toLowerCase());
1587
- }
1588
- emitExpErr({ name, loc }, required = true) {
1589
- this.options.debug(new CompileError(required
1590
- ? `"${name}" requires expression`
1591
- : `"${name}" should not have expression`, this.template, loc));
1592
- }
1593
- }
1594
-
1595
- const special = /[&<>"']/;
1596
- const specials = /[&<>"']/g;
1597
- const entities = {
1598
- '&': '&amp;',
1599
- '"': '&#34;',
1600
- "'": '&#39;',
1601
- '<': '&lt;',
1602
- '>': '&gt;',
1603
- };
1604
- const entity = (char) => entities[char];
1605
- function escape(v) {
1606
- const str = typeof v === 'string' ? v : `${v}`;
1607
- // Most values contain nothing to escape; they are returned as they are,
1608
- // without allocating
1609
- return special.test(str) ? str.replace(specials, entity) : str;
1610
- }
1611
-
1612
- class Safe extends String {
1613
- constructor(value) {
1614
- super(`${value}`);
1615
- }
1616
- }
1617
-
1618
- /** Defaults and resolved limits used by the compiler and renderer. */
1619
- function resolveSecurityLimits(security = {}) {
1620
- return {
1621
- maxIncludeDepth: security.maxIncludeDepth ?? 100,
1622
- maxLoopIterations: security.maxLoopIterations,
1623
- maxCallDepth: security.maxCallDepth,
1624
- timeoutMs: security.timeoutMs,
1625
- };
1626
- }
1627
- class SecuritySandbox {
1628
- constructor(options = {}) {
1629
- Object.defineProperty(this, "allowedGlobals", {
1630
- enumerable: true,
1631
- configurable: true,
1632
- writable: true,
1633
- value: void 0
1634
- });
1635
- Object.defineProperty(this, "cspNonce", {
1636
- enumerable: true,
1637
- configurable: true,
1638
- writable: true,
1639
- value: void 0
1640
- });
1641
- this.allowedGlobals = new Set(options.allowedGlobals || []);
1642
- this.cspNonce = options.cspNonce;
1643
- }
1644
- sanitizeGlobals(globals) {
1645
- const sanitized = {};
1646
- for (const [key, value] of Object.entries(globals)) {
1647
- if (this.allowedGlobals.has(key)) {
1648
- sanitized[key] = value;
1649
- }
1650
- }
1651
- return sanitized;
1652
- }
1653
- validateExpression(expression) {
1654
- // Prevent access to dangerous globals
1655
- const dangerousPatterns = [
1656
- /\bprocess\b/,
1657
- /\brequire\b/,
1658
- /\bimport\b/,
1659
- /\bexport\b/,
1660
- /\beval\b/,
1661
- /\bFunction\b/,
1662
- /\b__proto__\b/,
1663
- /\bconstructor\b/,
1664
- ];
1665
- for (const pattern of dangerousPatterns) {
1666
- if (pattern.test(expression)) {
1667
- return false;
1668
- }
1669
- }
1670
- return true;
1671
- }
1672
- createSecureContext(globals) {
1673
- const sanitized = this.sanitizeGlobals(globals);
1674
- // Add safe utility functions
1675
- return {
1676
- ...sanitized,
1677
- Math,
1678
- Date,
1679
- JSON,
1680
- // Add other safe built-ins as needed
1681
- };
1682
- }
1683
- getCSPNonce() {
1684
- return this.cspNonce;
1685
- }
1686
- generateCSPHeaders() {
1687
- const headers = {};
1688
- if (this.cspNonce) {
1689
- headers['Content-Security-Policy'] =
1690
- `script-src 'nonce-${this.cspNonce}'`;
1691
- }
1692
- return headers;
1693
- }
1694
- }
1695
- function deepEscape(value, seen = new WeakSet()) {
1696
- if (value === null || value === undefined) {
1697
- return '';
1698
- }
1699
- if (value instanceof Safe) {
1700
- return `${value}`;
1701
- }
1702
- if (typeof value === 'object') {
1703
- // Guard against circular references
1704
- if (seen.has(value)) {
1705
- return '';
1706
- }
1707
- seen.add(value);
1708
- const values = Array.isArray(value)
1709
- ? value
1710
- : Object.values(value);
1711
- return values.map((v) => deepEscape(v, seen)).join('');
1712
- }
1713
- return escape(value);
1714
- }
1715
- class SecurityAuditor {
1716
- auditTemplate(template) {
1717
- const issues = [];
1718
- // Check for dangerous patterns
1719
- const dangerousPatterns = [
1720
- {
1721
- pattern: /\beval\s*\(/,
1722
- type: 'dangerous-eval',
1723
- message: 'Use of eval() is dangerous and should be avoided',
1724
- severity: 'critical',
1725
- },
1726
- {
1727
- pattern: /\bFunction\s*\(/,
1728
- type: 'dangerous-function',
1729
- message: 'Use of Function constructor is dangerous',
1730
- severity: 'critical',
1731
- },
1732
- {
1733
- pattern: /\brequire\s*\(/,
1734
- type: 'require-usage',
1735
- message: 'Direct require() usage in templates is unsafe',
1736
- severity: 'high',
1737
- },
1738
- {
1739
- pattern: /\bimport\s*\(/,
1740
- type: 'dynamic-import',
1741
- message: 'Dynamic import() usage in templates may be unsafe',
1742
- severity: 'high',
1743
- },
1744
- ];
1745
- for (const { pattern, type, message, severity } of dangerousPatterns) {
1746
- const match = template.match(pattern);
1747
- if (match) {
1748
- issues.push({
1749
- type,
1750
- message,
1751
- location: `at index ${match.index}`,
1752
- severity,
1753
- });
1754
- }
1755
- }
1756
- // Calculate overall severity
1757
- const overallSeverity = this.calculateOverallSeverity(issues);
1758
- return {
1759
- issues,
1760
- severity: overallSeverity,
1761
- };
1762
- }
1763
- calculateOverallSeverity(issues) {
1764
- if (issues.length === 0) {
1765
- return 'low';
1786
+ parseExp({ val, loc }) {
1787
+ try {
1788
+ return this.expParser.parse(val, loc);
1766
1789
  }
1767
- const severityMap = {
1768
- critical: 4,
1769
- high: 3,
1770
- medium: 2,
1771
- low: 1,
1772
- };
1773
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1774
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
1790
+ catch (error) {
1791
+ this.options.debug(error.loc
1792
+ ? new CompileError(error.message, this.template, error.loc)
1793
+ : error);
1794
+ }
1795
+ }
1796
+ peek() {
1797
+ return this.tokens.at(this.cursor) ?? null;
1798
+ }
1799
+ advance() {
1800
+ this.cursor++;
1801
+ }
1802
+ match(names, token = this.peek()) {
1803
+ // Directive names are case-insensitive, like the lookup of their parser
1804
+ return names.includes(token?.name?.toLowerCase());
1805
+ }
1806
+ emitExpErr({ name, loc }, required = true) {
1807
+ this.options.debug(new CompileError(required
1808
+ ? `"${name}" requires expression`
1809
+ : `"${name}" should not have expression`, this.template, loc));
1775
1810
  }
1776
1811
  }
1777
1812
 
1778
- const fingerprints = new WeakMap();
1779
- // How deep includes may nest while rendering. Only templates that include
1780
- // themselves get anywhere near it; the limit turns a cycle that never ends
1781
- // into an error instead of a stack overflow.
1782
- const MAX_INCLUDE_DEPTH = 100;
1783
- // Directives whose body is still the template's own top-level output
1784
- const transparent = new Set(['IF', 'FOR']);
1785
- // The template itself is the key: one string that is hashed once, and two
1786
- // different templates can never share an entry
1787
- function templateCacheKey(template, stream = false) {
1788
- return stream ? `\0stream:${template}` : template;
1813
+ function isStringLit(exp) {
1814
+ return exp.type === 'LIT' && typeof exp.value === 'string';
1789
1815
  }
1790
- function optionsFingerprint(options) {
1791
- let fingerprint = fingerprints.get(options);
1792
- if (fingerprint === undefined) {
1793
- const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1794
- // Limits that change the generated code must bust the compile cache
1795
- const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1796
- fingerprint = JSON.stringify([
1797
- trimWhitespace,
1798
- stripComments,
1799
- commentOpen,
1800
- commentClose,
1801
- directiveOpen,
1802
- directiveClose,
1803
- outputOpen,
1804
- outputClose,
1805
- maxIncludeDepth,
1806
- maxLoopIterations ?? null,
1807
- maxCallDepth ?? null,
1808
- ]);
1809
- fingerprints.set(options, fingerprint);
1816
+ class IncludeNode extends Traversal {
1817
+ constructor(val, loc, strip, withExp = null) {
1818
+ super();
1819
+ Object.defineProperty(this, "val", {
1820
+ enumerable: true,
1821
+ configurable: true,
1822
+ writable: true,
1823
+ value: val
1824
+ });
1825
+ Object.defineProperty(this, "loc", {
1826
+ enumerable: true,
1827
+ configurable: true,
1828
+ writable: true,
1829
+ value: loc
1830
+ });
1831
+ Object.defineProperty(this, "strip", {
1832
+ enumerable: true,
1833
+ configurable: true,
1834
+ writable: true,
1835
+ value: strip
1836
+ });
1837
+ Object.defineProperty(this, "withExp", {
1838
+ enumerable: true,
1839
+ configurable: true,
1840
+ writable: true,
1841
+ value: withExp
1842
+ });
1843
+ Object.defineProperty(this, "type", {
1844
+ enumerable: true,
1845
+ configurable: true,
1846
+ writable: true,
1847
+ value: 'INCLUDE'
1848
+ });
1810
1849
  }
1811
- return fingerprint;
1812
1850
  }
1851
+
1852
+ const PRELOAD_LOC = {
1853
+ start: { line: 1, column: 1 },
1854
+ end: { line: 1, column: 1 },
1855
+ };
1856
+ // Directives whose body is still the template's own top-level output
1857
+ const transparent = new Set(['IF', 'FOR']);
1813
1858
  class Compiler extends Context {
1814
1859
  constructor(options, cache, revalidate = true, stream = false) {
1815
1860
  super();
@@ -1899,6 +1944,13 @@ class Compiler extends Context {
1899
1944
  writable: true,
1900
1945
  value: void 0
1901
1946
  });
1947
+ /** True when the template uses a non-literal include path. */
1948
+ Object.defineProperty(this, "hasDynamicInclude", {
1949
+ enumerable: true,
1950
+ configurable: true,
1951
+ writable: true,
1952
+ value: false
1953
+ });
1902
1954
  /**
1903
1955
  * Whether the code being generated may write output to the stream. True
1904
1956
  * only in stream mode, for the template's own top-level output.
@@ -1919,6 +1971,7 @@ class Compiler extends Context {
1919
1971
  this.stylesheets = stylesheets;
1920
1972
  this.stylesheetKey = stylesheetKey;
1921
1973
  this.sources = sources;
1974
+ this.hasDynamicInclude = false;
1922
1975
  // Generate cache key from template and options
1923
1976
  const cacheKey = this.generateCacheKey(template);
1924
1977
  // Check cache first
@@ -1944,7 +1997,7 @@ class Compiler extends Context {
1944
1997
  }
1945
1998
  await this.parseTemplates();
1946
1999
  if (this.isRoot) {
1947
- if (this.partials.size) {
2000
+ if (this.partials.size || this.hasDynamicInclude) {
1948
2001
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1949
2002
  // Alias the render data before partials shadow `c` with their argument.
1950
2003
  this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
@@ -2042,6 +2095,17 @@ class Compiler extends Context {
2042
2095
  }
2043
2096
  async parseTemplates() {
2044
2097
  const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
2098
+ if (this.isRoot) {
2099
+ for (const path of this.options.preloadIncludes) {
2100
+ if (!partials.has(path)) {
2101
+ partials.set(path, new IncludeNode({
2102
+ type: 'LIT',
2103
+ value: path,
2104
+ loc: PRELOAD_LOC,
2105
+ }, PRELOAD_LOC, { before: false, after: false }));
2106
+ }
2107
+ }
2108
+ }
2045
2109
  for (const [path, node] of partials) {
2046
2110
  if (!this.partials.has(path)) {
2047
2111
  let template;
@@ -2079,8 +2143,14 @@ class Compiler extends Context {
2079
2143
  const stylesheets = [];
2080
2144
  const traverse = (node) => {
2081
2145
  if (node.type === 'INCLUDE') {
2082
- if (!partials.has(node.val.value)) {
2083
- partials.set(node.val.value, node);
2146
+ const include = node;
2147
+ if (isStringLit(include.val)) {
2148
+ if (!partials.has(include.val.value)) {
2149
+ partials.set(include.val.value, include);
2150
+ }
2151
+ }
2152
+ else {
2153
+ this.hasDynamicInclude = true;
2084
2154
  }
2085
2155
  }
2086
2156
  if (node.type === 'BLOCK') {
@@ -2491,6 +2561,7 @@ const compilerOptions = {
2491
2561
  trimWhitespace: false,
2492
2562
  stripComments: false,
2493
2563
  loader: async () => '',
2564
+ preloadIncludes: [],
2494
2565
  };
2495
2566
  const renderOptions = {
2496
2567
  ...compilerOptions,
@@ -3555,10 +3626,12 @@ const plugin$9 = {
3555
3626
  parsers: parsers$9,
3556
3627
  };
3557
3628
 
3558
- async function compileInclude({ val: { value }, loc, withExp }, compiler) {
3559
- const path = JSON.stringify(value);
3629
+ async function compileInclude({ val, loc, withExp }, compiler) {
3630
+ const expCompiler = new ExpCompiler();
3631
+ const path = isStringLit(val)
3632
+ ? JSON.stringify(val.value)
3633
+ : expCompiler.compile(val, compiler.context);
3560
3634
  if (withExp) {
3561
- const expCompiler = new ExpCompiler();
3562
3635
  const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3563
3636
  compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3564
3637
  return;
@@ -3570,45 +3643,6 @@ const compilers$8 = {
3570
3643
  INCLUDE: compileInclude,
3571
3644
  };
3572
3645
 
3573
- class IncludeNode extends Traversal {
3574
- constructor(val, loc, strip, withExp = null) {
3575
- super();
3576
- Object.defineProperty(this, "val", {
3577
- enumerable: true,
3578
- configurable: true,
3579
- writable: true,
3580
- value: val
3581
- });
3582
- Object.defineProperty(this, "loc", {
3583
- enumerable: true,
3584
- configurable: true,
3585
- writable: true,
3586
- value: loc
3587
- });
3588
- Object.defineProperty(this, "strip", {
3589
- enumerable: true,
3590
- configurable: true,
3591
- writable: true,
3592
- value: strip
3593
- });
3594
- Object.defineProperty(this, "withExp", {
3595
- enumerable: true,
3596
- configurable: true,
3597
- writable: true,
3598
- value: withExp
3599
- });
3600
- Object.defineProperty(this, "type", {
3601
- enumerable: true,
3602
- configurable: true,
3603
- writable: true,
3604
- value: 'INCLUDE'
3605
- });
3606
- }
3607
- }
3608
-
3609
- function isStringLit(exp) {
3610
- return exp.type === 'LIT' && typeof exp.value === 'string';
3611
- }
3612
3646
  function* parseInclude(token, parser) {
3613
3647
  if (!token.expression) {
3614
3648
  parser.emitExpErr(token);
@@ -3619,18 +3653,12 @@ function* parseInclude(token, parser) {
3619
3653
  if (!exp) {
3620
3654
  return;
3621
3655
  }
3622
- if (isStringLit(exp)) {
3623
- yield new IncludeNode(exp, token.loc, token.strip);
3624
- return;
3625
- }
3626
3656
  if (exp.type === 'WITH') {
3627
3657
  const { left, right } = exp;
3628
- if (isStringLit(left)) {
3629
- yield new IncludeNode(left, token.loc, token.strip, right);
3630
- return;
3631
- }
3658
+ yield new IncludeNode(left, token.loc, token.strip, right);
3659
+ return;
3632
3660
  }
3633
- parser.options.debug?.(new CompileError('"include" expects "path" or "path" with expr', parser.template, token.loc));
3661
+ yield new IncludeNode(exp, token.loc, token.strip);
3634
3662
  }
3635
3663
  const parsers$8 = {
3636
3664
  include: parseInclude,
@@ -3911,14 +3939,18 @@ async function compileStylesheet() {
3911
3939
  async function compileStylesheets({ loc }, compiler) {
3912
3940
  compiler.pushRaw(loc,
3913
3941
  // First `stylesheets` wins; later ones are ignored (same idea as blocks).
3914
- 'if(!ss_u++){', 's+="<style>";', 'for(const f_ of ss_)s+=await f_();', 's+="</style>";', '}');
3942
+ // Bodies are emitted as-is — authors wrap CSS in `<style>` for IDE highlighting.
3943
+ 'if(!ss_u++){', 'for(const f_ of ss_)s+=await f_();', '}');
3915
3944
  }
3916
3945
  const compilers$4 = {
3917
3946
  STYLESHEET: compileStylesheet,
3918
3947
  STYLESHEETS: compileStylesheets,
3919
3948
  };
3920
3949
 
3921
- /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
3950
+ /**
3951
+ * Co-located styles with a section/snippet (Shopify `{% stylesheet %}` analogue).
3952
+ * Body is usually a `<style>…</style>` block for native IDE CSS highlighting.
3953
+ */
3922
3954
  class StylesheetNode extends Traversal {
3923
3955
  constructor(body, loc, strip) {
3924
3956
  super();
@@ -3948,7 +3980,7 @@ class StylesheetNode extends Traversal {
3948
3980
  });
3949
3981
  }
3950
3982
  }
3951
- /** Emits every collected stylesheet into the document (typically in `<head>`). */
3983
+ /** Concatenates collected stylesheet bodies into the document (typically in `<head>`). */
3952
3984
  class StylesheetsNode extends Traversal {
3953
3985
  constructor(loc, strip) {
3954
3986
  super();
@@ -4666,10 +4698,13 @@ class Analyzer {
4666
4698
  await this.nodes(node.body, scope);
4667
4699
  break;
4668
4700
  case 'INCLUDE':
4701
+ this.exp(node.val, scope);
4669
4702
  if (node.withExp) {
4670
4703
  this.exp(node.withExp, scope);
4671
4704
  }
4672
- await this.include(node.val.value, scope);
4705
+ if (node.val.type === 'LIT' && typeof node.val.value === 'string') {
4706
+ await this.include(node.val.value, scope);
4707
+ }
4673
4708
  break;
4674
4709
  default:
4675
4710
  await this.nodes(node.body, scope);
@@ -5434,6 +5469,149 @@ class ExpFormatter {
5434
5469
  }
5435
5470
  }
5436
5471
 
5472
+ /**
5473
+ * Brace-depth reindent for co-located CSS. Only leading whitespace changes;
5474
+ * braces inside strings/comments are ignored.
5475
+ */
5476
+ function indentCss(source, tabWidth) {
5477
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5478
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5479
+ const lines = source.split(/\r?\n/);
5480
+ let depth = 0;
5481
+ const out = [];
5482
+ for (const line of lines) {
5483
+ const content = line.trim();
5484
+ if (content.length === 0) {
5485
+ out.push('');
5486
+ continue;
5487
+ }
5488
+ const { opens, closes } = countCssBraces(content);
5489
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5490
+ out.push(pad.repeat(lineDepth) + content);
5491
+ depth = Math.max(0, depth + opens - closes);
5492
+ }
5493
+ return out.join(eol);
5494
+ }
5495
+ function countCssBraces(line) {
5496
+ let opens = 0;
5497
+ let closes = 0;
5498
+ let quote = null;
5499
+ let i = 0;
5500
+ while (i < line.length) {
5501
+ const c = line[i];
5502
+ if (quote) {
5503
+ if (c === '\\') {
5504
+ i += 2;
5505
+ continue;
5506
+ }
5507
+ if (c === quote) {
5508
+ quote = null;
5509
+ }
5510
+ i += 1;
5511
+ continue;
5512
+ }
5513
+ if (c === '"' || c === "'") {
5514
+ quote = c;
5515
+ i += 1;
5516
+ continue;
5517
+ }
5518
+ if (c === '/' && line[i + 1] === '*') {
5519
+ const end = line.indexOf('*/', i + 2);
5520
+ i = end === -1 ? line.length : end + 2;
5521
+ continue;
5522
+ }
5523
+ if (c === '/' && line[i + 1] === '/') {
5524
+ break;
5525
+ }
5526
+ if (c === '{') {
5527
+ opens += 1;
5528
+ }
5529
+ else if (c === '}') {
5530
+ closes += 1;
5531
+ }
5532
+ i += 1;
5533
+ }
5534
+ return { opens, closes };
5535
+ }
5536
+
5537
+ /**
5538
+ * Brace-depth reindent for `<script>` bodies. Only leading whitespace changes;
5539
+ * braces inside strings, comments, template literals, and Janja tags are ignored.
5540
+ */
5541
+ function indentJs(source, tabWidth) {
5542
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5543
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5544
+ const lines = source.split(/\r?\n/);
5545
+ let depth = 0;
5546
+ const out = [];
5547
+ for (const line of lines) {
5548
+ const content = line.trim();
5549
+ if (content.length === 0) {
5550
+ out.push('');
5551
+ continue;
5552
+ }
5553
+ const { opens, closes } = countJsBraces(content);
5554
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5555
+ out.push(pad.repeat(lineDepth) + content);
5556
+ depth = Math.max(0, depth + opens - closes);
5557
+ }
5558
+ return out.join(eol);
5559
+ }
5560
+ function countJsBraces(line) {
5561
+ let opens = 0;
5562
+ let closes = 0;
5563
+ let quote = null;
5564
+ let i = 0;
5565
+ while (i < line.length) {
5566
+ const c = line[i];
5567
+ if (quote) {
5568
+ if (c === '\\') {
5569
+ i += 2;
5570
+ continue;
5571
+ }
5572
+ if (c === quote) {
5573
+ quote = null;
5574
+ }
5575
+ i += 1;
5576
+ continue;
5577
+ }
5578
+ if (c === '{' && line[i + 1] === '{') {
5579
+ i = endOfJanja(line, i);
5580
+ continue;
5581
+ }
5582
+ if (c === '"' || c === "'" || c === '`') {
5583
+ quote = c;
5584
+ i += 1;
5585
+ continue;
5586
+ }
5587
+ if (c === '/' && line[i + 1] === '*') {
5588
+ const end = line.indexOf('*/', i + 2);
5589
+ i = end === -1 ? line.length : end + 2;
5590
+ continue;
5591
+ }
5592
+ if (c === '/' && line[i + 1] === '/') {
5593
+ break;
5594
+ }
5595
+ if (c === '{') {
5596
+ opens += 1;
5597
+ }
5598
+ else if (c === '}') {
5599
+ closes += 1;
5600
+ }
5601
+ i += 1;
5602
+ }
5603
+ return { opens, closes };
5604
+ }
5605
+ /** Skip a Janja tag starting at `i` (`{{`, `{{=`, `{{#` …). */
5606
+ function endOfJanja(line, i) {
5607
+ if (line.startsWith('{{#', i)) {
5608
+ const end = line.indexOf('#}}', i + 3);
5609
+ return end === -1 ? line.length : end + 3;
5610
+ }
5611
+ const end = line.indexOf('}}', i + 2);
5612
+ return end === -1 ? line.length : end + 2;
5613
+ }
5614
+
5437
5615
  /** HTML void elements — never take children, so they do not change indent. */
5438
5616
  const VOID = new Set([
5439
5617
  'area',
@@ -5451,8 +5629,13 @@ const VOID = new Set([
5451
5629
  'track',
5452
5630
  'wbr',
5453
5631
  ]);
5454
- /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5632
+ /**
5633
+ * Mark open/close so the body can be buffered. `pre` / `textarea` keep
5634
+ * whitespace; `script` / `style` are reindented (see body buffer below).
5635
+ */
5455
5636
  const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5637
+ /** HTML elements whose bodies are reindented (not left raw). */
5638
+ const REINDENT_HTML = new Set(['script', 'style']);
5456
5639
  const DIR_OPEN = new Set([
5457
5640
  'if',
5458
5641
  'for',
@@ -5479,8 +5662,9 @@ const DIR_CLOSE = new Set([
5479
5662
  /**
5480
5663
  * Reindent a template that already had its Janja tags normalised.
5481
5664
  * Only leading whitespace on each line changes; line breaks and
5482
- * intra-line spacing stay put. Content inside pre/textarea/script/style
5483
- * is left alone; the closing tag of those elements is still reindented.
5665
+ * intra-line spacing stay put. Content inside pre/textarea is left alone;
5666
+ * `script` / `style` bodies are brace-reindented; `stylesheet` bodies are
5667
+ * formatted as an HTML fragment (so nested `<style>` gets CSS indent).
5484
5668
  */
5485
5669
  function indentHtml(source, options) {
5486
5670
  const tabWidth = options.tabWidth ?? 2;
@@ -5489,6 +5673,8 @@ function indentHtml(source, options) {
5489
5673
  const lines = source.split(/\r?\n/);
5490
5674
  let depth = 0;
5491
5675
  let sensitive = null;
5676
+ /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5677
+ let bodyBuf = null;
5492
5678
  const out = [];
5493
5679
  for (const line of lines) {
5494
5680
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
@@ -5497,7 +5683,28 @@ function indentHtml(source, options) {
5497
5683
  const activeSensitive = sensitive;
5498
5684
  const closesSensitive = activeSensitive !== null &&
5499
5685
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5500
- if (sensitive && !closesSensitive) {
5686
+ const reindentBody = activeSensitive === 'stylesheet' ||
5687
+ (activeSensitive !== null && REINDENT_HTML.has(activeSensitive));
5688
+ if (reindentBody && !closesSensitive) {
5689
+ // Do not applyDepth: bodies may contain nested Janja if/for tags.
5690
+ (bodyBuf ?? (bodyBuf = [])).push(line);
5691
+ continue;
5692
+ }
5693
+ if (bodyBuf && closesSensitive && reindentBody) {
5694
+ // stylesheet: same column as the tags; script/style: one level inside.
5695
+ const baseDepth = activeSensitive === 'stylesheet' ? Math.max(0, depth - 1) : depth;
5696
+ const raw = bodyBuf.join(eol);
5697
+ const formatted = activeSensitive === 'stylesheet'
5698
+ ? indentHtml(raw, options)
5699
+ : activeSensitive === 'style'
5700
+ ? indentCss(raw, tabWidth)
5701
+ : indentJs(raw, tabWidth);
5702
+ for (const bodyLine of formatted.split(/\r?\n/)) {
5703
+ out.push(bodyLine.length === 0 ? '' : pad.repeat(baseDepth) + bodyLine);
5704
+ }
5705
+ bodyBuf = null;
5706
+ }
5707
+ else if (sensitive && !closesSensitive) {
5501
5708
  out.push(line);
5502
5709
  applyDepth(pieces);
5503
5710
  continue;