janja 4.3.0 → 4.5.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';
@@ -1577,241 +1795,74 @@ class Parser extends Tokenizer {
1577
1795
  : error);
1578
1796
  }
1579
1797
  }
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';
1768
- }
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];
1777
- }
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));
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, modifier = 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, "modifier", {
1846
+ enumerable: true,
1847
+ configurable: true,
1848
+ writable: true,
1849
+ value: modifier
1850
+ });
1851
+ Object.defineProperty(this, "type", {
1852
+ enumerable: true,
1853
+ configurable: true,
1854
+ writable: true,
1855
+ value: 'INCLUDE'
1856
+ });
1812
1857
  }
1813
- return fingerprint;
1814
1858
  }
1859
+
1860
+ const PRELOAD_LOC = {
1861
+ start: { line: 1, column: 1 },
1862
+ end: { line: 1, column: 1 },
1863
+ };
1864
+ // Directives whose body is still the template's own top-level output
1865
+ const transparent = new Set(['IF', 'FOR']);
1815
1866
  class Compiler extends Context {
1816
1867
  constructor(options, cache, revalidate = true, stream = false) {
1817
1868
  super();
@@ -1901,6 +1952,13 @@ class Compiler extends Context {
1901
1952
  writable: true,
1902
1953
  value: void 0
1903
1954
  });
1955
+ /** True when the template uses a non-literal include path. */
1956
+ Object.defineProperty(this, "hasDynamicInclude", {
1957
+ enumerable: true,
1958
+ configurable: true,
1959
+ writable: true,
1960
+ value: false
1961
+ });
1904
1962
  /**
1905
1963
  * Whether the code being generated may write output to the stream. True
1906
1964
  * only in stream mode, for the template's own top-level output.
@@ -1921,6 +1979,7 @@ class Compiler extends Context {
1921
1979
  this.stylesheets = stylesheets;
1922
1980
  this.stylesheetKey = stylesheetKey;
1923
1981
  this.sources = sources;
1982
+ this.hasDynamicInclude = false;
1924
1983
  // Generate cache key from template and options
1925
1984
  const cacheKey = this.generateCacheKey(template);
1926
1985
  // Check cache first
@@ -1946,10 +2005,12 @@ class Compiler extends Context {
1946
2005
  }
1947
2006
  await this.parseTemplates();
1948
2007
  if (this.isRoot) {
1949
- if (this.partials.size) {
2008
+ if (this.partials.size || this.hasDynamicInclude) {
1950
2009
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1951
2010
  // Alias the render data before partials shadow `c` with their argument.
1952
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
2011
+ // `inc_` tracks `include … once` occurrences across the whole render,
2012
+ // root template and partials alike (they share this closure).
2013
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
1953
2014
  for (const [path, code] of this.partials) {
1954
2015
  this.pushRaw(null,
1955
2016
  // Partials take the context they should render with: plain include
@@ -2044,6 +2105,17 @@ class Compiler extends Context {
2044
2105
  }
2045
2106
  async parseTemplates() {
2046
2107
  const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
2108
+ if (this.isRoot) {
2109
+ for (const path of this.options.preloadIncludes) {
2110
+ if (!partials.has(path)) {
2111
+ partials.set(path, new IncludeNode({
2112
+ type: 'LIT',
2113
+ value: path,
2114
+ loc: PRELOAD_LOC,
2115
+ }, PRELOAD_LOC, { before: false, after: false }));
2116
+ }
2117
+ }
2118
+ }
2047
2119
  for (const [path, node] of partials) {
2048
2120
  if (!this.partials.has(path)) {
2049
2121
  let template;
@@ -2079,10 +2151,26 @@ class Compiler extends Context {
2079
2151
  const partials = new Map();
2080
2152
  const blocks = [];
2081
2153
  const stylesheets = [];
2154
+ const includeLast = new Map();
2082
2155
  const traverse = (node) => {
2083
2156
  if (node.type === 'INCLUDE') {
2084
- if (!partials.has(node.val.value)) {
2085
- partials.set(node.val.value, node);
2157
+ const include = node;
2158
+ if (isStringLit(include.val)) {
2159
+ if (!partials.has(include.val.value)) {
2160
+ partials.set(include.val.value, include);
2161
+ }
2162
+ if (include.modifier === 'last') {
2163
+ const existing = includeLast.get(include.val.value);
2164
+ if (existing) {
2165
+ existing.total += 1;
2166
+ }
2167
+ else {
2168
+ includeLast.set(include.val.value, { total: 1, emitted: 0 });
2169
+ }
2170
+ }
2171
+ }
2172
+ else {
2173
+ this.hasDynamicInclude = true;
2086
2174
  }
2087
2175
  }
2088
2176
  if (node.type === 'BLOCK') {
@@ -2094,6 +2182,7 @@ class Compiler extends Context {
2094
2182
  node.traverse(traverse);
2095
2183
  };
2096
2184
  traverse(this.rootNode);
2185
+ this.state.includeLast = includeLast;
2097
2186
  return {
2098
2187
  partials,
2099
2188
  blocks,
@@ -2493,6 +2582,7 @@ const compilerOptions = {
2493
2582
  trimWhitespace: false,
2494
2583
  stripComments: false,
2495
2584
  loader: async () => '',
2585
+ preloadIncludes: [],
2496
2586
  };
2497
2587
  const renderOptions = {
2498
2588
  ...compilerOptions,
@@ -3557,82 +3647,71 @@ const plugin$9 = {
3557
3647
  parsers: parsers$9,
3558
3648
  };
3559
3649
 
3560
- async function compileInclude({ val: { value }, loc, withExp }, compiler) {
3561
- const path = JSON.stringify(value);
3562
- if (withExp) {
3563
- const expCompiler = new ExpCompiler();
3564
- const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3565
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3650
+ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3651
+ const expCompiler = new ExpCompiler();
3652
+ const path = isStringLit(val)
3653
+ ? JSON.stringify(val.value)
3654
+ : expCompiler.compile(val, compiler.context);
3655
+ // Emit the partial call, against the top context for a plain include or a
3656
+ // merged scope for `include … with`.
3657
+ const emit = withExp
3658
+ ? `s+=await p[${path}]?.({...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}})??"";`
3659
+ : `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`;
3660
+ // `once`: render the first occurrence only. The registry lives in the root
3661
+ // script's closure, so occurrences spread across different files (a root
3662
+ // template and its partials) still deduplicate at runtime.
3663
+ if (modifier === 'once') {
3664
+ compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3566
3665
  return;
3567
3666
  }
3568
- // Plain include always sees the top-level context, not loop/with scopes.
3569
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`);
3667
+ // `last`: emit only at the final occurrence within the template file,
3668
+ // determined at compile time from the counts collected alongside partials.
3669
+ // Static string paths only — a dynamic path has no stable identity to count.
3670
+ if (modifier === 'last' && isStringLit(val)) {
3671
+ const counts = compiler.state.includeLast;
3672
+ const entry = counts?.get(val.value);
3673
+ if (entry) {
3674
+ entry.emitted += 1;
3675
+ if (entry.emitted < entry.total) {
3676
+ // Not the last occurrence — emit nothing.
3677
+ return;
3678
+ }
3679
+ }
3680
+ }
3681
+ compiler.pushRaw(loc, emit);
3570
3682
  }
3571
3683
  const compilers$8 = {
3572
3684
  INCLUDE: compileInclude,
3573
3685
  };
3574
3686
 
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
- }
3687
+ // Modifier keywords that may appear after the path expression.
3688
+ // e.g. `{{ include "foo" once }}` or `{{ include "foo" last }}`
3689
+ const MODIFIER_RE = /\s+(once|last)\s*$/;
3614
3690
  function* parseInclude(token, parser) {
3615
3691
  if (!token.expression) {
3616
3692
  parser.emitExpErr(token);
3617
3693
  return;
3618
3694
  }
3619
3695
  yield 'NEXT';
3620
- const exp = parser.parseExp(token.expression);
3696
+ // Strip a trailing `once` or `last` keyword before parsing the expression,
3697
+ // so the expression parser does not trip over an unknown identifier.
3698
+ let rawVal = token.expression.val;
3699
+ let modifier = null;
3700
+ const modifierMatch = MODIFIER_RE.exec(rawVal);
3701
+ if (modifierMatch) {
3702
+ modifier = modifierMatch[1];
3703
+ rawVal = rawVal.slice(0, modifierMatch.index);
3704
+ }
3705
+ const exp = parser.parseExp({ val: rawVal, loc: token.expression.loc });
3621
3706
  if (!exp) {
3622
3707
  return;
3623
3708
  }
3624
- if (isStringLit(exp)) {
3625
- yield new IncludeNode(exp, token.loc, token.strip);
3626
- return;
3627
- }
3628
3709
  if (exp.type === 'WITH') {
3629
3710
  const { left, right } = exp;
3630
- if (isStringLit(left)) {
3631
- yield new IncludeNode(left, token.loc, token.strip, right);
3632
- return;
3633
- }
3711
+ yield new IncludeNode(left, token.loc, token.strip, right, modifier);
3712
+ return;
3634
3713
  }
3635
- parser.options.debug?.(new CompileError('"include" expects "path" or "path" with expr', parser.template, token.loc));
3714
+ yield new IncludeNode(exp, token.loc, token.strip, null, modifier);
3636
3715
  }
3637
3716
  const parsers$8 = {
3638
3717
  include: parseInclude,
@@ -3913,14 +3992,18 @@ async function compileStylesheet() {
3913
3992
  async function compileStylesheets({ loc }, compiler) {
3914
3993
  compiler.pushRaw(loc,
3915
3994
  // 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>";', '}');
3995
+ // Bodies are emitted as-is — authors wrap CSS in `<style>` for IDE highlighting.
3996
+ 'if(!ss_u++){', 'for(const f_ of ss_)s+=await f_();', '}');
3917
3997
  }
3918
3998
  const compilers$4 = {
3919
3999
  STYLESHEET: compileStylesheet,
3920
4000
  STYLESHEETS: compileStylesheets,
3921
4001
  };
3922
4002
 
3923
- /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
4003
+ /**
4004
+ * Co-located styles with a section/snippet (Shopify `{% stylesheet %}` analogue).
4005
+ * Body is usually a `<style>…</style>` block for native IDE CSS highlighting.
4006
+ */
3924
4007
  class StylesheetNode extends Traversal {
3925
4008
  constructor(body, loc, strip) {
3926
4009
  super();
@@ -3950,7 +4033,7 @@ class StylesheetNode extends Traversal {
3950
4033
  });
3951
4034
  }
3952
4035
  }
3953
- /** Emits every collected stylesheet into the document (typically in `<head>`). */
4036
+ /** Concatenates collected stylesheet bodies into the document (typically in `<head>`). */
3954
4037
  class StylesheetsNode extends Traversal {
3955
4038
  constructor(loc, strip) {
3956
4039
  super();
@@ -4668,10 +4751,13 @@ class Analyzer {
4668
4751
  await this.nodes(node.body, scope);
4669
4752
  break;
4670
4753
  case 'INCLUDE':
4754
+ this.exp(node.val, scope);
4671
4755
  if (node.withExp) {
4672
4756
  this.exp(node.withExp, scope);
4673
4757
  }
4674
- await this.include(node.val.value, scope);
4758
+ if (node.val.type === 'LIT' && typeof node.val.value === 'string') {
4759
+ await this.include(node.val.value, scope);
4760
+ }
4675
4761
  break;
4676
4762
  default:
4677
4763
  await this.nodes(node.body, scope);
@@ -5436,6 +5522,149 @@ class ExpFormatter {
5436
5522
  }
5437
5523
  }
5438
5524
 
5525
+ /**
5526
+ * Brace-depth reindent for co-located CSS. Only leading whitespace changes;
5527
+ * braces inside strings/comments are ignored.
5528
+ */
5529
+ function indentCss(source, tabWidth) {
5530
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5531
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5532
+ const lines = source.split(/\r?\n/);
5533
+ let depth = 0;
5534
+ const out = [];
5535
+ for (const line of lines) {
5536
+ const content = line.trim();
5537
+ if (content.length === 0) {
5538
+ out.push('');
5539
+ continue;
5540
+ }
5541
+ const { opens, closes } = countCssBraces(content);
5542
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5543
+ out.push(pad.repeat(lineDepth) + content);
5544
+ depth = Math.max(0, depth + opens - closes);
5545
+ }
5546
+ return out.join(eol);
5547
+ }
5548
+ function countCssBraces(line) {
5549
+ let opens = 0;
5550
+ let closes = 0;
5551
+ let quote = null;
5552
+ let i = 0;
5553
+ while (i < line.length) {
5554
+ const c = line[i];
5555
+ if (quote) {
5556
+ if (c === '\\') {
5557
+ i += 2;
5558
+ continue;
5559
+ }
5560
+ if (c === quote) {
5561
+ quote = null;
5562
+ }
5563
+ i += 1;
5564
+ continue;
5565
+ }
5566
+ if (c === '"' || c === "'") {
5567
+ quote = c;
5568
+ i += 1;
5569
+ continue;
5570
+ }
5571
+ if (c === '/' && line[i + 1] === '*') {
5572
+ const end = line.indexOf('*/', i + 2);
5573
+ i = end === -1 ? line.length : end + 2;
5574
+ continue;
5575
+ }
5576
+ if (c === '/' && line[i + 1] === '/') {
5577
+ break;
5578
+ }
5579
+ if (c === '{') {
5580
+ opens += 1;
5581
+ }
5582
+ else if (c === '}') {
5583
+ closes += 1;
5584
+ }
5585
+ i += 1;
5586
+ }
5587
+ return { opens, closes };
5588
+ }
5589
+
5590
+ /**
5591
+ * Brace-depth reindent for `<script>` bodies. Only leading whitespace changes;
5592
+ * braces inside strings, comments, template literals, and Janja tags are ignored.
5593
+ */
5594
+ function indentJs(source, tabWidth) {
5595
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5596
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5597
+ const lines = source.split(/\r?\n/);
5598
+ let depth = 0;
5599
+ const out = [];
5600
+ for (const line of lines) {
5601
+ const content = line.trim();
5602
+ if (content.length === 0) {
5603
+ out.push('');
5604
+ continue;
5605
+ }
5606
+ const { opens, closes } = countJsBraces(content);
5607
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5608
+ out.push(pad.repeat(lineDepth) + content);
5609
+ depth = Math.max(0, depth + opens - closes);
5610
+ }
5611
+ return out.join(eol);
5612
+ }
5613
+ function countJsBraces(line) {
5614
+ let opens = 0;
5615
+ let closes = 0;
5616
+ let quote = null;
5617
+ let i = 0;
5618
+ while (i < line.length) {
5619
+ const c = line[i];
5620
+ if (quote) {
5621
+ if (c === '\\') {
5622
+ i += 2;
5623
+ continue;
5624
+ }
5625
+ if (c === quote) {
5626
+ quote = null;
5627
+ }
5628
+ i += 1;
5629
+ continue;
5630
+ }
5631
+ if (c === '{' && line[i + 1] === '{') {
5632
+ i = endOfJanja(line, i);
5633
+ continue;
5634
+ }
5635
+ if (c === '"' || c === "'" || c === '`') {
5636
+ quote = c;
5637
+ i += 1;
5638
+ continue;
5639
+ }
5640
+ if (c === '/' && line[i + 1] === '*') {
5641
+ const end = line.indexOf('*/', i + 2);
5642
+ i = end === -1 ? line.length : end + 2;
5643
+ continue;
5644
+ }
5645
+ if (c === '/' && line[i + 1] === '/') {
5646
+ break;
5647
+ }
5648
+ if (c === '{') {
5649
+ opens += 1;
5650
+ }
5651
+ else if (c === '}') {
5652
+ closes += 1;
5653
+ }
5654
+ i += 1;
5655
+ }
5656
+ return { opens, closes };
5657
+ }
5658
+ /** Skip a Janja tag starting at `i` (`{{`, `{{=`, `{{#` …). */
5659
+ function endOfJanja(line, i) {
5660
+ if (line.startsWith('{{#', i)) {
5661
+ const end = line.indexOf('#}}', i + 3);
5662
+ return end === -1 ? line.length : end + 3;
5663
+ }
5664
+ const end = line.indexOf('}}', i + 2);
5665
+ return end === -1 ? line.length : end + 2;
5666
+ }
5667
+
5439
5668
  /** HTML void elements — never take children, so they do not change indent. */
5440
5669
  const VOID = new Set([
5441
5670
  'area',
@@ -5453,8 +5682,13 @@ const VOID = new Set([
5453
5682
  'track',
5454
5683
  'wbr',
5455
5684
  ]);
5456
- /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5685
+ /**
5686
+ * Mark open/close so the body can be buffered. `pre` / `textarea` keep
5687
+ * whitespace; `script` / `style` are reindented (see body buffer below).
5688
+ */
5457
5689
  const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5690
+ /** HTML elements whose bodies are reindented (not left raw). */
5691
+ const REINDENT_HTML = new Set(['script', 'style']);
5458
5692
  const DIR_OPEN = new Set([
5459
5693
  'if',
5460
5694
  'for',
@@ -5481,8 +5715,9 @@ const DIR_CLOSE = new Set([
5481
5715
  /**
5482
5716
  * Reindent a template that already had its Janja tags normalised.
5483
5717
  * 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.
5718
+ * intra-line spacing stay put. Content inside pre/textarea is left alone;
5719
+ * `script` / `style` bodies are brace-reindented; `stylesheet` bodies are
5720
+ * formatted as an HTML fragment (so nested `<style>` gets CSS indent).
5486
5721
  */
5487
5722
  function indentHtml(source, options) {
5488
5723
  const tabWidth = options.tabWidth ?? 2;
@@ -5491,15 +5726,40 @@ function indentHtml(source, options) {
5491
5726
  const lines = source.split(/\r?\n/);
5492
5727
  let depth = 0;
5493
5728
  let sensitive = null;
5729
+ /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5730
+ let bodyBuf = null;
5494
5731
  const out = [];
5732
+ /** Open `{{#` comment: inner lines are never scanned for pieces. */
5733
+ const state = { inComment: false };
5495
5734
  for (const line of lines) {
5496
5735
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5497
5736
  const content = line.slice(leading);
5498
- const { pieces, prefixClosers } = scanLine(content, options);
5737
+ const { pieces, prefixClosers } = scanLine(content, options, state);
5499
5738
  const activeSensitive = sensitive;
5500
5739
  const closesSensitive = activeSensitive !== null &&
5501
5740
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5502
- if (sensitive && !closesSensitive) {
5741
+ const reindentBody = activeSensitive === 'stylesheet' ||
5742
+ (activeSensitive !== null && REINDENT_HTML.has(activeSensitive));
5743
+ if (reindentBody && !closesSensitive) {
5744
+ // Do not applyDepth: bodies may contain nested Janja if/for tags.
5745
+ (bodyBuf ?? (bodyBuf = [])).push(line);
5746
+ continue;
5747
+ }
5748
+ if (bodyBuf && closesSensitive && reindentBody) {
5749
+ // stylesheet: same column as the tags; script/style: one level inside.
5750
+ const baseDepth = activeSensitive === 'stylesheet' ? Math.max(0, depth - 1) : depth;
5751
+ const raw = bodyBuf.join(eol);
5752
+ const formatted = activeSensitive === 'stylesheet'
5753
+ ? indentHtml(raw, options)
5754
+ : activeSensitive === 'style'
5755
+ ? indentCss(raw, tabWidth)
5756
+ : indentJs(raw, tabWidth);
5757
+ for (const bodyLine of formatted.split(/\r?\n/)) {
5758
+ out.push(bodyLine.length === 0 ? '' : pad.repeat(baseDepth) + bodyLine);
5759
+ }
5760
+ bodyBuf = null;
5761
+ }
5762
+ else if (sensitive && !closesSensitive) {
5503
5763
  out.push(line);
5504
5764
  applyDepth(pieces);
5505
5765
  continue;
@@ -5530,16 +5790,35 @@ function indentHtml(source, options) {
5530
5790
  }
5531
5791
  }
5532
5792
  }
5533
- function scanLine(line, options) {
5793
+ function scanLine(line, options, state) {
5534
5794
  const pieces = [];
5535
5795
  let prefixClosers = 0;
5536
5796
  let atPrefix = true;
5537
5797
  let i = 0;
5798
+ if (state.inComment) {
5799
+ const close = line.indexOf(options.commentClose);
5800
+ if (close === -1) {
5801
+ return { pieces, prefixClosers };
5802
+ }
5803
+ state.inComment = false;
5804
+ i = close + options.commentClose.length;
5805
+ }
5538
5806
  while (i < line.length) {
5539
5807
  if (/\s/.test(line[i])) {
5540
5808
  i += 1;
5541
5809
  continue;
5542
5810
  }
5811
+ if (line.startsWith(options.commentOpen, i)) {
5812
+ const close = line.indexOf(options.commentClose, i + options.commentOpen.length);
5813
+ // Comment runs past this line; the rest is comment text
5814
+ if (close === -1) {
5815
+ state.inComment = true;
5816
+ return { pieces, prefixClosers };
5817
+ }
5818
+ atPrefix = false;
5819
+ i = close + options.commentClose.length;
5820
+ continue;
5821
+ }
5543
5822
  const next = readAt(line, i, options);
5544
5823
  if (!next) {
5545
5824
  // Plain text ends the leading-closer prefix
@@ -5566,12 +5845,7 @@ function scanLine(line, options) {
5566
5845
  return { pieces, prefixClosers };
5567
5846
  }
5568
5847
  function readAt(line, i, options) {
5569
- const { commentOpen, directiveOpen, outputOpen } = options;
5570
- if (line.startsWith(commentOpen, i)) {
5571
- return {
5572
- end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5573
- };
5574
- }
5848
+ const { directiveOpen, outputOpen } = options;
5575
5849
  if (line.startsWith(outputOpen, i)) {
5576
5850
  return {
5577
5851
  end: endOfDelimited(line, i + outputOpen.length, options.outputClose),